blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 4 201 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 7 100 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 260
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 11.4k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 17
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 80
values | src_encoding stringclasses 28
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 8 9.86M | extension stringclasses 52
values | content stringlengths 8 9.86M | authors listlengths 1 1 | author stringlengths 0 119 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ae317e57760c6592e01d4d0b16b3fc9b26e7a7cd | 31334b0618db6ad84f7f4d5e34c4283f1c33b07e | /RGB-IR_dodelat.ino | f5c07e57dd49101480c9562972acf506d67b7a11 | [] | no_license | NolimitL/AdruinoProjects | 568f96e2a24bac411b313060594c9a796c4c6466 | 1eeeb031de26b660c9ca16229608440c71be4720 | refs/heads/master | 2020-09-10T08:37:12.548739 | 2019-11-14T13:43:43 | 2019-11-14T13:43:43 | 221,704,525 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,508 | ino | #include <IRremote.h>
IRsend::Irsend(11); // Пин ИК-передатчика
decode_results results;
int regim=1; // Переменная режима кнопки
int flag=0;
void setup()
{
Serial.begin(9600); // Ставим скорость СОМ порта
irsend.enableIROut(); // Включаем передачу
pinMode(11, OUTPUT); // Это ИК-светодиод передатчик
pinMode(10, INPUT); // Пин кнопки
}
void loop()
{
if(digitalRead(10)==HIGH&&flag==0) // если кнопка нажата
// и перемення flag равна 0 , то ...
{
regim++;
flag=1;
//это нужно для того что бы с каждым нажатием кнопки
//происходило только одно действие
// плюс защита от "дребезга" 100%
if(regim>5)
{
regim = 1;
}
}
if(digitalRead(10)==LOW&&flag==1)//если кнопка НЕ нажата
//и переменная flag равна - 1 ,то ...
{
flag=0;//обнуляем переменную flag
}
if (regim==1)
{
irsend.sendNEC(result=1, 11);
}
if (regim==2)
{
digitalWrite(12, HIGH);
digitalWrite(13, LOW);
}
if (regim==3)
{
digitalWrite(11, HIGH);
digitalWrite(12, LOW);
}
if (regim==4)
{
digitalWrite(11, LOW);
}
}
| [
"noreply@github.com"
] | noreply@github.com |
678894fc0e5cfba68cd95d0fee8125699e48de65 | b3ff614159b3e0abedc7b6e9792b86145639994b | /dynamic-programming/general/a_question_of_ingestion.cpp | 49f036fdb073e651b85ed91d84d42f6e6b060548 | [] | no_license | s-nandi/contest-problems | 828b66e1ce4c9319033fdc78140dd2c240f40cd4 | d4caa7f19bf51794e4458f5a61c50f23594d50a7 | refs/heads/master | 2023-05-01T06:17:01.181487 | 2023-04-26T00:42:52 | 2023-04-26T00:42:52 | 113,280,133 | 0 | 0 | null | 2018-02-09T18:44:26 | 2017-12-06T06:51:11 | C++ | UTF-8 | C++ | false | false | 1,625 | cpp | // dp
// https://open.kattis.com/problems/ingestion
// 2017 East-Central NA Regional
#include <bits/stdc++.h>
using namespace std;
using vi = vector<int>;
using ll = long long;
using ld = long double;
using pii = pair<int, int>;
#define rep(i,a,b) for(auto i = (a); i < (b); ++i)
#define trav(a,x) for(auto& a: x)
#define all(a) begin(a),end(a)
#define sz(a) (int)size(a)
#define PB push_back
#define cauto const auto
struct edge{int to;};
using graph = vector<vector<edge>>;
constexpr auto dbg = true;
int32_t main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int n, m;
cin >> n >> m;
vi a(n);
trav(i, a) cin >> i;
vi amt(n + 1);
amt[0] = m;
rep(i, 1, n + 1) amt[i] = 2 * amt[i - 1] / 3;
constexpr auto INF = 1031231234;
auto dp = vector(n + 1, vector(n + 5, vector(2, -INF))); // dp[i][j][k] => considering course i (0 indexed), with max capacity amt[j],
// and k == 1 if a break was taken last move
// (might be k == 0 if j == 0 since it doesn't matter)
dp[0][0][0] = 0;
auto maxx = [](auto& a, auto b){a = max(a, b);};
rep(i, 0, n) {
rep(j, 0, n + 1) {
rep(k, 0, 2) {
if (k + 1 >= 2)
maxx(dp[i + 1][0][0], dp[i][j][k]);
else
maxx(dp[i + 1][max(0, j - 1)][k + 1], dp[i][j][k]);
auto delta = min(amt[j], a[i]);
maxx(dp[i + 1][j + 1][0], dp[i][j][k] + delta);
}
}
}
auto best = 0;
trav(row, dp.back()) trav(elem, row) maxx(best, elem);
cout << best << '\n';
}
| [
"noreply@github.com"
] | noreply@github.com |
44a425e2f1774330c4432a9f891b2a3b6f2d9f44 | 8caa570ec32fa20d01e55acefd2b933f16964421 | /online_judges/leetcode_oj/TextJustification/TextJustification/main.cpp | 54181c81f44c49a2f89106c98b2eb58ca4846693 | [] | no_license | zhenl010/zhenl010 | 50d37601e3f9a7f759d6563ef53e0df98ffca261 | f70065b153a8eb3dc357899158fe8011e4d93121 | refs/heads/master | 2020-04-18T10:16:53.980484 | 2013-06-05T16:11:47 | 2013-06-05T16:11:47 | 3,318,566 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,965 | cpp | #include <cassert>
#include <iostream>
#include <string>
#include <vector>
namespace {
//////////////////////////////////////////////////////////////////////////
using namespace std;
template <typename T, int N>
int ArraySize(const T (&a) [N]) { return N; }
class Solution {
public:
vector<string> fullJustify(vector<string> &words, int L) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<string> result;
vector<string> line;
int line_length = 0;
for (size_t i=0; i<words.size(); ++i) {
if (words[i].empty()) {
continue; // skip empty string
} else if (line.empty()) {
line = vector<string>(1, words[i]);
line_length = words[i].size();
} else if (line_length+words[i].size()+1 <= L) {
line.push_back(words[i]);
line_length += words[i].size()+1;
} else {
result.push_back(GetLineStringFull(line, line_length, L));
line = vector<string>(1, words[i]);
line_length = words[i].size();
}
}
if (!line.empty()) {
result.push_back(GetLineStringLeft(line, line_length, L));
}
return result.empty() ? vector<string>(1, string(L, ' ')) : result;
}
private:
// assemble justified line from words where line_length is calculated as
// sum(word lengths) + (number of words)
string GetLineStringFull(const vector<string> &line,
int line_length, int L) {
assert(!line.empty());
string str = line[0];
// special case to avoid divide by zero case
if (line.size()==1) return str + string(L-str.size(), ' ');
int long_space_num = (L-line_length) % (line.size()-1);
string delim(1+(L-line_length) / ((line.size()-1)), ' ');
for (size_t i=1; i<line.size(); ++i) {
if ((i-1)<long_space_num) {
str += (" " + delim + line[i]);
} else {
str += delim + line[i];
}
}
return str;
}
// assemble justified line from words where line_length is calculated as
// sum(word lengths) + (number of words)
string GetLineStringLeft(const vector<string> &line, int line_length, int L) {
assert(!line.empty());
string str = line[0];
for (size_t i=1; i<line.size(); ++i) {
str += (" " + line[i]);
}
return str + string(L-str.size(), ' ');
}
};
//////////////////////////////////////////////////////////////////////////
}
int main() {
Solution solver;
// int line_max = 0;
// int line_max = 1;
// int line_max = 3;
// int line_max = 12;
// int line_max = 6;
int line_max = 16;
string word_array[] = {
// ""
// "a"
// "a","b","c","d","e"
// "What","must","be","shall","be."
// "Listen","to","many,","speak","to","a","few."
"Here","is","an","example","of","text","justification."
};
vector<string> words(word_array, word_array+ArraySize(word_array));
vector<string> article = solver.fullJustify(words, line_max);
return 0;
} | [
"lv.zhen.g@gmail.com"
] | lv.zhen.g@gmail.com |
2587d004ac3155ff649182e22660406a240dd7f6 | a09ac3756172a5fd32e0f2ece904c6b8586b1195 | /examples/03-advanced/serialSAM/serialSAM.ino | 8b8a81638d26938fc166f7a3dcab20f65acc7493 | [] | no_license | sywxf/STM32SAM | 73991e8742ef76510d04b54bc62b084fca3c625f | 3488b85e0ee6b9ea65dfff5c1f1c0f4d667159d1 | refs/heads/master | 2022-11-29T08:19:15.909450 | 2020-07-21T16:33:06 | 2020-07-21T16:33:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,910 | ino |
/*
SCHEMATICS (not to scale) :
STM32F103C8/B - STM32F401CC - STM32F411CE - STM32F407VE :
.-------------------------------------.
| |
| STM32FxxxXXxx |
.-------------------------------------.
|G P|
|N A|
|D 8-----|R1|---+--|C2|-----------|
| | --
| C || P1
| 1 ||<----------------| OUDIO OUT
| | --
.-------------------------------------------+-----------------+------------------| GND
GND
R1 = 100-500 Ohm
C1 = 10-100 nF
C2 = 10 uF
P1 = 10KOhm potentiometer
HAVE FUN :-)
*/
#include <STM32SAM.h>
STM32SAM voice1; // start voice instance with default (5) speed
int pos = 0;
char line [256];
char c;
#define Print Serial1 // select serial port
void setup() {
// put your setup code here, to run once:
voice1.begin();
Print.begin(115200);
delay(1000);
Print.println ( "hello world, I am S T M 32 SAM, automated voice! ") ;
voice1.say ( "hello world, I am S T M 32 SAM, automated voice! ") ;
}
void loop() {
if (Print.available() > 0) {
c = (char)Print.read();
line[pos] = c;
if ((c == '\n') | (pos > 254) ) { // end of string or maximum number of chars?
pos = pos + 1; //
line[pos] = 0; // EOL
Print.println(line); // print back
voice1.say(line);// play
pos = 0; // reset position
}
else {
pos = pos + 1;
}
}
}
| [
"noreply@github.com"
] | noreply@github.com |
4b8df6c1ec3e6a5b4db3b225759f435c95a04a2a | f953e478ae95cabd6e5d813d309dd498f6158898 | /616/a.cpp | a544e8aeab5ed2247ebf5009cd590dee0380f6e6 | [] | no_license | geckods/CodeForces | da5b368dd62ba03bd96aadd30f124a388817fd43 | 6a75697a05d460c9593b3549b7ee001e116e3905 | refs/heads/master | 2021-04-19T14:21:22.102504 | 2020-08-14T07:05:48 | 2020-08-14T07:05:48 | 249,611,848 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,510 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int main(){
#ifndef ONLINE_JUDGE
freopen("input", "r", stdin);
freopen("output", "w", stdout);
freopen("error", "w", stderr);
#endif
ios_base::sync_with_stdio(false);
cin.tie(NULL);
ll t;
cin>>t;
while(t--){
ll n,m,k;
cin>>n>>m>>k;
ll arr[n];
for(int i=0;i<n;i++){
cin>>arr[i];
}
// ll minrange[n][n];//represents minimum in the range
// for (int i = 0; i < n; i++)
// minrange[i][i] = arr[i];
// for (int i=0; i<n; i++)
// {
// for (int j = i+1; j<n; j++)
// if (minrange[i][j - 1] < arr[j])
// minrange[i][j] = minrange[i][j - 1];
// else
// minrange[i][j] = arr[j];
// }
//for all orientations of k, check the min of the range that I may get
ll ans=INT_MIN;
ll minians;
for(int i=0;i<=min(k,m-1);i++){
minians=INT_MAX;
//i is the number of people that you persuade to take the left
//you persuade k-i people to take the right
//m-k-1 people are free
for(int j=0;j<=m-min(k,m-1)-1;j++){
// cout<<i<<" "<<j<<" "<<arr[i+j]<<" "<<arr[n-1-(k-i)-(m-k-1-j)]<<endl;
//number of free people who pick left
minians=min(minians,max(arr[i+j],arr[n-1-(k-i)-(m-k-1-j)]));
}
ans=max(ans,minians);
}
// if(ans==INT_MAX){
// ans=max()
// }
cout<<ans<<endl;
}
}
| [
"geckods@gmail.com"
] | geckods@gmail.com |
2594f7a3a1456b337d1c497590292bb0c36caf3c | cbd022378f8c657cef7f0d239707c0ac0b27118a | /src/server/bulkobjects/psquest.h | 97848dacae6dcdc094b2c4c86826c7409c3243aa | [] | no_license | randomcoding/PlaneShift-PSAI | 57d3c1a2accdef11d494c523f3e2e99142d213af | 06c585452abf960e0fc964fe0b7502b9bd550d1f | refs/heads/master | 2016-09-10T01:58:01.360365 | 2011-09-07T23:13:48 | 2011-09-07T23:13:48 | 2,336,981 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,939 | h | /*
* psquest.h
*
* Copyright (C) 2003 Atomic Blue (info@planeshift.it, http://www.atomicblue.org)
*
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation (version 2 of the License)
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
*/
#ifndef __PSQUEST_H__
#define __PSQUEST_H__
//=============================================================================
// Crystal Space Includes
//=============================================================================
#include <csutil/csstring.h>
#include <csutil/weakreferenced.h>
//=============================================================================
// Project Includes
//=============================================================================
#include <idal.h>
//=============================================================================
// Local Includes
//=============================================================================
using namespace CS;
#define QUEST_OPT_SAVEONCOMPLETE 0x01
/// The quest is disabled and won't be loaded by the server, used for the flags column
#define PSQUEST_DISABLED_QUEST 0x00000001
class psQuestPrereqOp;
class psCharacter;
class NpcTrigger;
class psQuest;
/**
* Utility function to parse prerequisite scripts.
*
* @param prerequisite The variable that will hold the parsed prerequisite
* @param self Pointer to the quest if used to load for a quest
* @param scripts The prerequisite to parse <pre>...</pre>.
* @return True if successfully parsed.
*/
bool LoadPrerequisiteXML(csRef<psQuestPrereqOp>& prerequisite, psQuest* self, csString script);
/**
* This class holds the master list of all quests available in the game.
*/
class psQuest : public CS::Utility::WeakReferenced
{
public:
psQuest();
virtual ~psQuest();
bool Load(iResultRow& row);
bool PostLoad();
void Init(int id, const char *name);
int GetID() const { return id; }
const char *GetName() const { return name; }
const char *GetImage() const { return image; }
const char *GetTask() const { return task; }
void SetTask(csString mytask) { task = mytask; }
psQuest *GetParentQuest() const { return parent_quest; }
void SetParentQuest(psQuest *parent) { parent_quest=parent; }
int GetStep() const { return step_id; }
bool HasInfinitePlayerLockout() const { return infinitePlayerLockout; }
unsigned int GetPlayerLockoutTime() const { return player_lockout_time; }
unsigned int GetQuestLockoutTime() const { return quest_lockout_time; }
unsigned int GetQuestLastActivatedTime() const { return quest_last_activated; }
void SetQuestLastActivatedTime(unsigned int when) { quest_last_activated=when; }
// csString QuestToXML() const;
bool AddPrerequisite(csString prerequisitescript);
bool AddPrerequisite(csRef<psQuestPrereqOp> op);
void AddTriggerResponse(NpcTrigger * trigger, int responseID);
void AddSubQuest(int id) { subquests.Push(id); }
/**
* @brief Return the prerequisite for this quest.
* @return The prerequisite for this quest.
*/
psQuestPrereqOp* GetPrerequisite() { return prerequisite; }
csString GetPrerequisiteStr();
const csString& GetCategory() const { return category; }
/**
* @brief Check if the quest is active (and also it's parents)
*
* A quest to be active must be active itself and, if so, also it's parents (most probably earlier steps)
* must be active themselves so check back to them if this quest is active else return as not active directly.
*
* @return The active status of the quest.
*/
bool Active() { return active ? (parent_quest ? parent_quest->Active() : active) : active; }
/**
* @brief Sets activation status of the quest
*/
void Active(bool state) { active = state; }
protected:
int id;
csString name;
csString task;
csString image;
int flags;
psQuest *parent_quest;
int step_id;
csRef<psQuestPrereqOp> prerequisite;
csString category;
csString prerequisiteStr;
bool infinitePlayerLockout;
unsigned int player_lockout_time;
unsigned int quest_lockout_time;
unsigned int quest_last_activated;
struct TriggerResponse
{
NpcTrigger * trigger;
int responseID;
};
csArray<TriggerResponse> triggerPairs;
csArray<int> subquests;
bool active;
};
#endif
| [
"whacko88@2752fbe2-5038-0410-9d0a-88578062bcef"
] | whacko88@2752fbe2-5038-0410-9d0a-88578062bcef |
624b3b161d4ee71d9822d60bdcb86e93937a77e1 | d496be05ef0aba263dd245d5d62170468652c3ec | /cpp/src/Manager.h | 8801e5fe26dcb17322eb2e5980f2dc5f14f0a6f3 | [] | no_license | wycc/openzwave-hsc48 | 61d162d2092ab1000f5795637d9fd3e6eb0f8e39 | 18f712468a899b96267de005b7533dde17dd5d5b | refs/heads/master | 2021-06-04T13:03:42.468644 | 2019-07-22T01:29:45 | 2019-07-22T01:29:45 | 8,784,786 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 103,207 | h | //-----------------------------------------------------------------------------
//
// Manager.h
//
// The main public interface to OpenZWave.
//
// Copyright (c) 2010 Mal Lansell <openzwave@lansell.org>
//
// SOFTWARE NOTICE AND LICENSE
//
// This file is part of OpenZWave.
//
// OpenZWave 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, either version 3 of the License,
// or (at your option) any later version.
//
// OpenZWave 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 OpenZWave. If not, see <http://www.gnu.org/licenses/>.
//
//-----------------------------------------------------------------------------
#ifndef _Manager_H
#define _Manager_H
#include <string>
#include <cstring>
#include <vector>
#include <map>
#include <list>
#include <deque>
#include "Defs.h"
#include "Driver.h"
#include "ValueID.h"
namespace OpenZWave
{
class Options;
class Node;
class Msg;
class Value;
class Event;
class Mutex;
class SerialPort;
class Thread;
class Notification;
class ValueBool;
class ValueByte;
class ValueDecimal;
class ValueInt;
class ValueList;
class ValueShort;
class ValueString;
class ValueRaw;
/** \brief
* The main public interface to OpenZWave.
*
* \nosubgrouping
* A singleton class providing the main public interface to OpenZWave.
* The Manager class exposes all the functionality required to add
* Z-Wave support to an application. It handles the sending and receiving
* of Z-Wave messages as well as the configuration of a Z-Wave network
* and its devices, freeing the library user from the burden of learning
* the low-level details of the Z-Wave protocol.
* <p>
* All Z-Wave functionality is accessed via the Manager class. While this
* does not make for the most efficient code structure, it does enable
* the library to handle potentially complex and hard-to-debug issues
* such as multi-threading and object lifespans behind the scenes.
* Application development is therefore simplified and less prone to bugs.
* <p>
* There can be only one instance of the Manager class, and all applications
* will start by calling Manager::Create static method to create that instance.
* From then on, a call to the Manager::Get static method will return the
* pointer to the Manager object. On application exit, Manager::Destroy
* should be called to allow OpenZWave to clean up and delete any other
* objects it has created.
* <p>
* Once the Manager has been created, a call should be made to Manager::AddWatcher
* to install a notification callback handler. This handler will receive
* notifications of Z-Wave network changes and updates to device values, and is
* an essential element of OpenZWave.
* <p>
* Next, a call should be made to Manager::AddDriver for each Z-Wave controller
* attached to the PC. Each Driver will handle the sending and receiving of
* messages for all the devices in its controller's Z-Wave network. The Driver
* will read any previously saved configuration and then query the Z-Wave controller
* for any missing information. Once that process is complete, a DriverReady
* notification callback will be sent containing the Home ID of the controller,
* which is required by most of the other Manager class methods.
* <p>
* [After the DriverReady notification is sent, the Driver will poll each node on
* the network to update information about each node. After all "awake" nodes
* have been polled, an "AllAwakeNodesQueried" notification is sent. This is when
* a client application can expect all of the node information (both static
* information, like the physical device's capabilities, session information
* (like [associations and/or names] and dynamic information (like temperature or
* on/off state) to be available. Finally, after all nodes (whether listening or
* sleeping) have been polled, an "AllNodesQueried" notification is sent.]
*/
class Manager
{
friend class Driver;
friend class CommandClass;
friend class Group;
friend class Node;
friend class Value;
friend class ValueStore;
friend class ValueButton;
public:
typedef void (*pfnOnNotification_t)( Notification const* _pNotification, void* _context );
//-----------------------------------------------------------------------------
// Construction
//-----------------------------------------------------------------------------
/** \name Construction
* For creating and destroying the Manager singleton.
*/
/*@{*/
public:
/**
* \brief Creates the Manager singleton object.
* The Manager provides the public interface to OpenZWave, exposing all the functionality required
* to add Z-Wave support to an application. There can be only one Manager in an OpenZWave application.
* An Options object must be created and Locked first, otherwise the call to Manager::Create will
* fail. Once the Manager has been created, call AddWatcher to install a notification callback handler,
* and then call the AddDriver method for each attached PC Z-Wave controller in turn.
* \param _options a locked Options object containing all the application's configurable option values.
* \return a pointer to the newly created Manager object, or NULL if creation failed.
* \see Options, Get, Destroy, AddWatcher, AddDriver
*/
static Manager* Create();
/**
* \brief Gets a pointer to the Manager object.
* \return pointer to the Manager object, or NULL if Create has not yet been called.
* \see Create, Destroy
*/
static Manager* Get(){ return s_instance; }
/**
* \brief Deletes the Manager and cleans up any associated objects.
* \see Create, Get
*/
static void Destroy();
/*@}*/
private:
Manager(); // Constructor, to be called only via the static Create method.
virtual ~Manager(); // Destructor, to be called only via the static Destroy method.
bool m_exit; // Flag indicating that program exit is in progress.
static Manager* s_instance; // Pointer to the instance of the Manager singleton.
//-----------------------------------------------------------------------------
// Configuration
//-----------------------------------------------------------------------------
/** \name Configuration
* For saving the Z-Wave network configuration so that the entire network does not need to be
* polled every time the application starts.
*/
/*@{*/
public:
/**
* \brief Saves the configuration of a PC Controller's Z-Wave network to the application's user data folder.
* This method does not normally need to be called, since OpenZWave will save the state automatically
* during the shutdown process. It is provided here only as an aid to development.
* The configuration of each PC Controller's Z-Wave network is stored in a separate file. The filename
* consists of the 8 digit hexadecimal version of the controller's Home ID, prefixed with the string 'zwcfg_'.
* This convention allows OpenZWave to find the correct configuration file for a controller, even if it is
* attached to a different serial port, USB device path, etc.
* \param _homeId The Home ID of the Z-Wave controller to save.
*/
void WriteConfig( uint32 const _homeId );
/**
* \brief Gets a pointer to the locked Options object.
* \return pointer to the Options object.
* \see Create
*/
Options* GetOptions()const{ return m_options; }
/*@}*/
private:
Options* m_options; // Pointer to the locked Options object that was passed in during creation.
//-----------------------------------------------------------------------------
// Drivers
//-----------------------------------------------------------------------------
/** \name Drivers
* Methods for adding and removing drivers and obtaining basic controller information.
*/
/*@{*/
public:
/**
* \brief Creates a new driver for a Z-Wave controller.
* This method creates a Driver object for handling communications with a single Z-Wave controller. In the background, the
* driver first tries to read configuration data saved during a previous run. It then queries the controller directly for any
* missing information, and a refresh of the list of nodes that it controls. Once this information
* has been received, a DriverReady notification callback is sent, containing the Home ID of the controller. This Home ID is
* required by most of the OpenZWave Manager class methods.
* @param _controllerPath The string used to open the controller. On Windows this might be something like
* "\\.\COM3", or on Linux "/dev/ttyUSB0".
* \return True if a new driver was created, false if a driver for the controller already exists.
* \see Create, Get, RemoveDriver
*/
bool AddDriver( string const& _controllerPath, Driver::ControllerInterface const& _interface = Driver::ControllerInterface_Serial);
/**
* \brief Removes the driver for a Z-Wave controller, and closes the controller.
* Drivers do not need to be explicitly removed before calling Destroy - this is handled automatically.
* @param _controllerPath The same string as was passed in the original call to AddDriver.
* @returns True if the driver was removed, false if it could not be found.
* @see Destroy, AddDriver
*/
bool RemoveDriver( string const& _controllerPath );
/**
* \brief Get the node ID of the Z-Wave controller.
* \param _homeId The Home ID of the Z-Wave controller.
* \return the node ID of the Z-Wave controller.
*/
uint8 GetControllerNodeId( uint32 const _homeId );
/**
* \brief Get the node ID of the Static Update Controller.
* \param _homeId The Home ID of the Z-Wave controller.
* \return the node ID of the Z-Wave controller.
*/
uint8 GetSUCNodeId( uint32 const _homeId );
/**
* \brief Query if the controller is a primary controller.
* The primary controller is the main device used to configure and control a Z-Wave network.
* There can only be one primary controller - all other controllers are secondary controllers.
* <p>
* The only difference between a primary and secondary controller is that the primary is the
* only one that can be used to add or remove other devices. For this reason, it is usually
* better for the promary controller to be portable, since most devices must be added when
* installed in their final location.
* <p>
* Calls to BeginControllerCommand will fail if the controller is not the primary.
* \param _homeId The Home ID of the Z-Wave controller.
* \return true if it is a primary controller, false if not.
*/
bool IsPrimaryController( uint32 const _homeId );
/**
* \brief Query if the controller is a static update controller.
* A Static Update Controller (SUC) is a controller that must never be moved in normal operation
* and which can be used by other nodes to receive information about network changes.
* \param _homeId The Home ID of the Z-Wave controller.
* \return true if it is a static update controller, false if not.
*/
bool IsStaticUpdateController( uint32 const _homeId );
/**
* \brief Query if the controller is using the bridge controller library.
* A bridge controller is able to create virtual nodes that can be associated
* with other controllers to enable events to be passed on.
* \param _homeId The Home ID of the Z-Wave controller.
* \return true if it is a bridge controller, false if not.
*/
bool IsBridgeController( uint32 const _homeId );
/**
* \brief Get the version of the Z-Wave API library used by a controller.
* \param _homeId The Home ID of the Z-Wave controller.
* \return a string containing the library version. For example, "Z-Wave 2.48".
*/
string GetLibraryVersion( uint32 const _homeId );
/**
* \brief Get a string containing the Z-Wave API library type used by a controller.
* The possible library types are:
* - Static Controller
* - Controller
* - Enhanced Slave
* - Slave
* - Installer
* - Routing Slave
* - Bridge Controller
* - Device Under Test
* The controller should never return a slave library type.
* For a more efficient test of whether a controller is a Bridge Controller, use
* the IsBridgeController method.
* \param _homeId The Home ID of the Z-Wave controller.
* \return a string containing the library type.
* \see GetLibraryVersion, IsBridgeController
*/
string GetLibraryTypeName( uint32 const _homeId );
/**
* \brief Get count of messages in the outgoing send queue.
* \param _homeId The Home ID of the Z-Wave controller.
* \return a integer message count
*/
int32 GetSendQueueCount( uint32 const _homeId );
/**
* \brief Send current driver statistics to the log file
* \param _homeId The Home ID of the Z-Wave controller.
*/
void LogDriverStatistics( uint32 const _homeId );
/**
* \brief Obtain controller interface type
* \param _homeId The Home ID of the Z-Wave controller.
*/
Driver::ControllerInterface GetControllerInterfaceType( uint32 const _homeId );
/**
* \brief Obtain controller interface name
* \param _homeId The Home ID of the Z-Wave controller.
*/
string GetControllerPath( uint32 const _homeId );
/**
* \brief Get the endpoint of the value object
* \param _homeId The Home ID of the Z-Wave controller.
* \param v The ValueID of the Value object
*/
int GetEndPoint(uint32 const _homeId,OpenZWave::ValueID* v);
/*@}*/
private:
Driver* GetDriver( uint32 const _homeId ); /**< Get a pointer to a Driver object from the HomeID. Only to be used by OpenZWave. */
void SetDriverReady( Driver* _driver, bool success ); /**< Indicate that the Driver is ready to be used, and send the notification callback. */
list<Driver*> m_pendingDrivers; /**< Drivers that are in the process of reading saved data and querying their Z-Wave network for basic information. */
map<uint32,Driver*> m_readyDrivers; /**< Drivers that are ready to be used by the application. */
//-----------------------------------------------------------------------------
// Polling Z-Wave devices
//-----------------------------------------------------------------------------
/** \name Polling Z-Wave devices
* Methods for controlling the polling of Z-Wave devices. Modern devices will not
* require polling. Some old devices need to be polled as the only way to detect
* status changes.
*/
/*@{*/
public:
/**
* \brief Get the time period between polls of a node's state.
*/
int32 GetPollInterval();
/**
* \brief Set the time period between polls of a node's state.
* Due to patent concerns, some devices do not report state changes automatically to the controller.
* These devices need to have their state polled at regular intervals. The length of the interval
* is the same for all devices. To even out the Z-Wave network traffic generated by polling, OpenZWave
* divides the polling interval by the number of devices that have polling enabled, and polls each
* in turn. It is recommended that if possible, the interval should not be set shorter than the
* number of polled devices in seconds (so that the network does not have to cope with more than one
* poll per second).
* \param _seconds The length of the polling interval in seconds.
*/
void SetPollInterval( int32 _milliseconds, bool _bIntervalBetweenPolls );
/**
* \brief Enable the polling of a device's state.
* \param _valueId The ID of the value to start polling.
* \return True if polling was enabled.
*/
bool EnablePoll( ValueID const _valueId, uint8 const _intensity = 1 );
/**
* \brief Disable the polling of a device's state.
* \param _valueId The ID of the value to stop polling.
* \return True if polling was disabled.
*/
bool DisablePoll( ValueID const _valueId );
/**
* \brief Determine the polling of a device's state.
* \param _valueId The ID of the value to check polling.
* \return True if polling is active.
*/
bool isPolled( ValueID const _valueId );
/**
* \brief Set the frequency of polling (0=none, 1=every time through the list, 2-every other time, etc)
* \param _valueId The ID of the value whose intensity should be set
*/
void SetPollIntensity( ValueID const _valueId, uint8 const _intensity );
/**
* \brief Get the polling intensity of a device's state.
* \param _valueId The ID of the value to check polling.
* \return Intensity, number of polling for one polling interval.
*/
uint8 GetPollIntensity( ValueID const _valueId );
/*@}*/
//-----------------------------------------------------------------------------
// Node information
//-----------------------------------------------------------------------------
/** \name Node information
* Methods for accessing information on indivdual nodes.
*/
/*@{*/
public:
/**
* \brief Trigger the fetching of fixed data about a node.
* Causes the node's data to be obtained from the Z-Wave network in the same way as if it had just been added.
* This method would normally be called automatically by OpenZWave, but if you know that a node has been
* changed, calling this method will force a refresh of all of the data held by the library. This can be especially
* useful for devices that were asleep when the application was first run. This is the
* same as the query state starting from the beginning.
* \param _homeId The Home ID of the Z-Wave controller that manages the node.
* \param _nodeId The ID of the node to query.
* \return True if the request was sent successfully.
*/
bool RefreshNodeInfo( uint32 const _homeId, uint8 const _nodeId );
/**
* \brief Trigger the fetching of dynamic value data for a node.
* Causes the node's values to be requested from the Z-Wave network. This is the
* same as the query state starting from the associations state.
* \param _homeId The Home ID of the Z-Wave controller that manages the node.
* \param _nodeId The ID of the node to query.
* \return True if the request was sent successfully.
*/
bool RequestNodeState( uint32 const _homeId, uint8 const _nodeId );
/**
* \brief Trigger the fetching of just the dynamic value data for a node.
* Causes the node's values to be requested from the Z-Wave network. This is the
* same as the query state starting from the dynamic state.
* \param _homeId The Home ID of the Z-Wave controller that manages the node.
* \param _nodeId The ID of the node to query.
* \return True if the request was sent successfully.
*/
bool RequestNodeDynamic( uint32 const _homeId, uint8 const _nodeId );
/**
* \brief Get whether the node is a listening device that does not go to sleep
* \param _homeId The Home ID of the Z-Wave controller that manages the node.
* \param _nodeId The ID of the node to query.
* \return True if it is a listening node.
*/
bool IsNodeListeningDevice( uint32 const _homeId, uint8 const _nodeId );
/**
* \brief Get whether the node is a frequent listening device that goes to sleep but
* can be woken up by a beam. Useful to determine node and controller consistency.
* \param _homeId The Home ID of the Z-Wave controller that manages the node.
* \param _nodeId The ID of the node to query.
* \return True if it is a frequent listening node.
*/
bool IsNodeFrequentListeningDevice( uint32 const _homeId, uint8 const _nodeId );
/**
* \brief Get whether the node is a beam capable device.
* \param _homeId The Home ID of the Z-Wave controller that manages the node.
* \param _nodeId The ID of the node to query.
* \return True if it is a beam capable node.
*/
bool IsNodeBeamingDevice( uint32 const _homeId, uint8 const _nodeId );
/**
* \brief Get whether the node is a routing device that passes messages to other nodes
* \param _homeId The Home ID of the Z-Wave controller that manages the node.
* \param _nodeId The ID of the node to query.
* \return True if the node is a routing device
*/
bool IsNodeRoutingDevice( uint32 const _homeId, uint8 const _nodeId );
/**
* \brief Get the security attribute for a node. True if node supports security features.
* \param _homeId The Home ID of the Z-Wave controller that manages the node.
* \param _nodeId The ID of the node to query.
* \return true if security features implemented.
*/
bool IsNodeSecurityDevice( uint32 const _homeId, uint8 const _nodeId );
/**
* \brief Get the maximum baud rate of a node's communications
* \param _homeId The Home ID of the Z-Wave controller that manages the node.
* \param _nodeId The ID of the node to query.
* \return the baud rate in bits per second.
*/
uint32 GetNodeMaxBaudRate( uint32 const _homeId, uint8 const _nodeId );
/**
* \brief Get the version number of a node
* \param _homeId The Home ID of the Z-Wave controller that manages the node.
* \param _nodeId The ID of the node to query.
* \return the node's version number
*/
uint8 GetNodeVersion( uint32 const _homeId, uint8 const _nodeId );
/**
* \brief Get the security byte of a node
* \param _homeId The Home ID of the Z-Wave controller that manages the node.
* \param _nodeId The ID of the node to query.
* \return the node's security byte
*/
uint8 GetNodeSecurity( uint32 const _homeId, uint8 const _nodeId );
/**
* \brief Get the basic type of a node.
* \param _homeId The Home ID of the Z-Wave controller that manages the node.
* \param _nodeId The ID of the node to query.
* \return the node's basic type.
*/
uint8 GetNodeBasic( uint32 const _homeId, uint8 const _nodeId );
/**
* \brief Get the generic type of a node.
* \param _homeId The Home ID of the Z-Wave controller that manages the node.
* \param _nodeId The ID of the node to query.
* \return the node's generic type.
*/
uint8 GetNodeGeneric( uint32 const _homeId, uint8 const _nodeId );
/**
* \brief Get the specific type of a node.
* \param _homeId The Home ID of the Z-Wave controller that manages the node.
* \param _nodeId The ID of the node to query.
* \return the node's specific type.
*/
uint8 GetNodeSpecific( uint32 const _homeId, uint8 const _nodeId );
/**
* \brief Get a human-readable label describing the node
* The label is taken from the Z-Wave specific, generic or basic type, depending on which of those values are specified by the node.
* \param _homeId The Home ID of the Z-Wave controller that manages the node.
* \param _nodeId The ID of the node to query.
* \return A string containing the label text.
*/
string GetNodeType( uint32 const _homeId, uint8 const _nodeId );
/**
* \brief Get the bitmap of this node's neighbors
*
* \param _homeId The Home ID of the Z-Wave controller that manages the node.
* \param _nodeId The ID of the node to query.
* \param _nodeNeighbors An array of 29 uint8s to hold the neighbor bitmap
*/
uint32 GetNodeNeighbors( uint32 const _homeId, uint8 const _nodeId, uint8** _nodeNeighbors );
/**
* \brief Get the manufacturer name of a device
* The manufacturer name would normally be handled by the Manufacturer Specific commmand class,
* taking the manufacturer ID reported by the device and using it to look up the name from the
* manufacturer_specific.xml file in the OpenZWave config folder.
* However, there are some devices that do not support the command class, so to enable the user
* to manually set the name, it is stored with the node data and accessed via this method rather
* than being reported via a command class Value object.
* \param _homeId The Home ID of the Z-Wave controller that manages the node.
* \param _nodeId The ID of the node to query.
* \return A string containing the node's manufacturer name.
* \see SetNodeManufacturerName, GetNodeProductName, SetNodeProductName
*/
string GetNodeManufacturerName( uint32 const _homeId, uint8 const _nodeId );
/**
* \brief Get the product name of a device
* The product name would normally be handled by the Manufacturer Specific commmand class,
* taking the product Type and ID reported by the device and using it to look up the name from the
* manufacturer_specific.xml file in the OpenZWave config folder.
* However, there are some devices that do not support the command class, so to enable the user
* to manually set the name, it is stored with the node data and accessed via this method rather
* than being reported via a command class Value object.
* \param _homeId The Home ID of the Z-Wave controller that manages the node.
* \param _nodeId The ID of the node to query.
* \return A string containing the node's product name.
* \see SetNodeProductName, GetNodeManufacturerName, SetNodeManufacturerName
*/
string GetNodeProductName( uint32 const _homeId, uint8 const _nodeId );
/**
* \brief Get the name of a node
* The node name is a user-editable label for the node that would normally be handled by the
* Node Naming commmand class, but many devices do not support it. So that a node can always
* be named, OpenZWave stores it with the node data, and provides access through this method
* and SetNodeName, rather than reporting it via a command class Value object.
* The maximum length of a node name is 16 characters.
* \param _homeId The Home ID of the Z-Wave controller that manages the node.
* \param _nodeId The ID of the node to query.
* \return A string containing the node's name.
* \see SetNodeName, GetNodeLocation, SetNodeLocation
*/
string GetNodeName( uint32 const _homeId, uint8 const _nodeId );
/**
* \brief Get the location of a node
* The node location is a user-editable string that would normally be handled by the Node Naming
* commmand class, but many devices do not support it. So that a node can always report its
* location, OpenZWave stores it with the node data, and provides access through this method
* and SetNodeLocation, rather than reporting it via a command class Value object.
* \param _homeId The Home ID of the Z-Wave controller that manages the node.
* \param _nodeId The ID of the node to query.
* \return A string containing the node's location.
* \see SetNodeLocation, GetNodeName, SetNodeName
*/
string GetNodeLocation( uint32 const _homeId, uint8 const _nodeId );
/**
* \brief Get the manufacturer ID of a device
* The manufacturer ID is a four digit hex code and would normally be handled by the Manufacturer
* Specific commmand class, but not all devices support it. Although the value reported by this
* method will be an empty string if the command class is not supported and cannot be set by the
* user, the manufacturer ID is still stored with the node data (rather than being reported via a
* command class Value object) to retain a consistent approach with the other manufacturer specific data.
* \param _homeId The Home ID of the Z-Wave controller that manages the node.
* \param _nodeId The ID of the node to query.
* \return A string containing the node's manufacturer ID, or an empty string if the manufactuer
* specific command class is not supported by the device.
* \see GetNodeProductType, GetNodeProductId, GetNodeManufacturerName, GetNodeProductName
*/
string GetNodeManufacturerId( uint32 const _homeId, uint8 const _nodeId );
/**
* \brief Get the product type of a device
* The product type is a four digit hex code and would normally be handled by the Manufacturer Specific
* commmand class, but not all devices support it. Although the value reported by this method will
* be an empty string if the command class is not supported and cannot be set by the user, the product
* type is still stored with the node data (rather than being reported via a command class Value object)
* to retain a consistent approach with the other manufacturer specific data.
* \param _homeId The Home ID of the Z-Wave controller that manages the node.
* \param _nodeId The ID of the node to query.
* \return A string containing the node's product type, or an empty string if the manufactuer
* specific command class is not supported by the device.
* \see GetNodeManufacturerId, GetNodeProductId, GetNodeManufacturerName, GetNodeProductName
*/
string GetNodeProductType( uint32 const _homeId, uint8 const _nodeId );
/**
* \brief Get the product ID of a device
* The product ID is a four digit hex code and would normally be handled by the Manufacturer Specific
* commmand class, but not all devices support it. Although the value reported by this method will
* be an empty string if the command class is not supported and cannot be set by the user, the product
* ID is still stored with the node data (rather than being reported via a command class Value object)
* to retain a consistent approach with the other manufacturer specific data.
* \param _homeId The Home ID of the Z-Wave controller that manages the node.
* \param _nodeId The ID of the node to query.
* \return A string containing the node's product ID, or an empty string if the manufactuer
* specific command class is not supported by the device.
* \see GetNodeManufacturerId, GetNodeProductType, GetNodeManufacturerName, GetNodeProductName
*/
string GetNodeProductId( uint32 const _homeId, uint8 const _nodeId );
/**
* \brief Set the manufacturer name of a device
* The manufacturer name would normally be handled by the Manufacturer Specific commmand class,
* taking the manufacturer ID reported by the device and using it to look up the name from the
* manufacturer_specific.xml file in the OpenZWave config folder.
* However, there are some devices that do not support the command class, so to enable the user
* to manually set the name, it is stored with the node data and accessed via this method rather
* than being reported via a command class Value object.
* \param _homeId The Home ID of the Z-Wave controller that manages the node.
* \param _nodeId The ID of the node to query.
* \param _manufacturerName A string containing the node's manufacturer name.
* \see GetNodeManufacturerName, GetNodeProductName, SetNodeProductName
*/
void SetNodeManufacturerName( uint32 const _homeId, uint8 const _nodeId, string const& _manufacturerName );
/**
* \brief Set the product name of a device
* The product name would normally be handled by the Manufacturer Specific commmand class,
* taking the product Type and ID reported by the device and using it to look up the name from the
* manufacturer_specific.xml file in the OpenZWave config folder.
* However, there are some devices that do not support the command class, so to enable the user
* to manually set the name, it is stored with the node data and accessed via this method rather
* than being reported via a command class Value object.
* \param _homeId The Home ID of the Z-Wave controller that manages the node.
* \param _nodeId The ID of the node to query.
* \param _productName A string containing the node's product name.
* \see GetNodeProductName, GetNodeManufacturerName, SetNodeManufacturerName
*/
void SetNodeProductName( uint32 const _homeId, uint8 const _nodeId, string const& _productName );
/**
* \brief Set the name of a node
* The node name is a user-editable label for the node that would normally be handled by the
* Node Naming commmand class, but many devices do not support it. So that a node can always
* be named, OpenZWave stores it with the node data, and provides access through this method
* and GetNodeName, rather than reporting it via a command class Value object.
* If the device does support the Node Naming command class, the new name will be sent to the node.
* The maximum length of a node name is 16 characters.
* \param _homeId The Home ID of the Z-Wave controller that manages the node.
* \param _nodeId The ID of the node to query.
* \param _nodeName A string containing the node's name.
* \see GetNodeName, GetNodeLocation, SetNodeLocation
*/
void SetNodeName( uint32 const _homeId, uint8 const _nodeId, string const& _nodeName );
/**
* \brief Set the location of a node
* The node location is a user-editable string that would normally be handled by the Node Naming
* commmand class, but many devices do not support it. So that a node can always report its
* location, OpenZWave stores it with the node data, and provides access through this method
* and GetNodeLocation, rather than reporting it via a command class Value object.
* If the device does support the Node Naming command class, the new location will be sent to the node.
* \param _homeId The Home ID of the Z-Wave controller that manages the node.
* \param _nodeId The ID of the node to query.
* \param _location A string containing the node's location.
* \see GetNodeLocation, GetNodeName, SetNodeName
*/
void SetNodeLocation( uint32 const _homeId, uint8 const _nodeId, string const& _location );
/**
* \brief Turns a node on
* This is a helper method to simplify basic control of a node. It is the equivalent of
* changing the level reported by the node's Basic command class to 255, and will generate a
* ValueChanged notification from that class. This command will turn on the device at its
* last known level, if supported by the device, otherwise it will turn it on at 100%.
* \param _homeId The Home ID of the Z-Wave controller that manages the node.
* \param _nodeId The ID of the node to be changed.
* \see SetNodeOff, SetNodeLevel
*/
void SetNodeOn( uint32 const _homeId, uint8 const _nodeId );
/**
* \brief Turns a node off
* This is a helper method to simplify basic control of a node. It is the equivalent of
* changing the level reported by the node's Basic command class to zero, and will generate
* a ValueChanged notification from that class.
* \param _homeId The Home ID of the Z-Wave controller that manages the node.
* \param _nodeId The ID of the node to be changed.
* \see SetNodeOn, SetNodeLevel
*/
void SetNodeOff( uint32 const _homeId, uint8 const _nodeId );
/**
* \brief Sets the basic level of a node
* This is a helper method to simplify basic control of a node. It is the equivalent of
* changing the value reported by the node's Basic command class and will generate a
* ValueChanged notification from that class.
* \param _homeId The Home ID of the Z-Wave controller that manages the node.
* \param _nodeId The ID of the node to be changed.
* \param _level The level to set the node. Valid values are 0-99 and 255. Zero is off and
* 99 is fully on. 255 will turn on the device at its last known level (if supported).
* \see SetNodeOn, SetNodeOff
*/
void SetNodeLevel( uint32 const _homeId, uint8 const _nodeId, uint8 const _level );
/**
* \brief Get whether the node information has been received
* \param _homeId The Home ID of the Z-Wave controller that manages the node.
* \param _nodeId The ID of the node to query.
* \return True if the node information has been received yet
*/
bool IsNodeInfoReceived( uint32 const _homeId, uint8 const _nodeId );
/**
* \brief Get whether the node has the defined class available or not
* \param _homeId The Home ID of the Z-Wave controller that manages the node.
* \param _nodeId The ID of the node to query.
* \param _commandClassId Id of the class to test for
* \return True if the node does have the class instantiated, will return name & version
*/
bool GetNodeClassInformation( uint32 const _homeId, uint8 const _nodeId, uint8 const _commandClassId,
string *_className = NULL, uint8 *_classVersion = NULL);
/**
* \brief Get whether the node is awake or asleep
* \param _homeId The Home ID of the Z-Wave controller that manages the node.
* \param _nodeId The ID of the node to query.
* \return True if the node is awake
*/
bool IsNodeAwake( uint32 const _homeId, uint8 const _nodeId );
/**
* \brief Get whether the node is working or has failed
* \param _homeId The Home ID of the Z-Wave controller that manages the node.
* \param _nodeId The ID of the node to query.
* \return True if the node has failed and is no longer part of the network
*/
bool IsNodeFailed( uint32 const _homeId, uint8 const _nodeId );
/**
* \brief Get whether the node's query stage as a string
* \param _homeId The Home ID of the Z-Wave controller that manages the node.
* \param _nodeId The ID of the node to query.
* \return name of current query stage as a string.
*/
string GetNodeQueryStage( uint32 const _homeId, uint8 const _nodeId );
/*@}*/
//-----------------------------------------------------------------------------
// Values
//-----------------------------------------------------------------------------
/** \name Values
* Methods for accessing device values. All the methods require a ValueID, which will have been provided
* in the ValueAdded Notification callback when the the value was first discovered by OpenZWave.
*/
/*@{*/
public:
/**
* \brief Gets the user-friendly label for the value.
* \param _id The unique identifier of the value.
* \return The value label.
* \see ValueID
*/
string GetValueLabel( ValueID const& _id );
/**
* \brief Sets the user-friendly label for the value.
* \param _id The unique identifier of the value.
* \param _value The new value of the label.
* \see ValueID
*/
void SetValueLabel( ValueID const& _id, string const& _value );
/**
* \brief Gets the units that the value is measured in.
* \param _id The unique identifier of the value.
* \return The value units.
* \see ValueID
*/
string GetValueUnits( ValueID const& _id );
/**
* \brief Sets the units that the value is measured in.
* \param _id The unique identifier of the value.
* \param _value The new value of the units.
* \see ValueID
*/
void SetValueUnits( ValueID const& _id, string const& _value );
/**
* \brief Gets a help string describing the value's purpose and usage.
* \param _id The unique identifier of the value.
* \return The value help text.
* \see ValueID
*/
string GetValueHelp( ValueID const& _id );
/**
* \brief Sets a help string describing the value's purpose and usage.
* \param _id The unique identifier of the value.
* \param _value The new value of the help text.
* \see ValueID
*/
void SetValueHelp( ValueID const& _id, string const& _value );
/**
* \brief Gets the minimum that this value may contain.
* \param _id The unique identifier of the value.
* \return The value minimum.
* \see ValueID
*/
int32 GetValueMin( ValueID const& _id );
/**
* \brief Gets the maximum that this value may contain.
* \param _id The unique identifier of the value.
* \return The value maximum.
* \see ValueID
*/
int32 GetValueMax( ValueID const& _id );
/**
* \brief Test whether the value is read-only.
* \param _id The unique identifier of the value.
* \return true if the value cannot be changed by the user.
* \see ValueID
*/
bool IsValueReadOnly( ValueID const& _id );
/**
* \brief Test whether the value is write-only.
* \param _id The unique identifier of the value.
* \return true if the value can only be written to and not read.
* \see ValueID
*/
bool IsValueWriteOnly( ValueID const& _id );
/**
* \brief Test whether the value has been set.
* \param _id The unique identifier of the value.
* \return true if the value has actually been set by a status message from the device, rather than simply being the default.
* \see ValueID
*/
bool IsValueSet( ValueID const& _id );
/**
* \brief Test whether the value is currently being polled.
* \param _id The unique identifier of the value.
* \return true if the value is being polled, otherwise false.
* \see ValueID
*/
bool IsValuePolled( ValueID const& _id );
/**
* \brief Gets a value as a bool.
* \param _id The unique identifier of the value.
* \param o_value Pointer to a bool that will be filled with the value.
* \return true if the value was obtained. Returns false if the value is not a ValueID::ValueType_Bool. The type can be tested with a call to ValueID::GetType.
* \see ValueID::GetType, GetValueAsByte, GetValueAsFloat, GetValueAsInt, GetValueAsShort, GetValueAsString, GetValueListSelection, GetValueListItems, GetValueAsRaw
*/
bool GetValueAsBool( ValueID const& _id, bool* o_value );
/**
* \brief Gets a value as an 8-bit unsigned integer.
* \param _id The unique identifier of the value.
* \param o_value Pointer to a uint8 that will be filled with the value.
* \return true if the value was obtained. Returns false if the value is not a ValueID::ValueType_Byte. The type can be tested with a call to ValueID::GetType
* \see ValueID::GetType, GetValueAsBool, GetValueAsFloat, GetValueAsInt, GetValueAsShort, GetValueAsString, GetValueListSelection, GetValueListItems, GetValueAsRaw
*/
bool GetValueAsByte( ValueID const& _id, uint8* o_value );
/**
* \brief Gets a value as a float.
* \param _id The unique identifier of the value.
* \param o_value Pointer to a float that will be filled with the value.
* \return true if the value was obtained. Returns false if the value is not a ValueID::ValueType_Decimal. The type can be tested with a call to ValueID::GetType
* \see ValueID::GetType, GetValueAsBool, GetValueAsByte, GetValueAsInt, GetValueAsShort, GetValueAsString, GetValueListSelection, GetValueListItems, GetValueAsRaw
*/
bool GetValueAsFloat( ValueID const& _id, float* o_value );
/**
* \brief Gets a value as a 32-bit signed integer.
* \param _id The unique identifier of the value.
* \param o_value Pointer to an int32 that will be filled with the value.
* \return true if the value was obtained. Returns false if the value is not a ValueID::ValueType_Int. The type can be tested with a call to ValueID::GetType
* \see ValueID::GetType, GetValueAsBool, GetValueAsByte, GetValueAsFloat, GetValueAsShort, GetValueAsString, GetValueListSelection, GetValueListItems, GetValueAsRaw
*/
bool GetValueAsInt( ValueID const& _id, int32* o_value );
/**
* \brief Gets a value as a 16-bit signed integer.
* \param _id The unique identifier of the value.
* \param o_value Pointer to an int16 that will be filled with the value.
* \return true if the value was obtained. Returns false if the value is not a ValueID::ValueType_Short. The type can be tested with a call to ValueID::GetType.
* \see ValueID::GetType, GetValueAsBool, GetValueAsByte, GetValueAsFloat, GetValueAsInt, GetValueAsString, GetValueListSelection, GetValueListItems, GetValueAsRaw
*/
bool GetValueAsShort( ValueID const& _id, int16* o_value );
/**
* \brief Gets a value as a string.
* Creates a string representation of a value, regardless of type.
* \param _id The unique identifier of the value.
* \param o_value Pointer to a string that will be filled with the value.
* \return true if the value was obtained.</returns>
* \see ValueID::GetType, GetValueAsBool, GetValueAsByte, GetValueAsFloat, GetValueAsInt, GetValueAsShort, GetValueListSelection, GetValueListItems, GetValueAsRaw
*/
bool GetValueAsString( ValueID const& _id, string* o_value );
/**
* \brief Gets a value as a collection of bytes.
* \param _id The unique identifier of the value.
* \param o_value Pointer to a uint8* that will be filled with the value. This return value will need to be freed as it was dynamically allocated.
* \param o_length Pointer to a uint8 that will be fill with the data length.
* \return true if the value was obtained. Returns false if the value is not a ValueID::ValueType_Raw. The type can be tested with a call to ValueID::GetType.
* \see ValueID::GetType, GetValueAsBool, GetValueAsByte, GetValueAsFloat, GetValueAsInt, GetValueAsShort, GetValueListSelection, GetValueListItems, GetValueAsRaw
*/
bool GetValueAsRaw( ValueID const& _id, uint8** o_value, uint8* o_length );
/**
* \brief Gets the selected item from a list (as a string).
* \param _id The unique identifier of the value.
* \param o_value Pointer to a string that will be filled with the selected item.
* \return True if the value was obtained. Returns false if the value is not a ValueID::ValueType_List. The type can be tested with a call to ValueID::GetType.
* \see ValueID::GetType, GetValueAsBool, GetValueAsByte, GetValueAsFloat, GetValueAsInt, GetValueAsShort, GetValueAsString, GetValueListItems, GetValueAsRaw
*/
bool GetValueListSelection( ValueID const& _id, string* o_value );
/**
* \brief Gets the selected item from a list (as an integer).
* \param _id The unique identifier of the value.
* \param o_value Pointer to an integer that will be filled with the selected item.
* \return True if the value was obtained. Returns false if the value is not a ValueID::ValueType_List. The type can be tested with a call to ValueID::GetType.
* \see ValueID::GetType, GetValueAsBool, GetValueAsByte, GetValueAsFloat, GetValueAsInt, GetValueAsShort, GetValueAsString, GetValueListItems, GetValueAsRaw
*/
bool GetValueListSelection( ValueID const& _id, int32* o_value );
/**
* \brief Gets the list of items from a list value.
* \param _id The unique identifier of the value.
* \param o_value Pointer to a vector of strings that will be filled with list items. The vector will be cleared before the items are added.
* \return true if the list items were obtained. Returns false if the value is not a ValueID::ValueType_List. The type can be tested with a call to ValueID::GetType.
* \see ValueID::GetType, GetValueAsBool, GetValueAsByte, GetValueAsFloat, GetValueAsInt, GetValueAsShort, GetValueAsString, GetValueListSelection, GetValueAsRaw
*/
bool GetValueListItems( ValueID const& _id, vector<string>* o_value );
/**
* \brief Gets a float value's precision.
* \param _id The unique identifier of the value.
* \param o_value Pointer to a uint8 that will be filled with the precision value.
* \return true if the value was obtained. Returns false if the value is not a ValueID::ValueType_Decimal. The type can be tested with a call to ValueID::GetType
* \see ValueID::GetType, GetValueAsBool, GetValueAsByte, GetValueAsInt, GetValueAsShort, GetValueAsString, GetValueListSelection, GetValueListItems
*/
bool GetValueFloatPrecision( ValueID const& _id, uint8* o_value );
/**
* \brief Sets the state of a bool.
* Due to the possibility of a device being asleep, the command is assumed to suceed, and the value
* held by the node is updated directly. This will be reverted by a future status message from the device
* if the Z-Wave message actually failed to get through. Notification callbacks will be sent in both cases.
* \param _id The unique identifier of the bool value.
* \param _value The new value of the bool.
* \return true if the value was set. Returns false if the value is not a ValueID::ValueType_Bool. The type can be tested with a call to ValueID::GetType.
*/
bool SetValue( ValueID const& _id, bool const _value );
/**
* \brief Sets the value of a byte.
* Due to the possibility of a device being asleep, the command is assumed to suceed, and the value
* held by the node is updated directly. This will be reverted by a future status message from the device
* if the Z-Wave message actually failed to get through. Notification callbacks will be sent in both cases.
* \param _id The unique identifier of the byte value.
* \param _value The new value of the byte.
* \return true if the value was set. Returns false if the value is not a ValueID::ValueType_Byte. The type can be tested with a call to ValueID::GetType.
*/
bool SetValue( ValueID const& _id, uint8 const _value );
/**
* \brief Sets the value of a decimal.
* It is usually better to handle decimal values using strings rather than floats, to avoid floating point accuracy issues.
* Due to the possibility of a device being asleep, the command is assumed to succeed, and the value
* held by the node is updated directly. This will be reverted by a future status message from the device
* if the Z-Wave message actually failed to get through. Notification callbacks will be sent in both cases.
* \param _id The unique identifier of the decimal value.
* \param _value The new value of the decimal.
* \return true if the value was set. Returns false if the value is not a ValueID::ValueType_Decimal. The type can be tested with a call to ValueID::GetType.
*/
bool SetValue( ValueID const& _id, float const _value );
/**
* \brief Sets the value of a 32-bit signed integer.
* Due to the possibility of a device being asleep, the command is assumed to suceed, and the value
* held by the node is updated directly. This will be reverted by a future status message from the device
* if the Z-Wave message actually failed to get through. Notification callbacks will be sent in both cases.
* \param _id The unique identifier of the integer value.
* \param _value The new value of the integer.
* \return true if the value was set. Returns false if the value is not a ValueID::ValueType_Int. The type can be tested with a call to ValueID::GetType.
*/
bool SetValue( ValueID const& _id, int32 const _value );
/**
* \brief Sets the value of a 16-bit signed integer.
* Due to the possibility of a device being asleep, the command is assumed to suceed, and the value
* held by the node is updated directly. This will be reverted by a future status message from the device
* if the Z-Wave message actually failed to get through. Notification callbacks will be sent in both cases.
* \param _id The unique identifier of the integer value.
* \param _value The new value of the integer.
* \return true if the value was set. Returns false if the value is not a ValueID::ValueType_Short. The type can be tested with a call to ValueID::GetType.
*/
bool SetValue( ValueID const& _id, int16 const _value );
/**
* \brief Sets the value of a collection of bytes.
* Due to the possibility of a device being asleep, the command is assumed to suceed, and the value
* held by the node is updated directly. This will be reverted by a future status message from the device
* if the Z-Wave message actually failed to get through. Notification callbacks will be sent in both cases.
* \param _id The unique identifier of the raw value.
* \param _value The new collection of bytes.
* \return true if the value was set. Returns false if the value is not a ValueID::ValueType_Raw. The type can be tested with a call to ValueID::GetType.
*/
bool SetValue( ValueID const& _id, uint8 const* _value, uint8 const _length );
/**
* \brief Sets the value from a string, regardless of type.
* Due to the possibility of a device being asleep, the command is assumed to suceed, and the value
* held by the node is updated directly. This will be reverted by a future status message from the device
* if the Z-Wave message actually failed to get through. Notification callbacks will be sent in both cases.
* \param _id The unique identifier of the integer value.
* \param _value The new value of the string.
* \return true if the value was set. Returns false if the value could not be parsed into the correct type for the value.
*/
bool SetValue( ValueID const& _id, string const& _value );
/**
* \brief Sets the selected item in a list.
* Due to the possibility of a device being asleep, the command is assumed to suceed, and the value
* held by the node is updated directly. This will be reverted by a future status message from the device
* if the Z-Wave message actually failed to get through. Notification callbacks will be sent in both cases.
* \param _id The unique identifier of the list value.
* \param _selectedItem A string matching the new selected item in the list.
* \return true if the value was set. Returns false if the selection is not in the list, or if the value is not a ValueID::ValueType_List.
* The type can be tested with a call to ValueID::GetType
*/
bool SetValueListSelection( ValueID const& _id, string const& _selectedItem );
/**
* \brief Refreshes the specified value from the Z-Wave network.
* A call to this function causes the library to send a message to the network to retrieve the current value
* of the specified ValueID (just like a poll, except only one-time, not recurring).
* \param _id The unique identifier of the value to be refreshed.
* \return true if the driver and node were found; false otherwise
*/
bool RefreshValue( ValueID const& _id);
/**
* \brief Sets a flag indicating whether value changes noted upon a refresh should be verified. If so, the
* library will immediately refresh the value a second time whenever a change is observed. This helps to filter
* out spurious data reported occasionally by some devices.
* \param _id The unique identifier of the value whose changes should or should not be verified.
* \param _verify if true, verify changes; if false, don't verify changes.
*/
void SetChangeVerified( ValueID const& _id, bool _verify );
/**
* \brief Starts an activity in a device.
* Since buttons are write-only values that do not report a state, no notification callbacks are sent.
* \param _id The unique identifier of the integer value.
* \return true if the activity was started. Returns false if the value is not a ValueID::ValueType_Button. The type can be tested with a call to ValueID::GetType.
*/
bool PressButton( ValueID const& _id );
/**
* \brief Stops an activity in a device.
* Since buttons are write-only values that do not report a state, no notification callbacks are sent.
* \param _id The unique identifier of the integer value.
* \return true if the activity was stopped. Returns false if the value is not a ValueID::ValueType_Button. The type can be tested with a call to ValueID::GetType.
*/
bool ReleaseButton( ValueID const& _id );
/*@}*/
//-----------------------------------------------------------------------------
// Climate Control Schedules
//-----------------------------------------------------------------------------
/** \name Climate Control Schedules
* Methods for accessing schedule values. All the methods require a ValueID, which will have been provided
* in the ValueAdded Notification callback when the the value was first discovered by OpenZWave.
* <p>The ValueType_Schedule is a specialized Value used to simplify access to the switch point schedule
* information held by a setback thermostat that supports the Climate Control Schedule command class.
* Each schedule contains up to nine switch points for a single day, consisting of a time in
* hours and minutes (24 hour clock) and a setback in tenths of a degree Celsius. The setback value can
* range from -128 (-12.8C) to 120 (12.0C). There are two special setback values - 121 is used to set
* Frost Protection mode, and 122 is used to set Energy Saving mode.
* <p>The switch point methods only modify OpenZWave's copy of the schedule information. Once all changes
* have been made, they are sent to the device by calling SetSchedule.
*/
/*@{*/
/**
* \brief Get the number of switch points defined in a schedule.
* \param _id The unique identifier of the schedule value.
* \return the number of switch points defined in this schedule. Returns zero if the value is not a ValueID::ValueType_Schedule. The type can be tested with a call to ValueID::GetType.
*/
uint8 GetNumSwitchPoints( ValueID const& _id );
/**
* \brief Set a switch point in the schedule.
* Inserts a new switch point into the schedule, unless a switch point already exists at the specified
* time in which case that switch point is updated with the new setback value instead.
* A maximum of nine switch points can be set in the schedule.
* \param _id The unique identifier of the schedule value.
* \param _hours The hours part of the time when the switch point will trigger. The time is set using
* the 24-hour clock, so this value must be between 0 and 23.
* \param _minutes The minutes part of the time when the switch point will trigger. This value must be
* between 0 and 59.
* \param _setback The setback in tenths of a degree Celsius. The setback value can range from -128 (-12.8C)
* to 120 (12.0C). There are two special setback values - 121 is used to set Frost Protection mode, and
* 122 is used to set Energy Saving mode.
* \return true if successful. Returns false if the value is not a ValueID::ValueType_Schedule. The type can be tested with a call to ValueID::GetType.
* \see GetNumSwitchPoints, RemoveSwitchPoint, ClearSwitchPoints
*/
bool SetSwitchPoint( ValueID const& _id, uint8 const _hours, uint8 const _minutes, int8 const _setback );
/**
* \brief Remove a switch point from the schedule.
* Removes the switch point at the specified time from the schedule.
* \param _id The unique identifier of the schedule value.
* \param _hours The hours part of the time when the switch point will trigger. The time is set using
* the 24-hour clock, so this value must be between 0 and 23.
* \param _minutes The minutes part of the time when the switch point will trigger. This value must be
* between 0 and 59.
* \return true if successful. Returns false if the value is not a ValueID::ValueType_Schedule or if there
* is not switch point with the specified time values. The type can be tested with a call to ValueID::GetType.
* \see GetNumSwitchPoints, SetSwitchPoint, ClearSwitchPoints
*/
bool RemoveSwitchPoint( ValueID const& _id, uint8 const _hours, uint8 const _minutes );
/**
* \brief Clears all switch points from the schedule.
* \param _id The unique identifier of the schedule value.
* \see GetNumSwitchPoints, SetSwitchPoint, RemoveSwitchPoint
*/
void ClearSwitchPoints( ValueID const& _id );
/**
* \brief Gets switch point data from the schedule.
* Retrieves the time and setback values from a switch point in the schedule.
* \param _id The unique identifier of the schedule value.
* \param _idx The index of the switch point, between zero and one less than the value
* returned by GetNumSwitchPoints.
* \param o_hours a pointer to a uint8 that will be filled with the hours part of the switch point data.
* \param o_minutes a pointer to a uint8 that will be filled with the minutes part of the switch point data.
* \param o_setback a pointer to an int8 that will be filled with the setback value. This can range from -128
* (-12.8C)to 120 (12.0C). There are two special setback values - 121 is used to set Frost Protection mode, and
* 122 is used to set Energy Saving mode.
* \return true if successful. Returns false if the value is not a ValueID::ValueType_Schedule. The type can be tested with a call to ValueID::GetType.
* \see GetNumSwitchPoints
*/
bool GetSwitchPoint( ValueID const& _id, uint8 const _idx, uint8* o_hours, uint8* o_minutes, int8* o_setback );
/*@}*/
//-----------------------------------------------------------------------------
// SwitchAll
//-----------------------------------------------------------------------------
/** \name SwitchAll
* Methods for switching all devices on or off together. The devices must support
* the SwitchAll command class. The command is first broadcast to all nodes, and
* then followed up with individual commands to each node (because broadcasts are
* not routed, the message might not otherwise reach all the nodes).
*/
/*@{*/
/**
* \brief Switch all devices on.
* All devices that support the SwitchAll command class will be turned on.
*/
void SwitchAllOn( uint32 const _homeId );
/**
* \brief Switch all devices off.
* All devices that support the SwitchAll command class will be turned off.
*/
void SwitchAllOff( uint32 const _homeId );
/*@}*/
//-----------------------------------------------------------------------------
// Configuration Parameters
//-----------------------------------------------------------------------------
/** \name Configuration Parameters
* Methods for accessing device configuration parameters.
* Configuration parameters are values that are managed by the Configuration command class.
* The values are device-specific and are not reported by the devices. Information on parameters
* is provided only in the device user manual.
* <p>An ongoing task for the OpenZWave project is to create XML files describing the available
* parameters for every Z-Wave. See the config folder in the project source code for examples.
*/
/*@{*/
public:
/**
* \brief Set the value of a configurable parameter in a device.
* Some devices have various parameters that can be configured to control the device behaviour.
* These are not reported by the device over the Z-Wave network, but can usually be found in
* the device's user manual.
* This method returns immediately, without waiting for confirmation from the device that the
* change has been made.
* \param _homeId The Home ID of the Z-Wave controller that manages the node.
* \param _nodeId The ID of the node to configure.
* \param _param The index of the parameter.
* \param _value The value to which the parameter should be set.
* \param _size Is an optional number of bytes to be sent for the paramter _value. Defaults to 2.
* \return true if the a message setting the value was sent to the device.
* \see RequestConfigParam
*/
bool SetConfigParam( uint32 const _homeId, uint8 const _nodeId, uint8 const _param, int32 _value, uint8 const _size = 2 );
/**
* \brief Request the value of a configurable parameter from a device.
* Some devices have various parameters that can be configured to control the device behaviour.
* These are not reported by the device over the Z-Wave network, but can usually be found in
* the device's user manual.
* This method requests the value of a parameter from the device, and then returns immediately,
* without waiting for a response. If the parameter index is valid for this device, and the
* device is awake, the value will eventually be reported via a ValueChanged notification callback.
* The ValueID reported in the callback will have an index set the same as _param and a command class
* set to the same value as returned by a call to Configuration::StaticGetCommandClassId.
* \param _homeId The Home ID of the Z-Wave controller that manages the node.
* \param _nodeId The ID of the node to configure.
* \param _param The index of the parameter.
* \see SetConfigParam, ValueID, Notification
*/
void RequestConfigParam( uint32 const _homeId, uint8 const _nodeId, uint8 const _param );
/**
* \brief Request the values of all known configurable parameters from a device.
* \param _homeId The Home ID of the Z-Wave controller that manages the node.
* \param _nodeId The ID of the node to configure.
* \see SetConfigParam, ValueID, Notification
*/
void RequestAllConfigParams( uint32 const _homeId, uint8 const _nodeId );
/*@}*/
//-----------------------------------------------------------------------------
// Groups (wrappers for the Node methods)
//-----------------------------------------------------------------------------
/** \name Groups
* Methods for accessing device association groups.
*/
/*@{*/
public:
/**
* \brief Gets the number of association groups reported by this node
* In Z-Wave, groups are numbered starting from one. For example, if a call to GetNumGroups returns 4, the _groupIdx
* value to use in calls to GetAssociations, AddAssociation and RemoveAssociation will be a number between 1 and 4.
* \param _homeId The Home ID of the Z-Wave controller that manages the node.
* \param _nodeId The ID of the node whose groups we are interested in.
* \return The number of groups.
* \see GetAssociations, GetMaxAssociations, AddAssociation, RemoveAssociation
*/
uint8 GetNumGroups( uint32 const _homeId, uint8 const _nodeId );
/**
* \brief Gets the associations for a group.
* Makes a copy of the list of associated nodes in the group, and returns it in an array of uint8's.
* The caller is responsible for freeing the array memory with a call to delete [].
* \param _homeId The Home ID of the Z-Wave controller that manages the node.
* \param _nodeId The ID of the node whose associations we are interested in.
* \param _groupIdx One-based index of the group (because Z-Wave product manuals use one-based group numbering).
* \param o_associations If the number of associations returned is greater than zero, o_associations will be set to point to an array containing the IDs of the associated nodes.
* \return The number of nodes in the associations array. If zero, the array will point to NULL, and does not need to be deleted.
* \see GetNumGroups, AddAssociation, RemoveAssociation, GetMaxAssociations
*/
uint32 GetAssociations( uint32 const _homeId, uint8 const _nodeId, uint8 const _groupIdx, uint8** o_associations );
/**
* \brief Gets the maximum number of associations for a group.
* \param _homeId The Home ID of the Z-Wave controller that manages the node.
* \param _nodeId The ID of the node whose associations we are interested in.
* \param _groupIdx one-based index of the group (because Z-Wave product manuals use one-based group numbering).
* \return The maximum number of nodes that can be associated into the group.
* \see GetNumGroups, AddAssociation, RemoveAssociation, GetAssociations
*/
uint8 GetMaxAssociations( uint32 const _homeId, uint8 const _nodeId, uint8 const _groupIdx );
/**
* \brief Returns a label for the particular group of a node.
* This label is populated by the device specific configuration files.
* \param _homeId The Home ID of the Z-Wave controller that manages the node.
* \param _nodeId The ID of the node whose associations are to be changed.
* \param _groupIdx One-based index of the group (because Z-Wave product manuals use one-based group numbering).
* \see GetNumGroups, GetAssociations, GetMaxAssociations, AddAssociation
*/
string GetGroupLabel( uint32 const _homeId, uint8 const _nodeId, uint8 const _groupIdx );
/**
* \brief Adds a node to an association group.
* Due to the possibility of a device being asleep, the command is assumed to suceed, and the association data
* held in this class is updated directly. This will be reverted by a future Association message from the device
* if the Z-Wave message actually failed to get through. Notification callbacks will be sent in both cases.
* \param _homeId The Home ID of the Z-Wave controller that manages the node.
* \param _nodeId The ID of the node whose associations are to be changed.
* \param _groupIdx One-based index of the group (because Z-Wave product manuals use one-based group numbering).
* \param _targetNodeId Identifier for the node that will be added to the association group.
* \see GetNumGroups, GetAssociations, GetMaxAssociations, RemoveAssociation
*/
void AddAssociation( uint32 const _homeId, uint8 const _nodeId, uint8 const _groupIdx, uint8 const _targetNodeId );
/**
* \brief Removes a node from an association group.
* Due to the possibility of a device being asleep, the command is assumed to suceed, and the association data
* held in this class is updated directly. This will be reverted by a future Association message from the device
* if the Z-Wave message actually failed to get through. Notification callbacks will be sent in both cases.
* \param _homeId The Home ID of the Z-Wave controller that manages the node.
* \param _nodeId The ID of the node whose associations are to be changed.
* \param _groupIdx One-based index of the group (because Z-Wave product manuals use one-based group numbering).
* \param _targetNodeId Identifier for the node that will be removed from the association group.
* \see GetNumGroups, GetAssociations, GetMaxAssociations, AddAssociation
*/
void RemoveAssociation( uint32 const _homeId, uint8 const _nodeId, uint8 const _groupIdx, uint8 const _targetNodeId );
/*@}*/
//-----------------------------------------------------------------------------
// Notifications
//-----------------------------------------------------------------------------
/** \name Notifications
* For notification of changes to the Z-Wave network or device values and associations.
*/
/*@{*/
public:
/**
* \brief Add a notification watcher.
* In OpenZWave, all feedback from the Z-Wave network is sent to the application via callbacks.
* This method allows the application to add a notification callback handler, known as a "watcher" to OpenZWave.
* An application needs only add a single watcher - all notifications will be reported to it.
* \param _watcher pointer to a function that will be called by the notification system.
* \param _context pointer to user defined data that will be passed to the watcher function with each notification.
* \return true if the watcher was successfully added.
* \see RemoveWatcher, Notification
*/
bool AddWatcher( pfnOnNotification_t _watcher, void* _context );
/**
* \brief Remove a notification watcher.
* \param _watcher pointer to a function that must match that passed to a previous call to AddWatcher
* \param _context pointer to user defined data that must match the one passed in that same previous call to AddWatcher.
* \return true if the watcher was successfully removed.
* \see AddWatcher, Notification
*/
bool RemoveWatcher( pfnOnNotification_t _watcher, void* _context );
/*@}*/
private:
void NotifyWatchers( Notification* _notification ); // Passes the notifications to all the registered watcher callbacks in turn.
struct Watcher
{
pfnOnNotification_t m_callback;
void* m_context;
Watcher
(
pfnOnNotification_t _callback,
void* _context
):
m_callback( _callback ),
m_context( _context )
{
}
};
list<Watcher*> m_watchers; // List of all the registered watchers.
Mutex* m_notificationMutex;
//-----------------------------------------------------------------------------
// Controller commands
//-----------------------------------------------------------------------------
/** \name Controller Commands
* Commands for Z-Wave network management using the PC Controller.
*/
/*@{*/
public:
/**
* \brief Hard Reset a PC Z-Wave Controller.
* Resets a controller and erases its network configuration settings. The controller becomes a primary controller ready to add devices to a new network.
* \param _homeId The Home ID of the Z-Wave controller to be reset.
* \see SoftReset
*/
void ResetController( uint32 const _homeId );
/**
* \brief Soft Reset a PC Z-Wave Controller.
* Resets a controller without erasing its network configuration settings.
* \param _homeId The Home ID of the Z-Wave controller to be reset.
* \see SoftReset
*/
void SoftReset( uint32 const _homeId );
/**
* \brief Start a controller command process.
* \param _homeId The Home ID of the Z-Wave controller.
* \param _command The command to be sent to the controller.
* \param _callback pointer to a function that will be called at various stages during the command process
* to notify the user of progress or to request actions on the user's part. Defaults to NULL.
* \param _context pointer to user defined data that will be passed into to the callback function. Defaults to NULL.
* \param _highPower used only with the AddDevice, AddController, RemoveDevice and RemoveController commands.
* Usually when adding or removing devices, the controller operates at low power so that the controller must
* be physically close to the device for security reasons. If _highPower is true, the controller will
* operate at normal power levels instead. Defaults to false.
* \param _nodeId is the node ID used by the command if necessary.
* \param _arg is an optional argument, usually another node ID, that is used by the command.
* \return true if the command was accepted and has queued to be executed.
* \see CancelControllerCommand, HasNodeFailed, RemoveFailedNode, Driver::ControllerCommand, Driver::pfnControllerCallback_t,
* <p> Commands
* - Driver::ControllerCommand_AddDevice - Add a new device or controller to the Z-Wave network.
* - Driver::ControllerCommand_CreateNewPrimary - Create a new primary controller when old primary fails. Requires SUC.
* - Driver::ControllerCommand_ReceiveConfiguration - Receive network configuration information from primary controller. Requires secondary.
* - Driver::ControllerCommand_RemoveDevice - Remove a device or controller from the Z-Wave network.
* - Driver::ControllerCommand_RemoveFailedNode - Remove a node from the network. The node must not be responding
* and be on the controller's failed node list.
* - Driver::ControllerCommand_HasNodeFailed - Check whether a node is in the controller's failed nodes list.
* - Driver::ControllerCommand_ReplaceFailedNode - Replace a failed device with another. If the node is not in
* the controller's failed nodes list, or the node responds, this command will fail.
* - Driver:: ControllerCommand_TransferPrimaryRole - Add a new controller to the network and
* make it the primary. The existing primary will become a secondary controller.
* - Driver::ControllerCommand_RequestNetworkUpdate - Update the controller with network information from the SUC/SIS.
* - Driver::ControllerCommand_RequestNodeNeighborUpdate - Get a node to rebuild its neighbour list. This method also does RequestNodeNeighbors afterwards.
* - Driver::ControllerCommand_AssignReturnRoute - Assign a network return route to a device.
* - Driver::ControllerCommand_DeleteAllReturnRoutes - Delete all network return routes from a device.
* - Driver::ControllerCommand_SendNodeInformation - Send a node information frame.
* - Driver::ControllerCommand_ReplicationSend - Send information from primary to secondary
* - Driver::ControllerCommand_CreateButton - Create a handheld button id.
* - Driver::ControllerCommand_DeleteButton - Delete a handheld button id.
* <p> Callbacks
* - Driver::ControllerState_Starting, the controller command has begun
* - Driver::ControllerState_Waiting, the controller is waiting for a user action. A notice should be displayed
* to the user at this point, telling them what to do next.
* For the add, remove, replace and transfer primary role commands, the user needs to be told to press the
* inclusion button on the device that is going to be added or removed. For ControllerCommand_ReceiveConfiguration,
* they must set their other controller to send its data, and for ControllerCommand_CreateNewPrimary, set the other
* controller to learn new data.
* - Driver::ControllerState_InProgress - the controller is in the process of adding or removing the chosen node. It is now too late to cancel the command.
* - Driver::ControllerState_Complete - the controller has finished adding or removing the node, and the command is complete.
* - Driver::ControllerState_Failed - will be sent if the command fails for any reason.
*/
bool BeginControllerCommand( uint32 const _homeId, Driver::ControllerCommand _command, Driver::pfnControllerCallback_t _callback = NULL, void* _context = NULL, bool _highPower = false, uint8 _nodeId = 0xff, uint8 _arg = 0 );
/**
* \brief Cancels any in-progress command running on a controller.
* \param _homeId The Home ID of the Z-Wave controller.
* \return true if a command was running and was cancelled.
* \see BeginControllerCommand
*/
bool CancelControllerCommand( uint32 const _homeId );
/*@}*/
//-----------------------------------------------------------------------------
// Network commands
//-----------------------------------------------------------------------------
/** \name Network Commands
* Commands for Z-Wave network for testing, routing and other internal
* operations.
*/
/*@{*/
public:
/**
* \brief Test network node.
* Sends a series of messages to a network node for testing network reliability.
* \param _homeId The Home ID of the Z-Wave controller to be reset.
* \param _count This is the number of test messages to send.
* \see TestNetwork
*/
void TestNetworkNode( uint32 const _homeId, uint8 const _nodeId, uint32 const _count );
/**
* \brief Test network.
* Sends a series of messages to every node on the network for testing network reliability.
* \param _homeId The Home ID of the Z-Wave controller to be reset.
* \param _count This is the number of test messages to send.
* \see TestNetwork
*/
void TestNetwork( uint32 const _homeId, uint32 const _count );
/**
* \brief Heal network node by requesting the node rediscover their neighbors.
* Sends a ControllerCommand_RequestNodeNeighborUpdate to the node.
* \param _homeId The Home ID of the Z-Wave network to be healed.
* \param _nodeId The node to heal.
* \param _doRR Whether to perform return routes initialization.
*/
void HealNetworkNode( uint32 const _homeId, uint8 const _nodeId, bool _doRR );
/**
* \brief Heal network by requesting node's rediscover their neighbors.
* Sends a ControllerCommand_RequestNodeNeighborUpdate to every node.
* Can take a while on larger networks.
* \param _homeId The Home ID of the Z-Wave network to be healed.
* \param _doRR Whether to perform return routes initialization.
*/
void HealNetwork( uint32 const _homeId, bool _doRR );
void SendRaw( uint32 const _homeId, uint8 _nodeId, unsigned char *_data, int len );
/*@}*/
//-----------------------------------------------------------------------------
// Scene commands
//-----------------------------------------------------------------------------
/** \name Scene Commands
* Commands for Z-Wave scene interface.
*/
/*@{*/
public:
/**
* \brief Gets the number of scenes that have been defined.
* \return The number of scenes.
* \see GetAllScenes, RemoveAllScenes, CreateScene, RemoveScene, AddSceneValue, RemoveSceneValue, SceneGetValues, SceneGetValueAsBool, SceneGetValueAsByte, SceneGetValueAsFloat, SceneGetValueAsInt, SceneGetValueAsShort, SceneGetValueAsString, SetSceneValue, GetSceneLabel, SetSceneLabel, SceneExists, ActivateScene
*/
uint8 GetNumScenes( );
/**
* \brief Gets a list of all the SceneIds.
* \param _sceneIds is a pointer to an array of integers.
* \return The number of scenes. If zero, _sceneIds will be NULL and doesn't need to be freed.
* \see GetNumScenes, CreateScene, RemoveScene, AddSceneValue, RemoveSceneValue, SceneGetValues, SceneGetValueAsBool, SceneGetValueAsByte, SceneGetValueAsFloat, SceneGetValueAsInt, SceneGetValueAsShort, SceneGetValueAsString, SetSceneValue, GetSceneLabel, SetSceneLabel, SceneExists, ActivateScene
*/
uint8 GetAllScenes( uint8** _sceneIds );
/**
* \brief Remove all the SceneIds.
* \param _homeId The Home ID of the Z-Wave controller. 0 for all devices from all scenes.
* \see GetAllScenes, GetNumScenes, CreateScene, RemoveScene, AddSceneValue, RemoveSceneValue, SceneGetValues, SceneGetValueAsBool, SceneGetValueAsByte, SceneGetValueAsFloat, SceneGetValueAsInt, SceneGetValueAsShort, SceneGetValueAsString, SetSceneValue, GetSceneLabel, SetSceneLabel, SceneExists, ActivateScene
*/
void RemoveAllScenes( uint32 const _homeId );
/**
* \brief Create a new Scene passing in Scene ID
* \return uint8 Scene ID used to reference the scene. 0 is failure result.
* \see GetNumScenes, GetAllScenes, RemoveScene, AddSceneValue, RemoveSceneValue, SceneGetValues, SceneGetValueAsBool, SceneGetValueAsByte, SceneGetValueAsFloat, SceneGetValueAsInt, SceneGetValueAsShort, SceneGetValueAsString, SetSceneValue, GetSceneLabel, SetSceneLabel, SceneExists, ActivateScene
*/
uint8 CreateScene();
/**
* \brief Remove an existing Scene.
* \param _sceneId is an integer representing the unique Scene ID to be removed.
* \return true if scene was removed.
* \see GetNumScenes, GetAllScenes, CreateScene, AddSceneValue, RemoveSceneValue, SceneGetValues, SceneGetValueAsBool, SceneGetValueAsByte, SceneGetValueAsFloat, SceneGetValueAsInt, SceneGetValueAsShort, SceneGetValueAsString, SetSceneValue, GetSceneLabel, SetSceneLabel, SceneExists, ActivateScene
*/
bool RemoveScene( uint8 const _sceneId );
/**
* \brief Add a bool Value ID to an existing scene.
* \param _sceneId is an integer representing the unique Scene ID.
* \param _valueId is the Value ID to be added.
* \param _value is the bool value to be saved.
* \return true if Value ID was added.
* \see GetNumScenes, GetAllScenes, CreateScene, RemoveScene, RemoveSceneValue, SceneGetValues, SceneGetValueAsBool, SceneGetValueAsByte, SceneGetValueAsFloat, SceneGetValueAsInt, SceneGetValueAsShort, SceneGetValueAsString, SetSceneValue, GetSceneLabel, SetSceneLabel, SceneExists, ActivateScene
*/
bool AddSceneValue( uint8 const _sceneId, ValueID const& _valueId, bool const _value );
/**
* \brief Add a byte Value ID to an existing scene.
* \param _sceneId is an integer representing the unique Scene ID.
* \param _valueId is the Value ID to be added.
* \param _value is the byte value to be saved.
* \return true if Value ID was added.
* \see GetNumScenes, GetAllScenes, CreateScene, RemoveScene, RemoveSceneValue, SceneGetValues, SceneGetValueAsBool, SceneGetValueAsByte, SceneGetValueAsFloat, SceneGetValueAsInt, SceneGetValueAsShort, SceneGetValueAsString, SetSceneValue, GetSceneLabel, SetSceneLabel, SceneExists, ActivateScene
*/
bool AddSceneValue( uint8 const _sceneId, ValueID const& _valueId, uint8 const _value );
/**
* \brief Add a decimal Value ID to an existing scene.
* \param _sceneId is an integer representing the unique Scene ID.
* \param _valueId is the Value ID to be added.
* \param _value is the float value to be saved.
* \return true if Value ID was added.
* \see GetNumScenes, GetAllScenes, CreateScene, RemoveScene, RemoveSceneValue, SceneGetValues, SceneGetValueAsBool, SceneGetValueAsByte, SceneGetValueAsFloat, SceneGetValueAsInt, SceneGetValueAsShort, SceneGetValueAsString, SetSceneValue, GetSceneLabel, SetSceneLabel, SceneExists, ActivateScene
*/
bool AddSceneValue( uint8 const _sceneId, ValueID const& _valueId, float const _value );
/**
* \brief Add a 32-bit signed integer Value ID to an existing scene.
* \param _sceneId is an integer representing the unique Scene ID.
* \param _valueId is the Value ID to be added.
* \param _value is the int32 value to be saved.
* \return true if Value ID was added.
* \see GetNumScenes, GetAllScenes, CreateScene, RemoveScene, RemoveSceneValue, SceneGetValues, SceneGetValueAsBool, SceneGetValueAsByte, SceneGetValueAsFloat, SceneGetValueAsInt, SceneGetValueAsShort, SceneGetValueAsString, SetSceneValue, GetSceneLabel, SetSceneLabel, SceneExists, ActivateScene
*/
bool AddSceneValue( uint8 const _sceneId, ValueID const& _valueId, int32 const _value );
/**
* \brief Add a 16-bit signed integer Value ID to an existing scene.
* \param _sceneId is an integer representing the unique Scene ID.
* \param _valueId is the Value ID to be added.
* \param _value is the int16 value to be saved.
* \return true if Value ID was added.
* \see GetNumScenes, GetAllScenes, CreateScene, RemoveScene, RemoveSceneValue, SceneGetValues, SceneGetValueAsBool, SceneGetValueAsByte, SceneGetValueAsFloat, SceneGetValueAsInt, SceneGetValueAsShort, SceneGetValueAsString, SetSceneValue, GetSceneLabel, SetSceneLabel, SceneExists, ActivateScene
*/
bool AddSceneValue( uint8 const _sceneId, ValueID const& _valueId, int16 const _value );
/**
* \brief Add a string Value ID to an existing scene.
* \param _sceneId is an integer representing the unique Scene ID.
* \param _valueId is the Value ID to be added.
* \param _value is the string value to be saved.
* \return true if Value ID was added.
* \see GetNumScenes, GetAllScenes, CreateScene, RemoveScene, RemoveSceneValue, SceneGetValues, SceneGetValueAsBool, SceneGetValueAsByte, SceneGetValueAsFloat, SceneGetValueAsInt, SceneGetValueAsShort, SceneGetValueAsString, SetSceneValue, GetSceneLabel, SetSceneLabel, SceneExists, ActivateScene
*/
bool AddSceneValue( uint8 const _sceneId, ValueID const& _valueId, string const& _value );
/**
* \brief Add the selected item list Value ID to an existing scene (as a string).
* \param _sceneId is an integer representing the unique Scene ID.
* \param _valueId is the Value ID to be added.
* \param _value is the string value to be saved.
* \return true if Value ID was added.
* \see GetNumScenes, GetAllScenes, CreateScene, RemoveScene, AddSceneValue, RemoveSceneValue, SceneGetValues, SceneGetValueAsBool, SceneGetValueAsByte, SceneGetValueAsFloat, SceneGetValueAsInt, SceneGetValueAsShort, SceneGetValueAsString, SetSceneValue, GetSceneLabel, SetSceneLabel, SceneExists, ActivateScene
*/
bool AddSceneValueListSelection( uint8 const _sceneId, ValueID const& _valueId, string const& _value );
/**
* \brief Add the selected item list Value ID to an existing scene (as a integer).
* \param _sceneId is an integer representing the unique Scene ID.
* \param _valueId is the Value ID to be added.
* \param _value is the integer value to be saved.
* \return true if Value ID was added.
* \see GetNumScenes, GetAllScenes, CreateScene, RemoveScene, AddSceneValue, RemoveSceneValue, SceneGetValues, SceneGetValueAsBool, SceneGetValueAsByte, SceneGetValueAsFloat, SceneGetValueAsInt, SceneGetValueAsShort, SceneGetValueAsString, SetSceneValue, GetSceneLabel, SetSceneLabel, SceneExists, ActivateScene
*/
bool AddSceneValueListSelection( uint8 const _sceneId, ValueID const& _valueId, int32 const _value );
/**
* \brief Remove the Value ID from an existing scene.
* \param _sceneId is an integer representing the unique Scene ID.
* \param _valueId is the Value ID to be removed.
* \return true if Value ID was removed.
* \see GetNumScenes, GetAllScenes, CreateScene, RemoveScene, AddSceneValue, SceneGetValues, SceneGetValueAsBool, SceneGetValueAsByte, SceneGetValueAsFloat, SceneGetValueAsInt, SceneGetValueAsShort, SceneGetValueAsString, SetSceneValue, GetSceneLabel, SetSceneLabel, SceneExists, ActivateScene
*/
bool RemoveSceneValue( uint8 const _sceneId, ValueID const& _valueId );
/**
* \brief Retrieves the scene's list of values.
* \param _sceneId The Scene ID of the scene to retrieve the value from.
* \param o_value Pointer to an array of ValueIDs if return is non-zero.
* \return The number of nodes in the o_value array. If zero, the array will point to NULL and does not need to be deleted.
* \see GetNumScenes, GetAllScenes, CreateScene, RemoveScene, AddSceneValue, RemoveSceneValue, SceneGetValueAsBool, SceneGetValueAsByte, SceneGetValueAsFloat, SceneGetValueAsInt, SceneGetValueAsShort, SceneGetValueAsString, SetSceneValue, GetSceneLabel, SetSceneLabel, SceneExists, ActivateScene
*/
int SceneGetValues( uint8 const _sceneId, vector<ValueID>* o_value );
/**
* \brief Retrieves a scene's value as a bool.
* \param _sceneId The Scene ID of the scene to retrieve the value from.
* \param _valueId The Value ID of the value to retrieve.
* \param o_value Pointer to a bool that will be filled with the returned value.
* \return true if the value was obtained.
* \see GetNumScenes, GetAllScenes, CreateScene, RemoveScene, AddSceneValue, RemoveSceneValue, SceneGetValues, SceneGetValueAsByte, SceneGetValueAsFloat, SceneGetValueAsInt, SceneGetValueAsShort, SceneGetValueAsString, SetSceneValue, GetSceneLabel, SetSceneLabel, SceneExists, ActivateScene
*/
bool SceneGetValueAsBool( uint8 const _sceneId, ValueID const& _valueId, bool* o_value );
/**
* \brief Retrieves a scene's value as an 8-bit unsigned integer.
* \param _sceneId The Scene ID of the scene to retrieve the value from.
* \param _valueId The Value ID of the value to retrieve.
* \param o_value Pointer to a uint8 that will be filled with the returned value.
* \return true if the value was obtained.
* \see GetNumScenes, GetAllScenes, CreateScene, RemoveScene, AddSceneValue, RemoveSceneValue, SceneGetValues, SceneGetValueAsBool, SceneGetValueAsFloat, SceneGetValueAsInt, SceneGetValueAsShort, SceneGetValueAsString, SetSceneValue, GetSceneLabel, SetSceneLabel, SceneExists, ActivateScene
*/
bool SceneGetValueAsByte( uint8 const _sceneId, ValueID const& _valueId, uint8* o_value );
/**
* \brief Retrieves a scene's value as a float.
* \param _sceneId The Scene ID of the scene to retrieve the value from.
* \param _valueId The Value ID of the value to retrieve.
* \param o_value Pointer to a float that will be filled with the returned value.
* \return true if the value was obtained.
* \see GetNumScenes, GetAllScenes, CreateScene, RemoveScene, AddSceneValue, RemoveSceneValue, SceneGetValues, SceneGetValueAsBool, SceneGetValueAsByte, SceneGetValueAsInt, SceneGetValueAsShort, SceneGetValueAsString, SetSceneValue, GetSceneLabel, SetSceneLabel, SceneExists, ActivateScene
*/
bool SceneGetValueAsFloat( uint8 const _sceneId, ValueID const& _valueId, float* o_value );
/**
* \brief Retrieves a scene's value as a 32-bit signed integer.
* \param _sceneId The Scene ID of the scene to retrieve the value from.
* \param _valueId The Value ID of the value to retrieve.
* \param o_value Pointer to a int32 that will be filled with the returned value.
* \return true if the value was obtained.
* \see GetNumScenes, GetAllScenes, CreateScene, RemoveScene, AddSceneValue, RemoveSceneValue, SceneGetValues, SceneGetValueAsBool, SceneGetValueAsByte, SceneGetValueAsFloat, SceneGetValueAsShort, SceneGetValueAsString, SetSceneValue, GetSceneLabel, SetSceneLabel, SceneExists, ActivateScene
*/
bool SceneGetValueAsInt( uint8 const _sceneId, ValueID const& _valueId, int32* o_value );
/**
* \brief Retrieves a scene's value as a 16-bit signed integer.
* \param _sceneId The Scene ID of the scene to retrieve the value from.
* \param _valueId The Value ID of the value to retrieve.
* \param o_value Pointer to a int16 that will be filled with the returned value.
* \return true if the value was obtained.
* \see GetNumScenes, GetAllScenes, CreateScene, RemoveScene, AddSceneValue, RemoveSceneValue, SceneGetValues, SceneGetValueAsBool, SceneGetValueAsByte, SceneGetValueAsFloat, SceneGetValueAsInt, SceneGetValueAsString, SetSceneValue, GetSceneLabel, SetSceneLabel, SceneExists, ActivateScene
*/
bool SceneGetValueAsShort( uint8 const _sceneId, ValueID const& _valueId, int16* o_value );
/**
* \brief Retrieves a scene's value as a string.
* \param _sceneId The Scene ID of the scene to retrieve the value from.
* \param _valueId The Value ID of the value to retrieve.
* \param o_value Pointer to a string that will be filled with the returned value.
* \return true if the value was obtained.
* \see GetNumScenes, GetAllScenes, CreateScene, RemoveScene, AddSceneValue, RemoveSceneValue, SceneGetValues, SceneGetValueAsBool, SceneGetValueAsByte, SceneGetValueAsFloat, SceneGetValueAsInt, SceneGetValueAsShort, SetSceneValue, GetSceneLabel, SetSceneLabel, SceneExists, ActivateScene
*/
bool SceneGetValueAsString( uint8 const _sceneId, ValueID const& _valueId, string* o_value );
/**
* \brief Retrieves a scene's value as a list (as a string).
* \param _sceneId The Scene ID of the scene to retrieve the value from.
* \param _valueId The Value ID of the value to retrieve.
* \param o_value Pointer to a string that will be filled with the returned value.
* \return true if the value was obtained.
* \see GetNumScenes, GetAllScenes, CreateScene, RemoveScene, AddSceneValue, RemoveSceneValue, SceneGetValues, SceneGetValueAsBool, SceneGetValueAsByte, SceneGetValueAsFloat, SceneGetValueAsInt, SceneGetValueAsShort, SceneGetValueAsString, SetSceneValue, GetSceneLabel, SetSceneLabel, SceneExists, ActivateScene
*/
bool SceneGetValueListSelection( uint8 const _sceneId, ValueID const& _valueId, string* o_value );
/**
* \brief Retrieves a scene's value as a list (as a integer).
* \param _sceneId The Scene ID of the scene to retrieve the value from.
* \param _valueId The Value ID of the value to retrieve.
* \param o_value Pointer to a integer that will be filled with the returned value.
* \return true if the value was obtained.
* \see GetNumScenes, GetAllScenes, CreateScene, RemoveScene, AddSceneValue, RemoveSceneValue, SceneGetValues, SceneGetValueAsBool, SceneGetValueAsByte, SceneGetValueAsFloat, SceneGetValueAsInt, SceneGetValueAsShort, SceneGetValueAsString, SetSceneValue, GetSceneLabel, SetSceneLabel, SceneExists, ActivateScene
*/
bool SceneGetValueListSelection( uint8 const _sceneId, ValueID const& _valueId, int32* o_value );
/**
* \brief Set a bool Value ID to an existing scene's ValueID
* \param _sceneId is an integer representing the unique Scene ID.
* \param _valueId is the Value ID to be added.
* \param _value is the bool value to be saved.
* \return true if Value ID was added.
* \see GetNumScenes, GetAllScenes, CreateScene, RemoveScene, AddSceneValue, RemoveSceneValue, SceneGetValues, SceneGetValueAsBool, SceneGetValueAsByte, SceneGetValueAsFloat, SceneGetValueAsInt, SceneGetValueAsShort, SceneGetValueAsString, GetSceneLabel, SetSceneLabel, SceneExists, ActivateScene
*/
bool SetSceneValue( uint8 const _sceneId, ValueID const& _valueId, bool const _value );
/**
* \brief Set a byte Value ID to an existing scene's ValueID
* \param _sceneId is an integer representing the unique Scene ID.
* \param _valueId is the Value ID to be added.
* \param _value is the byte value to be saved.
* \return true if Value ID was added.
* \see GetNumScenes, GetAllScenes, CreateScene, RemoveScene, AddSceneValue, RemoveSceneValue, SceneGetValues, SceneGetValueAsBool, SceneGetValueAsByte, SceneGetValueAsFloat, SceneGetValueAsInt, SceneGetValueAsShort, SceneGetValueAsString, GetSceneLabel, SetSceneLabel, SceneExists, ActivateScene
*/
bool SetSceneValue( uint8 const _sceneId, ValueID const& _valueId, uint8 const _value );
/**
* \brief Set a decimal Value ID to an existing scene's ValueID
* \param _sceneId is an integer representing the unique Scene ID.
* \param _valueId is the Value ID to be added.
* \param _value is the float value to be saved.
* \return true if Value ID was added.
* \see GetNumScenes, GetAllScenes, CreateScene, RemoveScene, AddSceneValue, RemoveSceneValue, SceneGetValues, SceneGetValueAsBool, SceneGetValueAsByte, SceneGetValueAsFloat, SceneGetValueAsInt, SceneGetValueAsShort, SceneGetValueAsString, GetSceneLabel, SetSceneLabel, SceneExists, ActivateScene
*/
bool SetSceneValue( uint8 const _sceneId, ValueID const& _valueId, float const _value );
/**
* \brief Set a 32-bit signed integer Value ID to an existing scene's ValueID
* \param _sceneId is an integer representing the unique Scene ID.
* \param _valueId is the Value ID to be added.
* \param _value is the int32 value to be saved.
* \return true if Value ID was added.
* \see GetNumScenes, GetAllScenes, CreateScene, RemoveScene, AddSceneValue, RemoveSceneValue, SceneGetValues, SceneGetValueAsBool, SceneGetValueAsByte, SceneGetValueAsFloat, SceneGetValueAsInt, SceneGetValueAsShort, SceneGetValueAsString, GetSceneLabel, SetSceneLabel, SceneExists, ActivateScene
*/
bool SetSceneValue( uint8 const _sceneId, ValueID const& _valueId, int32 const _value );
/**
* \brief Set a 16-bit integer Value ID to an existing scene's ValueID
* \param _sceneId is an integer representing the unique Scene ID.
* \param _valueId is the Value ID to be added.
* \param _value is the int16 value to be saved.
* \return true if Value ID was added.
* \see GetNumScenes, GetAllScenes, CreateScene, RemoveScene, AddSceneValue, RemoveSceneValue, SceneGetValues, SceneGetValueAsBool, SceneGetValueAsByte, SceneGetValueAsFloat, SceneGetValueAsInt, SceneGetValueAsShort, SceneGetValueAsString, GetSceneLabel, SetSceneLabel, SceneExists, ActivateScene
*/
bool SetSceneValue( uint8 const _sceneId, ValueID const& _valueId, int16 const _value );
/**
* \brief Set a string Value ID to an existing scene's ValueID
* \param _sceneId is an integer representing the unique Scene ID.
* \param _valueId is the Value ID to be added.
* \param _value is the string value to be saved.
* \return true if Value ID was added.
* \see GetNumScenes, GetAllScenes, CreateScene, RemoveScene, AddSceneValue, RemoveSceneValue, SceneGetValues, SceneGetValueAsBool, SceneGetValueAsByte, SceneGetValueAsFloat, SceneGetValueAsInt, SceneGetValueAsShort, SceneGetValueAsString, GetSceneLabel, SetSceneLabel, SceneExists, ActivateScene
*/
bool SetSceneValue( uint8 const _sceneId, ValueID const& _valueId, string const& _value );
/**
* \brief Set the list selected item Value ID to an existing scene's ValueID (as a string).
* \param _sceneId is an integer representing the unique Scene ID.
* \param _valueId is the Value ID to be added.
* \param _value is the string value to be saved.
* \return true if Value ID was added.
* \see GetNumScenes, GetAllScenes, CreateScene, RemoveScene, AddSceneValue, RemoveSceneValue, SceneGetValues, SceneGetValueAsBool, SceneGetValueAsByte, SceneGetValueAsFloat, SceneGetValueAsInt, SceneGetValueAsShort, SceneGetValueAsString, SetSceneValue, GetSceneLabel, SetSceneLabel, SceneExists, ActivateScene
*/
bool SetSceneValueListSelection( uint8 const _sceneId, ValueID const& _valueId, string const& _value );
/**
* \brief Set the list selected item Value ID to an existing scene's ValueID (as a integer).
* \param _sceneId is an integer representing the unique Scene ID.
* \param _valueId is the Value ID to be added.
* \param _value is the integer value to be saved.
* \return true if Value ID was added.
* \see GetNumScenes, GetAllScenes, CreateScene, RemoveScene, AddSceneValue, RemoveSceneValue, SceneGetValues, SceneGetValueAsBool, SceneGetValueAsByte, SceneGetValueAsFloat, SceneGetValueAsInt, SceneGetValueAsShort, SceneGetValueAsString, SetSceneValue, GetSceneLabel, SetSceneLabel, SceneExists, ActivateScene
*/
bool SetSceneValueListSelection( uint8 const _sceneId, ValueID const& _valueId, int32 const _value );
/**
* \brief Returns a label for the particular scene.
* \param _sceneId The Scene ID
* \return The label string.
* \see GetNumScenes, GetAllScenes, CreateScene, RemoveScene, AddSceneValue, RemoveSceneValue, SceneGetValues, SceneGetValueAsBool, SceneGetValueAsByte, SceneGetValueAsFloat, SceneGetValueAsInt, SceneGetValueAsShort, SceneGetValueAsString, SetSceneValue, SetSceneLabel, SceneExists, ActivateScene
*/
string GetSceneLabel( uint8 const _sceneId );
/**
* \brief Sets a label for the particular scene.
* \param _sceneId The Scene ID
* \param _value The new value of the label.
* \see GetNumScenes, GetAllScenes, CreateScene, RemoveScene, AddSceneValue, RemoveSceneValue, SceneGetValues, SceneGetValueAsBool, SceneGetValueAsByte, SceneGetValueAsFloat, SceneGetValueAsInt, SceneGetValueAsShort, SceneGetValueAsString, SetSceneValue, GetSceneLabel, SceneExists, ActivateScene
*/
void SetSceneLabel( uint8 const _sceneId, string const& _value );
/**
* \brief Check if a Scene ID is defined.
* \param _sceneId The Scene ID.
* \return true if Scene ID exists.
* \see GetNumScenes, GetAllScenes, CreateScene, RemoveScene, AddSceneValue, RemoveSceneValue, SceneGetValues, SceneGetValueAsBool, SceneGetValueAsByte, SceneGetValueAsFloat, SceneGetValueAsInt, SceneGetValueAsShort, SceneGetValueAsString, SetSceneValue, GetSceneLabel, SetSceneLabel, ActivateScene
*/
bool SceneExists( uint8 const _sceneId );
/**
* \brief Activate given scene to perform all its actions.
* \param _sceneId The Scene ID.
* \return true if it is successful.
* \see GetNumScenes, GetAllScenes, CreateScene, RemoveScene, AddSceneValue, RemoveSceneValue, SceneGetValues, SceneGetValueAsBool, SceneGetValueAsByte, SceneGetValueAsFloat, SceneGetValueAsInt, SceneGetValueAsShort, SceneGetValueAsString, SetSceneValue, GetSceneLabel, SetSceneLabel, SceneExists
*/
bool ActivateScene( uint8 const _sceneId );
/*@}*/
//-----------------------------------------------------------------------------
// Statistics interface
//-----------------------------------------------------------------------------
/** \name Statistics retrieval interface
* Commands for Z-Wave statistics interface.
*/
/*@{*/
public:
/**
* \brief Retrieve statistics from driver
* \param _homeId The Home ID of the driver to obtain counters
* \param _data Pointer to structure DriverData to return values
*/
void GetDriverStatistics( uint32 const _homeId, Driver::DriverData* _data );
/**
* \brief Retrieve statistics per node
* \param _homeId The Home ID of the driver for the node
* \param _nodeId The node number
* \param _data Pointer to structure NodeData to return values
*/
void GetNodeStatistics( uint32 const _homeId, uint8 const _nodeId, Node::NodeData* _data );
};
/*@}*/
} // namespace OpenZWave
#endif // _Manager_H
| [
"wycca1@gmail.com"
] | wycca1@gmail.com |
76602b30378f7ae2775a85e3b6c64a1629b3e178 | 7c457d9cef7f8c93621635a1a4585f627c5c345a | /lib/src/improvement_heuristics.cpp | beacf1cc14817a1c1edbb1aa88e5f651686da968 | [] | no_license | jyxxhyx/vehicle_routing_problem | 4e270942a46114cce770312af97e27a019564a9c | eb4b53bf20a930cc769713233705e6760ad7c606 | refs/heads/master | 2020-07-05T07:09:39.609665 | 2019-05-23T18:41:47 | 2019-05-23T18:47:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 464 | cpp | #include "improvement_heuristics.h"
#include "src/internal/tabu_search.h"
namespace vrp {
Solution create_improved_solution(const Problem& prob,
const Solution& initial_sln,
ImprovementHeuristic heuristic) {
switch (heuristic) {
case ImprovementHeuristic::Tabu:
return detail::tabu_search(prob, initial_sln);
default:
return initial_sln;
}
}
} // namespace vrp
| [
"noreply@github.com"
] | noreply@github.com |
b83447776d671cceb689a60e466534242329e34b | ead5c32ff8cf5ce04c35603cc7698904e1536be4 | /plugins/revsocketinterface/revsocketinterface.h | 01e67bfe6693c8e2a11602b5592c1355602b0488 | [] | no_license | malcom2073/revfe | 7bda0386f4fb0d24b24414c724ddfcf7f768fd8e | 775a9a3efb11aa8f59210b3b440542acd61e8f58 | refs/heads/master | 2021-01-23T15:52:59.247127 | 2012-03-24T13:12:31 | 2012-03-24T13:12:31 | 33,929,251 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,334 | h | /***************************************************************************
* Copyright (C) 2008 by Michael Carpenter (malcom2073) *
* mcarpenter@interforcesystems.com *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#include <QTcpServer>
#include <QTcpSocket>
#include "baseinterface.h"
#include "ipcmessage.h"
class SocketInterface : public BaseInterface
{
Q_OBJECT
Q_INTERFACES(BaseInterface)
public:
SocketInterface();
void init();
QString getName();
private:
QString m_name;
QTcpServer *tcpListener;
QMap<QTcpSocket*,QString> m_bufferMap;
void parseBuffer(QTcpSocket *sock);
QList<QTcpSocket *> m_socketList;
signals:
void passCoreMessage(QString sender,QString message);
void passCoreMessage(QString sender,IPCMessage message);
void passCoreMessageBlocking(QString sender,IPCMessage message);
private slots:
void socketReadyRead();
void tcpListenerNewConnection();
void socketDisconnected();
void sockerError(QAbstractSocket::SocketError err);
public slots:
void passPluginMessage(QString sender,QString message);
void passPluginMessage(QString sender,IPCMessage message);
};
| [
"malcom2073@gmail.com"
] | malcom2073@gmail.com |
d7495db46e33c8545096dac9fb66d753255c4996 | 131223db8fe76478768e174d85828cf10862c0dc | /services/bluetooth_standard/service/src/obex/obex_client.cpp | a521b70d9fd71487f461caca2694444f91e04617 | [
"Apache-2.0"
] | permissive | openharmony-gitee-mirror/communication_bluetooth | e3c834043d8d96be666401ba6baa3f55e1f1f3d2 | 444309918cd00a65a10b8d798a0f5a78f8cf13be | refs/heads/master | 2023-08-24T10:05:20.001354 | 2021-10-19T01:45:18 | 2021-10-19T01:45:18 | 400,050,270 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 23,684 | cpp | /*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* 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 "obex_client.h"
#include <cstring>
#include <iostream>
#include "buffer.h"
#include "log.h"
#include "obex_socket_transport.h"
#include "obex_utils.h"
#include "transport/transport_l2cap.h"
namespace bluetooth {
ObexClient::ObexClientTransportObserver::ObexClientTransportObserver(ObexClient &obexClient) : obexClient_(obexClient)
{}
void ObexClient::ObexClientTransportObserver::OnTransportConnected(ObexTransport &transport)
{
OBEX_LOG_INFO("Call %{public}s", __PRETTY_FUNCTION__);
OBEX_LOG_INFO("ClientId: %{public}s", obexClient_.clientId_.c_str());
if (!transport.IsConnected()) {
obexClient_.clientObserver_.OnTransportFailed(obexClient_, -1);
return;
}
obexClient_.clientState_ = ObexClientState::TRANSPORT_CONNECTED;
if (obexClient_.isSupportReliableSession_ && obexClient_.reliableSessionReqHeader_ != nullptr) {
obexClient_.SendRequest(*obexClient_.reliableSessionReqHeader_);
} else if (obexClient_.connectReqHeader_ != nullptr) {
obexClient_.SendConnectRequest(*obexClient_.connectReqHeader_);
}
}
void ObexClient::ObexClientTransportObserver::OnTransportDisconnected(ObexTransport &transport)
{
OBEX_LOG_INFO("Call %{public}s", __PRETTY_FUNCTION__);
OBEX_LOG_INFO("ClientId: %{public}s", obexClient_.GetClientId().c_str());
obexClient_.clientState_ = ObexClientState::TRANSPORT_DISCONNECTED;
obexClient_.isObexConnected_ = false;
obexClient_.connectReqHeader_ = nullptr;
obexClient_.clientObserver_.OnDisconnected(obexClient_);
}
void ObexClient::ObexClientTransportObserver::OnTransportDataBusy(ObexTransport &transport, uint8_t isBusy)
{
OBEX_LOG_INFO("Call %{public}s, isBusy %{public}d", __PRETTY_FUNCTION__, isBusy);
OBEX_LOG_INFO("ClientId: %{public}s", obexClient_.GetClientId().c_str());
obexClient_.HandleTransportDataBusy(isBusy);
}
void ObexClient::ObexClientTransportObserver::OnTransportDataAvailable(
ObexTransport &transport, ObexPacket &obexPacket)
{
OBEX_LOG_INFO("Call %{public}s", __PRETTY_FUNCTION__);
OBEX_LOG_INFO("ClientId: %{public}s", obexClient_.GetClientId().c_str());
obexClient_.isProcessing_ = false;
auto resp = GetObexHeaderFromPacket(obexPacket);
if (!resp) {
return;
}
obexClient_.clientSession_->SetLastRespCd(resp->GetFieldCode());
OBEX_LOG_DEBUG("lastOpeId : %02X", obexClient_.clientSession_->GetLastOpeId());
switch (obexClient_.clientSession_->GetLastOpeId()) {
case static_cast<uint8_t>(ObexOpeId::CONNECT):
HandleDataAvailableConnect(*resp);
break;
case static_cast<uint8_t>(ObexOpeId::DISCONNECT):
HandleDataAvailableDisconnect(*resp);
break;
case static_cast<uint8_t>(ObexOpeId::PUT):
case static_cast<uint8_t>(ObexOpeId::PUT_FINAL):
HandleDataAvailablePut(*resp);
break;
case static_cast<uint8_t>(ObexOpeId::GET):
case static_cast<uint8_t>(ObexOpeId::GET_FINAL):
HandleDataAvailableGet(*resp);
break;
case static_cast<uint8_t>(ObexOpeId::SETPATH):
HandleDataAvailableSetPath(*resp);
break;
case static_cast<uint8_t>(ObexOpeId::SESSION):
HandleDataAvailableSession(*resp);
break;
case static_cast<uint8_t>(ObexOpeId::ABORT):
HandleDataAvailableAbort(*resp);
break;
case static_cast<uint8_t>(ObexOpeId::ACTION):
HandleDataAvailableAction(*resp);
break;
default:
break;
}
}
void ObexClient::ObexClientTransportObserver::HandleDataAvailableAction(const ObexHeader &resp)
{
obexClient_.clientObserver_.OnActionCompleted(obexClient_, resp);
}
void ObexClient::ObexClientTransportObserver::HandleDataAvailableAbort(const ObexHeader &resp)
{
if (resp.GetFieldCode() == static_cast<uint8_t>(ObexRspCode::CONTINUE)) {
// Skip unfinished get/put contniue packet
OBEX_LOG_DEBUG("abort request is sended, therefore skip unfinished get/put contniue packet");
return;
}
obexClient_.AbortDataAvailable(resp);
}
void ObexClient::ObexClientTransportObserver::HandleDataAvailableSession(const ObexHeader &resp)
{
if (resp.GetFieldCode() == static_cast<uint8_t>(ObexRspCode::SUCCESS)) {
auto sessionParams = resp.GetItemSessionParams();
// sessionParams is not exists? do disconnect
if (sessionParams == nullptr) {
obexClient_.Disconnect();
return;
}
obexClient_.isReliableSessionCreated_ = true;
obexClient_.clientState_ = ObexClientState::RELIABLE_SESSION_CREATED;
// will support in the future: COPY Session param to ClientSession
obexClient_.SendConnectRequest(*obexClient_.connectReqHeader_);
} else {
obexClient_.clientObserver_.OnActionCompleted(obexClient_, resp);
}
}
void ObexClient::ObexClientTransportObserver::HandleDataAvailableSetPath(const ObexHeader &resp)
{
obexClient_.SetPathDataAvailable(resp);
}
void ObexClient::ObexClientTransportObserver::HandleDataAvailablePut(const ObexHeader &resp)
{
obexClient_.PutDataAvailable(resp);
}
void ObexClient::ObexClientTransportObserver::HandleDataAvailableGet(const ObexHeader &resp)
{
obexClient_.GetDataAvailable(resp);
}
void ObexClient::ObexClientTransportObserver::HandleDataAvailableDisconnect(const ObexHeader &resp)
{
obexClient_.clientObserver_.OnActionCompleted(obexClient_, resp);
obexClient_.clientState_ = ObexClientState::OBEX_DISCONNECTED;
obexClient_.isObexConnected_ = false;
obexClient_.connectReqHeader_ = nullptr;
obexClient_.clientTransport_->Disconnect();
}
void ObexClient::ObexClientTransportObserver::HandleDataAvailableConnect(const ObexHeader &resp)
{
if (resp.GetFieldCode() == static_cast<uint8_t>(ObexRspCode::SUCCESS)) {
obexClient_.clientState_ = ObexClientState::OBEX_CONNECTED;
// set connected and mtu
obexClient_.isObexConnected_ = true;
uint16_t serverMaxPktLen = *resp.GetFieldMaxPacketLength();
if (serverMaxPktLen > OBEX_MINIMUM_MTU && serverMaxPktLen < obexClient_.clientSession_->GetMaxPacketLength()) {
obexClient_.clientSession_->SetMaxPacketLength(serverMaxPktLen);
OBEX_LOG_DEBUG("MTU Reset to:%{public}d", serverMaxPktLen);
}
// connect id
auto connectId = resp.GetItemConnectionId();
if (connectId != nullptr) {
obexClient_.clientSession_->SetConnectId(connectId->GetWord());
}
obexClient_.clientObserver_.OnConnected(obexClient_, resp);
} else {
obexClient_.clientObserver_.OnConnectFailed(obexClient_, resp);
}
}
void ObexClient::ObexClientTransportObserver::OnTransportError(ObexTransport &transport, int errCd)
{
OBEX_LOG_INFO("Call %{public}s", __PRETTY_FUNCTION__);
OBEX_LOG_ERROR("ClientId: %{public}s, errCd: %{public}d", obexClient_.GetClientId().c_str(), errCd);
obexClient_.clientObserver_.OnTransportFailed(obexClient_, errCd);
}
std::unique_ptr<bluetooth::ObexHeader> ObexClient::ObexClientTransportObserver::GetObexHeaderFromPacket(
ObexPacket &obexPacket)
{
uint8_t *packetBuf = obexPacket.GetBuffer();
size_t packetBufSize = obexPacket.GetSize();
if (packetBufSize < ObexHeader::MIN_PACKET_LENGTH) {
OBEX_LOG_ERROR("dataSize[%{public}d] < min[%{public}d]", packetBufSize, ObexHeader::MIN_PACKET_LENGTH);
return nullptr;
}
uint16_t packetLength = ObexUtils::GetBufData16(&packetBuf[0], 1);
if (packetLength != packetBufSize) {
OBEX_LOG_ERROR("packetLength[%{public}d] != packetBufSize[%{public}d]", packetLength, packetBufSize);
return nullptr;
}
std::unique_ptr<bluetooth::ObexHeader> resp;
if (obexClient_.clientSession_->GetLastOpeId() == static_cast<uint8_t>(ObexOpeId::CONNECT)) {
resp = ObexHeader::ParseResponse(packetBuf, packetLength, true);
} else {
resp = ObexHeader::ParseResponse(packetBuf, packetLength, false);
}
if (resp == nullptr) {
OBEX_LOG_ERROR("ParseResponse failure");
return nullptr;
}
return resp;
}
ObexClient::ObexClient(const ObexClientConfig &config, ObexClientObserver &observer, utility::Dispatcher &dispatcher)
: clientObserver_(observer), dispatcher_(dispatcher)
{
OBEX_LOG_INFO("Call %{public}s", __PRETTY_FUNCTION__);
isObexConnected_ = false;
transportObserver_ = std::make_unique<ObexClientTransportObserver>(*this);
ObexClientSocketTransport::Option option;
option.addr_ = config.addr_;
option.scn_ = config.scn_;
option.mtu_ = config.mtu_;
option.lpsm_ = config.lpsm_;
option.isGoepL2capPSM_ = config.isGoepL2capPSM_;
clientTransport_ = std::make_unique<ObexClientSocketTransport>(option, *transportObserver_, dispatcher);
isSupportSrm_ = config.isSupportSrm_; // srm mode
isSupportReliableSession_ = config.isSupportReliableSession_;
clientSession_ = std::make_unique<ObexClientSession>(RawAddress::ConvertToString(config.addr_.addr));
clientSession_->SetMaxPacketLength(config.mtu_);
clientSession_->SetServiceUUID(config.serviceUUID_);
clientSession_->FreeSendObject();
connectReqHeader_ = nullptr;
clientState_ = ObexClientState::INIT;
}
// send obex request
int ObexClient::SendRequest(const ObexHeader &req)
{
OBEX_LOG_INFO("Call %{public}s", __PRETTY_FUNCTION__);
OBEX_LOG_INFO("ClientId: %{public}s", GetClientId().c_str());
if (req.GetFieldCode() == static_cast<uint8_t>(ObexOpeId::SESSION)) {
auto sessionParams = req.GetItemSessionParams();
if (sessionParams == nullptr) {
OBEX_LOG_ERROR("Request of session is invalid!");
return -1;
}
const TlvTriplet *tlv = sessionParams->GetTlvtriplet(ObexSessionParameters::SESSION_OPCODE);
if (tlv == nullptr) {
OBEX_LOG_ERROR("Request of session is invalid!");
return -1;
}
if (!CheckBeforeSession(tlv->GetVal()[0])) {
return -1;
}
} else {
if (!CheckBeforeRequest(req.GetFieldCode())) {
return -1;
}
}
if (req.GetFieldPacketLength() > clientSession_->GetMaxPacketLength()) {
OBEX_LOG_ERROR(
"Request packet length[%{public}d] > mtu[%{public}d].", req.GetFieldPacketLength(), clientSession_->GetMaxPacketLength());
return -1;
}
auto obexPacket = req.Build();
isProcessing_ = true;
bool ret = clientTransport_->Write(obexPacket->GetPacket());
if (!ret) {
OBEX_LOG_ERROR("SendRequest Fail!");
isProcessing_ = false;
return -1;
}
OBEX_LOG_DEBUG("Client Set lastOpeId: 0x%02X", req.GetFieldCode());
clientSession_->SetLastOpeId(req.GetFieldCode());
clientSession_->SetLastReqHeader(req);
return 0;
}
// send obex connect request
int ObexClient::Connect()
{
ObexConnectParams connectParams;
return Connect(connectParams);
}
// send obex connect request with params
int ObexClient::Connect(ObexConnectParams &connectParams)
{
OBEX_LOG_INFO("Call %{public}s", __PRETTY_FUNCTION__);
OBEX_LOG_INFO("ClientId: %{public}s", GetClientId().c_str());
if (!CheckBeforeRequest(static_cast<uint8_t>(ObexOpeId::CONNECT))) {
return -1;
}
std::unique_ptr<ObexHeader> header = ObexHeader::CreateRequest(ObexOpeId::CONNECT);
const BtUuid &serviceUUID = clientSession_->GetServiceUUID();
if (serviceUUID.uuid128[0] != 0x00) {
header->AppendItemTarget(&serviceUUID.uuid128[0], sizeof(serviceUUID.uuid128));
}
if (connectParams.appParams_ != nullptr) {
header->AppendItemAppParams(*connectParams.appParams_);
}
if (connectParams.authChallenges_ != nullptr) {
header->AppendItemAuthChallenges(*connectParams.authChallenges_);
}
if (connectParams.authResponses_ != nullptr) {
header->AppendItemAuthResponse(*connectParams.authResponses_);
}
// create transport before obex connect
if (!clientTransport_->IsConnected()) {
connectReqHeader_ = std::move(header);
return clientTransport_->Connect();
}
return SendConnectRequest(*header);
}
// send obex disconnect request
int ObexClient::Disconnect(bool withObexReq)
{
OBEX_LOG_INFO("Call %{public}s", __PRETTY_FUNCTION__);
OBEX_LOG_INFO("ClientId: %{public}s", GetClientId().c_str());
if (withObexReq) {
if (!CheckBeforeRequest(static_cast<uint8_t>(ObexOpeId::DISCONNECT))) {
return -1;
}
auto req = ObexHeader::CreateRequest(ObexOpeId::DISCONNECT);
if (isReliableSessionCreated_) {
req->AppendItemSessionSeqNum(clientSession_->GetReliableSession()->sessionSequenceNumber_++);
}
uint32_t connectId = clientSession_->GetConnectId();
if (connectId != 0x00) {
req->AppendItemConnectionId(connectId);
}
return SendRequest(*req);
}
return clientTransport_->Disconnect();
}
// send obex abort request
int ObexClient::Abort()
{
dispatcher_.PostTask(std::bind(&ObexClient::ProcessAbort, this));
return 0;
}
int ObexClient::ProcessAbort()
{
OBEX_LOG_INFO("Call %{public}s", __PRETTY_FUNCTION__);
OBEX_LOG_INFO("ClientId: %{public}s", GetClientId().c_str());
if (isWaitingSendAbort_ || isAbortSended_) {
OBEX_LOG_ERROR("Abort is processing!");
return -1;
}
isAbortSended_ = false;
if (isProcessing_) {
isAbortSended_ = false;
switch (clientSession_->GetLastOpeId()) {
case static_cast<uint8_t>(ObexOpeId::PUT):
case static_cast<uint8_t>(ObexOpeId::PUT_FINAL):
case static_cast<uint8_t>(ObexOpeId::GET):
case static_cast<uint8_t>(ObexOpeId::GET_FINAL):
isWaitingSendAbort_ = true;
break;
default:
isWaitingSendAbort_ = false;
break;
}
return 0;
}
return SendAbortRequest();
}
int ObexClient::SendAbortRequest()
{
OBEX_LOG_INFO("Call %{public}s", __PRETTY_FUNCTION__);
OBEX_LOG_INFO("ClientId: %{public}s", GetClientId().c_str());
if (!CheckBeforeRequest(static_cast<uint8_t>(ObexOpeId::ABORT))) {
return -1;
}
auto req = ObexHeader::CreateRequest(ObexOpeId::ABORT);
uint32_t connectId = clientSession_->GetConnectId();
if (connectId != 0x00) {
req->AppendItemConnectionId(connectId);
}
isWaitingSendAbort_ = false;
isAbortSended_ = true;
return SendRequest(*req);
}
// send obex put request
int ObexClient::Put(const ObexHeader &req)
{
OBEX_LOG_INFO("Call %{public}s", __PRETTY_FUNCTION__);
OBEX_LOG_INFO("ClientId: %{public}s", GetClientId().c_str());
if (!CheckBeforeRequest(req.GetFieldCode())) {
return -1;
}
if (req.GetFieldCode() != static_cast<uint8_t>(ObexOpeId::PUT) &&
req.GetFieldCode() != static_cast<uint8_t>(ObexOpeId::PUT_FINAL)) {
OBEX_LOG_ERROR("Opcode is wrong.");
return -1;
}
return SendRequest(req);
}
// send obex get request
int ObexClient::Get(const ObexHeader &req)
{
OBEX_LOG_INFO("Call %{public}s", __PRETTY_FUNCTION__);
OBEX_LOG_INFO("ClientId: %{public}s", GetClientId().c_str());
if (!CheckBeforeRequest(req.GetFieldCode())) {
return -1;
}
if (req.GetFieldCode() != static_cast<uint8_t>(ObexOpeId::GET) &&
req.GetFieldCode() != static_cast<uint8_t>(ObexOpeId::GET_FINAL)) {
OBEX_LOG_ERROR("Opcode is wrong.");
return -1;
}
return SendRequest(req);
}
// send obex set_path request
int ObexClient::SetPath(uint8_t flag, const std::u16string &path)
{
OBEX_LOG_INFO("Call %{public}s", __PRETTY_FUNCTION__);
OBEX_LOG_INFO("ClientId: %{public}s", GetClientId().c_str());
if (!CheckBeforeRequest(static_cast<uint8_t>(ObexOpeId::SETPATH))) {
return -1;
}
if (path.find(u"/") != std::u16string::npos) {
OBEX_LOG_ERROR("The path shall not include any path information!");
return -1;
}
auto req = ObexHeader::CreateRequest(ObexOpeId::SETPATH);
req->SetFieldFlags(flag);
uint32_t connectId = clientSession_->GetConnectId();
if (connectId != 0x00) {
req->AppendItemConnectionId(connectId);
}
if (path.length() > 0) {
req->AppendItemName(path);
}
return SendRequest(*req);
}
// send obex action request
int ObexClient::Copy(const std::u16string &srcName, const std::u16string &destName)
{
OBEX_LOG_INFO("Call %{public}s", __PRETTY_FUNCTION__);
OBEX_LOG_INFO("ClientId: %{public}s", GetClientId().c_str());
// will support in the future
return 0;
}
int ObexClient::Move(const std::u16string &srcName, const std::u16string &destName)
{
OBEX_LOG_INFO("Call %{public}s", __PRETTY_FUNCTION__);
OBEX_LOG_INFO("ClientId: %{public}s", GetClientId().c_str());
// will support in the future
return 0;
}
int ObexClient::SetPermissions(const std::u16string &name, const uint32_t permissions)
{
OBEX_LOG_INFO("Call %{public}s", __PRETTY_FUNCTION__);
OBEX_LOG_INFO("ClientId: %{public}s", GetClientId().c_str());
// will support in the future
return 0;
}
// send obex session request
// This command must include a Session-Parameters header containing the Session Opcode, Device Address and Nonce
// fields. Optionally, a Timeout field can be included.
int ObexClient::CreateSession()
{
OBEX_LOG_INFO("Call %{public}s", __PRETTY_FUNCTION__);
// will support in the future
return CreateSession(OBEX_SESSION_MAX_TIMEOUT_SEC);
}
int ObexClient::CreateSession(uint32_t timeoutSec)
{
OBEX_LOG_INFO("Call %{public}s", __PRETTY_FUNCTION__);
return 0;
}
// This command must include a Session-Parameters header containing the Session Opcode field.
// Optionally, a Timeout field can be included.
int ObexClient::SuspendSession()
{
OBEX_LOG_INFO("Call %{public}s", __PRETTY_FUNCTION__);
return 0;
}
// This command must include a Session-Parameters header containing the Session Opcode, Device Address, Nonce,
// and Session ID and fields. Optionally, a Timeout field can be included.
int ObexClient::ResumeSession()
{
OBEX_LOG_INFO("Call %{public}s", __PRETTY_FUNCTION__);
return 0;
}
// This command must include a Session-Parameters header containing the Session Opcode and Session ID fields.
int ObexClient::CloseSession()
{
OBEX_LOG_INFO("Call %{public}s", __PRETTY_FUNCTION__);
return 0;
}
// This command must include a Session-Parameters header containing the Session Opcode field.
// Optionally, a Timeout field can be included.
int ObexClient::SetSessionTimeout(uint32_t timeoutSec)
{
OBEX_LOG_INFO("Call %{public}s", __PRETTY_FUNCTION__);
return 0;
}
bool ObexClient::CheckBeforeSession(uint8_t sessionOpcode)
{
return true;
}
bool ObexClient::CheckBeforeRequest(uint8_t opeId) const
{
OBEX_LOG_INFO("Call %{public}s", __PRETTY_FUNCTION__);
if (isProcessing_) {
OBEX_LOG_ERROR("Another operation is being processed, please try again later.");
return false;
}
bool checkConnect = true;
bool needConnected = true;
switch (opeId) {
case static_cast<uint8_t>(ObexOpeId::CONNECT):
needConnected = false;
break;
case static_cast<uint8_t>(ObexOpeId::SESSION):
checkConnect = false; // Session's connect check is in CheckBeforeSession
break;
case static_cast<uint8_t>(ObexOpeId::DISCONNECT):
if (!isObexConnected_) {
OBEX_LOG_ERROR("Already Disconnected from the server.");
return false;
}
break;
default:
break;
}
if (checkConnect) {
if (needConnected && !isObexConnected_) {
OBEX_LOG_ERROR(
"Please connect first. Before obex connected, only SESSION(Create) and CONNECT Operation can "
"be called.");
return false;
}
if (!needConnected && isObexConnected_) {
OBEX_LOG_ERROR("Already connected to server.");
return false;
}
}
return true;
}
void ObexClient::PutDataAvailable(const ObexHeader &resp)
{
if (isWaitingSendAbort_) {
isProcessing_ = false;
SendAbortRequest();
return;
}
SetBusy(false);
clientObserver_.OnActionCompleted(*this, resp);
}
void ObexClient::GetDataAvailable(const ObexHeader &resp)
{
if (isWaitingSendAbort_) {
isProcessing_ = false;
SendAbortRequest();
return;
}
SetBusy(false);
clientObserver_.OnActionCompleted(*this, resp);
}
void ObexClient::SetPathDataAvailable(const ObexHeader &resp)
{
clientObserver_.OnActionCompleted(*this, resp);
}
void ObexClient::AbortDataAvailable(const ObexHeader &resp)
{
isWaitingSendAbort_ = false;
isAbortSended_ = false;
SetBusy(false);
clientObserver_.OnActionCompleted(*this, resp);
}
void ObexClient::HandleTransportDataBusy(uint8_t isBusy)
{
OBEX_LOG_INFO("Call %{public}s, isBusy %{public}d", __PRETTY_FUNCTION__, isBusy);
}
int ObexClient::SendConnectRequest(ObexHeader &header)
{
int minPacketSize = std::min(clientTransport_->GetMaxSendPacketSize(),
clientTransport_->GetMaxReceivePacketSize());
minPacketSize = std::min(minPacketSize, (int)clientSession_->GetMaxPacketLength());
if (minPacketSize > OBEX_MAXIMUM_MTU) {
minPacketSize = OBEX_MAXIMUM_MTU;
} else if (minPacketSize < OBEX_MINIMUM_MTU) {
minPacketSize = OBEX_MINIMUM_MTU;
}
header.SetFieldMaxPacketLength(minPacketSize);
clientSession_->SetMaxPacketLength(minPacketSize);
OBEX_LOG_DEBUG("SendConnect with mtu:%{public}d", minPacketSize);
return SendRequest(header);
}
const ObexClientSession &ObexClient::GetClientSession() const
{
return *clientSession_;
}
const std::string &ObexClient::GetClientId()
{
if (clientId_.empty()) {
clientId_ = (clientTransport_ == nullptr) ? "" : clientTransport_->GetTransportKey();
}
return clientId_;
}
int ObexClient::RegisterL2capLPsm(uint16_t lpsm)
{
OBEX_LOG_INFO("Call %{public}s", __PRETTY_FUNCTION__);
OBEX_LOG_INFO("RegisterL2capLPsm: 0x%04X", lpsm);
return L2capTransport::RegisterClientPsm(lpsm);
}
void ObexClient::DeregisterL2capLPsm(uint16_t lpsm)
{
OBEX_LOG_INFO("Call %{public}s", __PRETTY_FUNCTION__);
OBEX_LOG_INFO("DeregisterL2capLPsm: 0x%04X", lpsm);
L2capTransport::DeregisterClientPsm(lpsm);
}
void ObexClient::SetBusy(bool isBusy)
{
if (clientSession_->IsBusy() != isBusy) {
clientSession_->SetBusy(isBusy);
OBEX_LOG_INFO("[%{public}s] ObexBusy=%{public}d", GetClientId().c_str(), isBusy);
clientObserver_.OnBusy(*this, isBusy);
}
}
void ObexClientObserver::OnBusy(ObexClient &client, bool isBusy)
{
OBEX_LOG_INFO("Call %{public}s", __PRETTY_FUNCTION__);
}
} // namespace bluetooth
| [
"guohong.cheng@huawei.com"
] | guohong.cheng@huawei.com |
f5c678bf4cedbb11cadf9308b17f17a6c9e9251c | a3c86fda4f54e621646afbb771d5fb7ec209120e | /tiendaDisco.cpp | 5dc65b17d77cd541b4e8e8fc88950ad958706118 | [] | no_license | angeloaroni/ejerciciosCpp | 9464cabfe6f1e15a9bfa440c090fde7c1796c5d6 | 845f6e58991e5915dc7eeef6f2bb7307f5ea0099 | refs/heads/master | 2022-01-14T11:49:20.802399 | 2019-06-11T06:55:08 | 2019-06-11T06:55:08 | 188,807,403 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 764 | cpp | //guardar 2 discos
//guarda titulo, autor, estilo
//dos formas:
//1.- con tres vectores
//2.- un vector de 2 dimensiones
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "conio.h"
#include <iomanip>
using namespace std;
int main() {
string titulo[2];
string autor[2];
string estilo[2];
for (int i = 0; i < 2; i++) {
titulo[i]="";
autor[i]="";
estilo[i]="";
}
for (int i = 0; i < 2; i++) {
cout << "Titulo: " << endl;
cin >> titulo[i];
cout << "Autor: " << endl;
cin >> autor[i];
cout << "Estilo: " << endl;
cin >> estilo[i];
}
for (int i = 0; i < 2; i++) {
cout << "Nombre " << titulo[i] << endl;
cout << "Autor: " << autor[i] << endl;
cout << "Estilo: " << estilo[i] << endl;
}
}
| [
"angeduff@hotmail.com"
] | angeduff@hotmail.com |
2c3bc14ce0a1649170b9d797f5314e7fd4df2016 | 4aefbe007452d6e3de3ce32b9aca320546c25db3 | /com.cpp | b186c2c0e729b33946bc035277499c5f82c49117 | [] | no_license | lasellers/CFX_IIS | a97054d7151f7c9d3654ba4e1b6883594032a1b7 | 91864fba4c2d5536bddb722a923c7a8264b61168 | refs/heads/master | 2020-06-08T06:17:53.816790 | 2012-09-21T07:26:43 | 2012-09-21T07:26:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,598 | cpp | /* #ifndef UNICODE
#define UNICODE
#endif
#ifndef _UNICODE
#define _UNICODE
#endif */
#include "stdafx.h" // Standard MFC libraries
#include "activeds.h"
#include "afxpriv.h" // MFC Unicode conversion macros
#include "cfx.h" //..\..\classes\cfx.h" // CFX Custom Tag API
#include "basetsd.h"
#include "lmaccess.h" // UNLEN LM20_PWLEN
#include "wchar.h"
// bstr
#include <objidl.h>
#include <comdef.h>
// adsi
#include <iads.h>
#include <adshlp.h>
//
#include <stdlib.h>
#include <adssts.h>
// errs
#include "winerror.h"
#include "lmerr.h"
//safearray
#include "oleauto.h"
//
#include "common.h" //..\..\classes\common.h"
// about
//#include "about.h" //..\..\classes\about.h"
// ihtkpassword
//#include "ihtkpassword.h" //a..\..\classes\ihtkpassword.h"
//general error reporting
#include "err.h" //..\..\classes\err.h"
//com error reporting
#include "com.h" //..\..\classes\com.h"
#include "utility.h"
#include "support.h"
// ////////////////////////////////////////////////////////////////////////
// ////////////////////////////////////////////////////////////////////////
// ///////////////////////////////////////////////////////////////////////
// v 1.3 COM Error Reporting
void log_COMError(int line, HRESULT hr)
{
if (FAILED(hr))
{
//
int Sev=(hr>>30)&3;
int C=(hr>>29)&1;
int R=(hr>>28)&1;
int Facility=(hr>>16)&4095;
int Code=hr&65535;
//
CString buf;
//
CString strSev;
switch(Sev)
{
case 0: strSev="SUCCESS"; break;
case 1: strSev="INFORMATIONAL"; break;
case 2: strSev="WARNING"; break;
case 3: strSev="ERROR"; break;
};
CString strFacility;
switch(Facility)
{
case FACILITY_WINDOWS: strFacility="WINDOWS"; break; //8
case FACILITY_URT: strFacility="URT"; break; //19
case FACILITY_STORAGE: strFacility="STORAGE"; break; //3
//case FACILITY_SSPI: strFacility="SSPI"; break; //9
case FACILITY_SCARD: strFacility="SCARD"; break; //16
case FACILITY_SETUPAPI: strFacility="SETUPAPI"; break; //15
case FACILITY_SECURITY: strFacility="SECURITY"; break; //9
case FACILITY_RPC: strFacility="RPC"; break; //1
case FACILITY_WIN32: strFacility="WIN32"; break; //7
case FACILITY_CONTROL: strFacility="CONTROL"; break; // 10
case FACILITY_NULL: strFacility="NULL"; break; //0
case FACILITY_MSMQ: strFacility="MSMQ"; break; //14
case FACILITY_MEDIASERVER: strFacility="MEDIASERVER"; break; //13
case FACILITY_INTERNET: strFacility="INTERNET"; break; //12
case FACILITY_ITF: strFacility="ITF"; break; //4
case FACILITY_DISPATCH: strFacility="DISPATCH"; break; //2
case FACILITY_COMPLUS: strFacility="COMPLUS"; break; //17
case FACILITY_CERT: strFacility="CERT"; break; //11
case FACILITY_ACS: strFacility="ACS"; break; //20
case FACILITY_AAF: strFacility="AAF"; break; //18
default: strFacility="UNKNOWN";
};
//
buf.Format("ADSI Error 0x%x(%d) (Severity=%u %s Customer=%u Reserve=%u Facility=%u %s Code=0x%X(%d)) ",
hr,
hr,
Sev,
strSev,
C,
R,
Facility,
strFacility,
Code,
Code
);
log_Error(__LINE__,buf);
//if facility is Win32, get the Win32 error
if (HRESULT_FACILITY(hr)==FACILITY_WIN32)
{
DWORD dwLastError;
WCHAR szErrorBuf[MAX_ERRTEXT];
WCHAR szNameBuf[MAX_ERRTEXT];
//Get extended error value.
HRESULT hr_return = S_OK;
hr_return = ADsGetLastError( &dwLastError, szErrorBuf, MAX_ERRTEXT-2, szNameBuf, MAX_ERRTEXT-2);
if (SUCCEEDED(hr_return))
{
buf.Format("LastError=0x%x(%d) Text=%ws Provider=%ws ", dwLastError,dwLastError, szErrorBuf, szNameBuf);
}
if(dwLastError==0)
{
LPVOID lpMsgBuf;
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
Code,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR)&lpMsgBuf,
MAX_ERRTEXT-2,
NULL
);
buf.Format(" %s ", lpMsgBuf);
LocalFree( lpMsgBuf );
}
log_Error(__LINE__,buf);
}
log_appendline(line);
}
}
//MK_E_SYNTAX 800401e4
//
//
// Values are 32 bit values layed out as follows:
//
// 3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1
// 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0
// +---+-+-+-----------------------+-------------------------------+
// |Sev|C|R| Facility | Code |
// +---+-+-+-----------------------+-------------------------------+
//
// where
//
// Sev - is the severity code
//
// 00 - Success
// 01 - Informational
// 10 - Warning
// 11 - Error
//
// C - is the Customer code flag
//
// R - is a reserved bit
//
// Facility - is the facility code
//
// Code - is the facility's status code
| [
"lasellers@gmail.com"
] | lasellers@gmail.com |
43d7c860515a4971aa2de68a2788adc9c473b8d7 | 41b4adb10cc86338d85db6636900168f55e7ff18 | /aws-cpp-sdk-dynamodb/source/model/BatchGetItemRequest.cpp | e86964db1934e1051c06a93c9e441fd56fb23ec2 | [
"JSON",
"MIT",
"Apache-2.0"
] | permissive | totalkyos/AWS | 1c9ac30206ef6cf8ca38d2c3d1496fa9c15e5e80 | 7cb444814e938f3df59530ea4ebe8e19b9418793 | refs/heads/master | 2021-01-20T20:42:09.978428 | 2016-07-16T00:03:49 | 2016-07-16T00:03:49 | 63,465,708 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,790 | cpp | /*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 <aws/dynamodb/model/BatchGetItemRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::DynamoDB::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
BatchGetItemRequest::BatchGetItemRequest() :
m_requestItemsHasBeenSet(false),
m_returnConsumedCapacityHasBeenSet(false)
{
}
Aws::String BatchGetItemRequest::SerializePayload() const
{
JsonValue payload;
if(m_requestItemsHasBeenSet)
{
JsonValue requestItemsJsonMap;
for(auto& requestItemsItem : m_requestItems)
{
requestItemsJsonMap.WithObject(requestItemsItem.first, requestItemsItem.second.Jsonize());
}
payload.WithObject("RequestItems", std::move(requestItemsJsonMap));
}
if(m_returnConsumedCapacityHasBeenSet)
{
payload.WithString("ReturnConsumedCapacity", ReturnConsumedCapacityMapper::GetNameForReturnConsumedCapacity(m_returnConsumedCapacity));
}
return payload.WriteReadable();
}
Aws::Http::HeaderValueCollection BatchGetItemRequest::GetRequestSpecificHeaders() const
{
Aws::Http::HeaderValueCollection headers;
headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "DynamoDB_20120810.BatchGetItem"));
return headers;
}
| [
"henso@amazon.com"
] | henso@amazon.com |
453c813879f3d4fcf824a95609d6fb4007c7f60c | aaebd5f24daa3cf77e9864e1f706867bd8703eb9 | /Clean_184_01/0/T | 8c19580ff73be2911b2166817c3f180333c2bf0c | [] | no_license | JDTyvand/InternalWaves | 9919e535f1a09fd19c8b09152401dfd80144edc3 | 0e086f9a949031a68819e95f4cea79ebfbf7999c | refs/heads/master | 2016-08-12T20:55:50.831153 | 2015-12-16T10:02:40 | 2015-12-16T10:02:40 | 47,399,324 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 101,337 | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: 2.4.0 |
| \\ / A nd | Web: www.OpenFOAM.org |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volScalarField;
location "0";
object T;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 0 0 1 0 0 0];
internalField nonuniform List<scalar>
14168
(
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
10.6625
10.6625
10.6625
10.6625
10.6625
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
16.325
16.325
16.325
16.325
16.325
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
21.9875
21.9875
21.9875
21.9875
21.9875
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
27.65
27.65
27.65
27.65
27.65
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
33.3125
33.3125
33.3125
33.3125
33.3125
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
38.975
38.975
38.975
38.975
38.975
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
44.6375
44.6375
44.6375
44.6375
44.6375
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
50.3
50.3
50.3
50.3
50.3
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
55.9625
55.9625
55.9625
55.9625
55.9625
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
61.625
61.625
61.625
61.625
61.625
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
67.2875
67.2875
67.2875
67.2875
67.2875
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
72.95
72.95
72.95
72.95
72.95
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
72.95
72.95
72.95
72.95
72.95
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
72.95
72.95
72.95
72.95
72.95
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
72.95
72.95
72.95
72.95
72.95
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
72.95
72.95
72.95
72.95
72.95
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
72.95
72.95
72.95
72.95
72.95
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
72.95
72.95
72.95
72.95
72.95
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
72.95
72.95
72.95
72.95
72.95
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
72.95
72.95
72.95
72.95
72.95
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
72.95
72.95
72.95
72.95
72.95
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
72.95
72.95
72.95
72.95
72.95
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
72.95
72.95
72.95
72.95
72.95
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
72.95
72.95
72.95
72.95
72.95
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
72.95
72.95
72.95
72.95
72.95
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
72.95
72.95
72.95
72.95
72.95
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
72.95
72.95
72.95
72.95
72.95
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
72.95
72.95
72.95
72.95
72.95
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
72.95
72.95
72.95
72.95
72.95
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
6.99852941176
72.95
72.95
72.95
72.95
72.95
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
8.99705882353
72.95
72.95
72.95
72.95
72.95
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
10.9955882353
72.95
72.95
72.95
72.95
72.95
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
12.9941176471
72.95
72.95
72.95
72.95
72.95
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
14.9926470588
72.95
72.95
72.95
72.95
72.95
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
16.9911764706
72.95
72.95
72.95
72.95
72.95
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
18.9897058824
72.95
72.95
72.95
72.95
72.95
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
20.9882352941
72.95
72.95
72.95
72.95
72.95
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
22.9867647059
72.95
72.95
72.95
72.95
72.95
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
24.9852941176
72.95
72.95
72.95
72.95
72.95
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
26.9838235294
72.95
72.95
72.95
72.95
72.95
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
28.9823529412
72.95
72.95
72.95
72.95
72.95
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
30.9808823529
72.95
72.95
72.95
72.95
72.95
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
32.9794117647
72.95
72.95
72.95
72.95
72.95
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
34.9779411765
72.95
72.95
72.95
72.95
72.95
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
36.9764705882
72.95
72.95
72.95
72.95
72.95
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
38.975
72.95
72.95
72.95
72.95
72.95
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
40.9735294118
72.95
72.95
72.95
72.95
72.95
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
42.9720588235
72.95
72.95
72.95
72.95
72.95
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
44.9705882353
72.95
72.95
72.95
72.95
72.95
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
46.9691176471
72.95
72.95
72.95
72.95
72.95
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
48.9676470588
72.95
72.95
72.95
72.95
72.95
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
50.9661764706
72.95
72.95
72.95
72.95
72.95
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
52.9647058824
72.95
72.95
72.95
72.95
72.95
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
54.9632352941
72.95
72.95
72.95
72.95
72.95
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
56.9617647059
72.95
72.95
72.95
72.95
72.95
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
58.9602941176
72.95
72.95
72.95
72.95
72.95
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
60.9588235294
72.95
72.95
72.95
72.95
72.95
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
62.9573529412
72.95
72.95
72.95
72.95
72.95
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
64.9558823529
72.95
72.95
72.95
72.95
72.95
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
66.9544117647
72.95
72.95
72.95
72.95
72.95
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
68.9529411765
72.95
72.95
72.95
72.95
72.95
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
70.9514705882
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
72.95
)
;
boundaryField
{
leftWall
{
type zeroGradient;
}
rightWall
{
type zeroGradient;
}
lowerWall
{
type fixedValue;
value uniform 5;
}
atmosphere
{
type fixedValue;
value uniform 72.95;
}
defaultFaces
{
type empty;
}
}
// ************************************************************************* //
| [
"jorgentyvand@gmail.com"
] | jorgentyvand@gmail.com | |
2363c733ad96ea2ccf375aa647da1504ea4ef2c4 | 0d2279376e5b9398f321993fb3993ddb5c18cf4a | /MotorControl.ino | d95347ab5b07b44c719e6363b63cf971f7a07ecf | [] | no_license | alexForver/Air_Hockey_Project | 9e6955abab27665a6027cc22de981f71ed2d7c09 | bdec6b4cc2128ed80225aa7aa0cb98a40170bdf0 | refs/heads/master | 2020-05-23T05:56:37.178684 | 2019-05-14T16:15:30 | 2019-05-14T16:15:30 | 186,657,536 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,535 | ino | #define EN 8 // port8=stepper enable/disable, active low
#define ENZ 1 // enable stepper motor, active low
#define Y_DIR 6 // PE4
#define Y_STP 3 // PE1
#define X_DIR 5 // PE3
#define X_STP 2 // PE0
#define MAX_SPEED 150
#define ZERO_SPEED 1000 //30000 //65535
#define X_step_per_mm 5
#define Y_step_per_mm 5
volatile unsigned int max_speed = MAX_SPEED;
volatile int16_t abs_target_m1_step = 0;
volatile int16_t abs_target_m2_step = 0;
volatile int16_t m1_stepCount = 0;
volatile int16_t m2_stepCount = 0;
volatile int16_t m1_stepPosition = 0;
volatile int16_t m2_stepPosition = 0;
volatile float factor1 = 1.0;
volatile float factor2 = 1.0;
volatile float factor11 = 1.0;
volatile float factor22 = 1.0;
volatile int16_t m1_dir = 0;
volatile int16_t m2_dir = 0;
volatile bool m1_moveDone = false;
volatile bool m2_moveDone = false;
volatile int16_t m1_rampUpStepCount = 0;
volatile int16_t m2_rampUpStepCount = 0;
volatile int16_t n1 = 0;
volatile int16_t n2 = 0;
volatile unsigned int d1 = 0;
volatile unsigned int d2 = 0;
uint32_t timer_old;
void setup() {
pinMode(X_STP, OUTPUT);
pinMode(X_DIR, OUTPUT);
pinMode(Y_STP, OUTPUT);
pinMode(Y_DIR, OUTPUT);
pinMode(EN, OUTPUT);
pinMode(ENZ, OUTPUT);
Serial.begin(115200); // PC debug connection
Serial.println("Ready:");
while (!(Serial.available())) {}
char a = Serial.read();
if (!(a == 'a'))
while (1);
digitalWrite(ENZ, LOW);
digitalWrite(EN, LOW);
TCCR1A = 0;
TCCR1B &= ~(1 << WGM13);
TCCR1B |= (1 << WGM12);
TCCR1B |= ((1 << CS10) | (1 << CS11)); // Start timer at Fcpu/64
TCNT1 = 0;
TCCR3A = 0;
TCCR3B &= ~(1 << WGM13);
TCCR3B |= (1 << WGM12);
TCCR3B |= ((1 << CS10) | (1 << CS11)); // Start timer at Fcpu/64
TCNT3 = 0;
sei();
timer_old = micros();
}
void loop() {
moveToPosition(200,200);
delay(500);
moveToPosition(0,100);
delay(500);
moveToPosition(-200,0);
delay(500);
moveToPosition(200,-100);
delay(500);
moveToPosition(-400,-100);
delay(500);
moveToPosition(200,-100);
while (true) {};
}
ISR(TIMER1_COMPA_vect)
{
if ( m1_stepCount < abs_target_m1_step )
{
digitalWrite(X_STP, HIGH);
__asm__ __volatile__ (
"nop" "\n\t"
"nop" "\n\t"
"nop" "\n\t"
"nop" "\n\t"
"nop" "\n\t"
"nop" "\n\t"
"nop" "\n\t"
"nop" "\n\t"
"nop" "\n\t"
"nop" "\n\t"
"nop" "\n\t"
"nop"); // Wait for step pulse
digitalWrite(X_STP, LOW);
m1_stepCount ++;
m1_stepPosition += m1_dir;
} else {
m1_moveDone = true;
TIMSK1 &= ~(1 << OCIE1A);
}
if ( m1_rampUpStepCount == 0 ) {
n1 ++;
d1 = d1 - int( 2 * float(d1) / (4 * float(n1) + 1));
//d1 = d1 - 2 * d1 / (4 * n1 + 1);
if ( d1 <= max_speed ) { //reach the max speed
d1 = max_speed;
m1_rampUpStepCount = m1_stepCount;
}
if ( m1_stepCount >= (abs_target_m1_step / 2 )) { //should start decel
m1_rampUpStepCount = m1_stepCount;
}
}
else if (m1_stepCount > (abs_target_m1_step - m1_rampUpStepCount)) { //decel
n1 --;
d1 = d1 * (4 * n1 + 1) / (4 * n1 - 1);
}
OCR1A = d1*factor11;
}
ISR(TIMER3_COMPA_vect)
{
if ( m2_stepCount < abs_target_m2_step )
{
digitalWrite(Y_STP, HIGH);
__asm__ __volatile__ (
"nop" "\n\t"
"nop" "\n\t"
"nop" "\n\t"
"nop" "\n\t"
"nop" "\n\t"
"nop" "\n\t"
"nop" "\n\t"
"nop" "\n\t"
"nop" "\n\t"
"nop" "\n\t"
"nop" "\n\t"
"nop"); // Wait for step pulse
digitalWrite(Y_STP, LOW);
m2_stepCount ++;
m2_stepPosition += m2_dir;
} else {
m2_moveDone = true;
TIMSK3 &= ~(1 << OCIE1A);
}
if ( m2_rampUpStepCount == 0 ) {
n2 ++;
d2 = d2 - int( 2 * float(d2) / (4 * float(n2) + 1));
//d2 = d2 - 2 * d2 / (4 * n2 + 1);
if ( d2 <= max_speed ) {
d2 = max_speed;
m2_rampUpStepCount = m2_stepCount;
}
if ( m2_stepCount >= (abs_target_m2_step / 2) ) {
m2_rampUpStepCount = m2_stepCount;
}
}
else if (m2_stepCount > (abs_target_m2_step - m2_rampUpStepCount)) {
n2 --;
d2 = d2 * (4 * n2 + 1) / (4 * n2 - 1);
}
OCR3A = d2*factor22;
}
void moveNSteps( int16_t target_y_mm,int16_t target_x_mm)
{
int16_t target_m1_step = X_step_per_mm * target_x_mm - Y_step_per_mm * target_y_mm;
int16_t target_m2_step = -X_step_per_mm * target_x_mm - Y_step_per_mm * target_y_mm;
digitalWrite(X_DIR, target_m1_step < 0 ? LOW : HIGH);
digitalWrite(Y_DIR, target_m2_step < 0 ? LOW : HIGH);
m1_dir = target_m1_step < 0 ? -1 : 1;
m2_dir = target_m2_step < 0 ? -1 : 1;
abs_target_m1_step = abs(target_m1_step);
abs_target_m2_step = abs(target_m2_step);
d1 = ZERO_SPEED * 0.676;
d2 = ZERO_SPEED * 0.676;
OCR1A = d1;
OCR3A = d2;
n1 = 0;
n2 = 0;
m1_stepCount = 0;
m2_stepCount = 0;
m1_rampUpStepCount = 0;
m2_rampUpStepCount = 0;
m1_moveDone = false;
m2_moveDone = false;
factor11 = 1.0;
factor22 = 1.0;
TIMSK1 |= (1 << OCIE1A);
TIMSK3 |= (1 << OCIE1A);
}
void moveToPosition(int16_t target_x_mm, int16_t target_y_mm )
{
int16_t diff1;
int16_t diff2;
moveNSteps(target_x_mm, target_y_mm);
while ( !m1_moveDone || !m2_moveDone ) {
diff1 = abs(abs_target_m1_step) - m1_stepCount;
diff2 = abs(abs_target_m2_step) - m2_stepCount;
if ( (diff2 > diff1) && (diff1!=0) ) {
factor11 = diff2 / diff1;
} else if((diff2 < diff1) && (diff2 !=0) ) {
factor22 = diff1 / diff2;
}else{
factor11 = 1.0;
factor22 = 1.0;
}
}
}
| [
"noreply@github.com"
] | noreply@github.com |
5a239cb13f5cfb9f93c7b291c96f80f1b87f9f4e | b1aef802c0561f2a730ac3125c55325d9c480e45 | /src/test/core/SociDB_test.cpp | b5c7b65d0b06962b9f1dc3340c61a8040f9d3835 | [] | no_license | sgy-official/sgy | d3f388cefed7cf20513c14a2a333c839aa0d66c6 | 8c5c356c81b24180d8763d3bbc0763f1046871ac | refs/heads/master | 2021-05-19T07:08:54.121998 | 2020-03-31T11:08:16 | 2020-03-31T11:08:16 | 251,577,856 | 6 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 11,950 | cpp |
#include <ripple/core/ConfigSections.h>
#include <ripple/core/SociDB.h>
#include <ripple/basics/contract.h>
#include <test/jtx/TestSuite.h>
#include <ripple/basics/BasicConfig.h>
#include <boost/filesystem.hpp>
#include <boost/algorithm/string.hpp>
namespace ripple {
class SociDB_test final : public TestSuite
{
private:
static void setupSQLiteConfig (BasicConfig& config,
boost::filesystem::path const& dbPath)
{
config.overwrite ("sqdb", "backend", "sqlite");
auto value = dbPath.string ();
if (!value.empty ())
config.legacy ("database_path", value);
}
static void cleanupDatabaseDir (boost::filesystem::path const& dbPath)
{
using namespace boost::filesystem;
if (!exists (dbPath) || !is_directory (dbPath) || !is_empty (dbPath))
return;
remove (dbPath);
}
static void setupDatabaseDir (boost::filesystem::path const& dbPath)
{
using namespace boost::filesystem;
if (!exists (dbPath))
{
create_directory (dbPath);
return;
}
if (!is_directory (dbPath))
{
Throw<std::runtime_error> (
"Cannot create directory: " + dbPath.string ());
}
}
static boost::filesystem::path getDatabasePath ()
{
return boost::filesystem::current_path () / "socidb_test_databases";
}
public:
SociDB_test ()
{
try
{
setupDatabaseDir (getDatabasePath ());
}
catch (std::exception const&)
{
}
}
~SociDB_test ()
{
try
{
cleanupDatabaseDir (getDatabasePath ());
}
catch (std::exception const&)
{
}
}
void testSQLiteFileNames ()
{
testcase ("sqliteFileNames");
BasicConfig c;
setupSQLiteConfig (c, getDatabasePath ());
std::vector<std::pair<std::string, std::string>> const d (
{{"peerfinder", ".sqlite"},
{"state", ".db"},
{"random", ".db"},
{"validators", ".sqlite"}});
for (auto const& i : d)
{
SociConfig sc (c, i.first);
BEAST_EXPECT(boost::ends_with (sc.connectionString (),
i.first + i.second));
}
}
void testSQLiteSession ()
{
testcase ("open");
BasicConfig c;
setupSQLiteConfig (c, getDatabasePath ());
SociConfig sc (c, "SociTestDB");
std::vector<std::string> const stringData (
{"String1", "String2", "String3"});
std::vector<int> const intData ({1, 2, 3});
auto checkValues = [this, &stringData, &intData](soci::session& s)
{
std::vector<std::string> stringResult (20 * stringData.size ());
std::vector<int> intResult (20 * intData.size ());
s << "SELECT StringData, IntData FROM SociTestTable;",
soci::into (stringResult), soci::into (intResult);
BEAST_EXPECT(stringResult.size () == stringData.size () &&
intResult.size () == intData.size ());
for (int i = 0; i < stringResult.size (); ++i)
{
auto si = std::distance (stringData.begin (),
std::find (stringData.begin (),
stringData.end (),
stringResult[i]));
auto ii = std::distance (
intData.begin (),
std::find (intData.begin (), intData.end (), intResult[i]));
BEAST_EXPECT(si == ii && si < stringResult.size ());
}
};
{
soci::session s;
sc.open (s);
s << "CREATE TABLE IF NOT EXISTS SociTestTable ("
" Key INTEGER PRIMARY KEY,"
" StringData TEXT,"
" IntData INTEGER"
");";
s << "INSERT INTO SociTestTable (StringData, IntData) VALUES "
"(:stringData, :intData);",
soci::use (stringData), soci::use (intData);
checkValues (s);
}
{
soci::session s;
sc.open (s);
checkValues (s);
}
{
namespace bfs = boost::filesystem;
bfs::path dbPath (sc.connectionString ());
if (bfs::is_regular_file (dbPath))
bfs::remove (dbPath);
}
}
void testSQLiteSelect ()
{
testcase ("select");
BasicConfig c;
setupSQLiteConfig (c, getDatabasePath ());
SociConfig sc (c, "SociTestDB");
std::vector<std::uint64_t> const ubid (
{(std::uint64_t)std::numeric_limits<std::int64_t>::max (), 20, 30});
std::vector<std::int64_t> const bid ({-10, -20, -30});
std::vector<std::uint32_t> const uid (
{std::numeric_limits<std::uint32_t>::max (), 2, 3});
std::vector<std::int32_t> const id ({-1, -2, -3});
{
soci::session s;
sc.open (s);
s << "DROP TABLE IF EXISTS STT;";
s << "CREATE TABLE STT ("
" I INTEGER,"
" UI INTEGER UNSIGNED,"
" BI BIGINT,"
" UBI BIGINT UNSIGNED"
");";
s << "INSERT INTO STT (I, UI, BI, UBI) VALUES "
"(:id, :idu, :bid, :bidu);",
soci::use (id), soci::use (uid), soci::use (bid),
soci::use (ubid);
try
{
std::int32_t ig = 0;
std::uint32_t uig = 0;
std::int64_t big = 0;
std::uint64_t ubig = 0;
s << "SELECT I, UI, BI, UBI from STT;", soci::into (ig),
soci::into (uig), soci::into (big), soci::into (ubig);
BEAST_EXPECT(ig == id[0] && uig == uid[0] && big == bid[0] &&
ubig == ubid[0]);
}
catch (std::exception&)
{
fail ();
}
try
{
boost::optional<std::int32_t> ig;
boost::optional<std::uint32_t> uig;
boost::optional<std::int64_t> big;
boost::optional<std::uint64_t> ubig;
s << "SELECT I, UI, BI, UBI from STT;", soci::into (ig),
soci::into (uig), soci::into (big), soci::into (ubig);
BEAST_EXPECT(*ig == id[0] && *uig == uid[0] && *big == bid[0] &&
*ubig == ubid[0]);
}
catch (std::exception&)
{
fail ();
}
#if 0
try
{
std::int32_t ig = 0;
std::uint32_t uig = 0;
std::int64_t big = 0;
std::uint64_t ubig = 0;
soci::row r;
s << "SELECT I, UI, BI, UBI from STT", soci::into (r);
ig = r.get<std::int32_t>(0);
uig = r.get<std::uint32_t>(1);
big = r.get<std::int64_t>(2);
ubig = r.get<std::uint64_t>(3);
BEAST_EXPECT(ig == id[0] && uig == uid[0] && big == bid[0] &&
ubig == ubid[0]);
}
catch (std::exception&)
{
fail ();
}
try
{
std::int32_t ig = 0;
std::uint32_t uig = 0;
std::int64_t big = 0;
std::uint64_t ubig = 0;
soci::row r;
s << "SELECT I, UI, BI, UBI from STT", soci::into (r);
ig = r.get<std::int32_t>("I");
uig = r.get<std::uint32_t>("UI");
big = r.get<std::int64_t>("BI");
ubig = r.get<std::uint64_t>("UBI");
BEAST_EXPECT(ig == id[0] && uig == uid[0] && big == bid[0] &&
ubig == ubid[0]);
}
catch (std::exception&)
{
fail ();
}
try
{
boost::tuple<std::int32_t,
std::uint32_t,
std::int64_t,
std::uint64_t> d;
s << "SELECT I, UI, BI, UBI from STT", soci::into (d);
BEAST_EXPECT(get<0>(d) == id[0] && get<1>(d) == uid[0] &&
get<2>(d) == bid[0] && get<3>(d) == ubid[0]);
}
catch (std::exception&)
{
fail ();
}
#endif
}
{
namespace bfs = boost::filesystem;
bfs::path dbPath (sc.connectionString ());
if (bfs::is_regular_file (dbPath))
bfs::remove (dbPath);
}
}
void testSQLiteDeleteWithSubselect()
{
testcase ("deleteWithSubselect");
BasicConfig c;
setupSQLiteConfig (c, getDatabasePath ());
SociConfig sc (c, "SociTestDB");
{
soci::session s;
sc.open (s);
const char* dbInit[] = {
"BEGIN TRANSACTION;",
"CREATE TABLE Ledgers ( \
LedgerHash CHARACTER(64) PRIMARY KEY, \
LedgerSeq BIGINT UNSIGNED \
);",
"CREATE INDEX SeqLedger ON Ledgers(LedgerSeq);",
"CREATE TABLE Validations ( \
LedgerHash CHARACTER(64) \
);",
"CREATE INDEX ValidationsByHash ON \
Validations(LedgerHash);",
"END TRANSACTION;"};
int dbInitCount = std::extent<decltype(dbInit)>::value;
for (int i = 0; i < dbInitCount; ++i)
{
s << dbInit[i];
}
char lh[65];
memset (lh, 'a', 64);
lh[64] = '\0';
int toIncIndex = 63;
int const numRows = 16;
std::vector<std::string> ledgerHashes;
std::vector<int> ledgerIndexes;
ledgerHashes.reserve(numRows);
ledgerIndexes.reserve(numRows);
for (int i = 0; i < numRows; ++i)
{
++lh[toIncIndex];
if (lh[toIncIndex] == 'z')
--toIncIndex;
ledgerHashes.emplace_back(lh);
ledgerIndexes.emplace_back(i);
}
s << "INSERT INTO Ledgers (LedgerHash, LedgerSeq) VALUES "
"(:lh, :li);",
soci::use (ledgerHashes), soci::use (ledgerIndexes);
s << "INSERT INTO Validations (LedgerHash) VALUES "
"(:lh);", soci::use (ledgerHashes);
std::vector<int> ledgersLS (numRows * 2);
std::vector<std::string> validationsLH (numRows * 2);
s << "SELECT LedgerSeq FROM Ledgers;", soci::into (ledgersLS);
s << "SELECT LedgerHash FROM Validations;",
soci::into (validationsLH);
BEAST_EXPECT(ledgersLS.size () == numRows &&
validationsLH.size () == numRows);
}
namespace bfs = boost::filesystem;
bfs::path dbPath (sc.connectionString ());
if (bfs::is_regular_file (dbPath))
bfs::remove (dbPath);
}
void testSQLite ()
{
testSQLiteFileNames ();
testSQLiteSession ();
testSQLiteSelect ();
testSQLiteDeleteWithSubselect();
}
void run () override
{
testSQLite ();
}
};
BEAST_DEFINE_TESTSUITE(SociDB,core,ripple);
}
| [
"sgy-official@hotmail.com"
] | sgy-official@hotmail.com |
7c93ef9cff4488c47968de6164e5cb6ccdae05ae | d78b1c661234f45aa189f4f4f15169b76bd88926 | /Player.h | 332cfabef419790a46495127c1d8738f64ec8805 | [] | no_license | HGahir/TerminalFightGame | 932aadff9cf3e639660e296657c508a3220b58a3 | 4c488620d545fe703e6075ca16da5a4824fec45b | refs/heads/master | 2023-01-07T00:45:20.665598 | 2020-10-25T10:54:29 | 2020-10-25T10:54:29 | 291,480,451 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 320 | h | #include <iostream>
#include <string>
class Player
{
public:
int PlayerHealth;
int PlayerStrength;
int PlayerEnergy;
int PlayerStamina;
int PlayerSkill;
int PlayerRespect;
bool JailCellVisited;
bool GymVisited;
std::string PlayerName = "";
};
| [
"noreply@github.com"
] | noreply@github.com |
7f2902b8d454121a5a60322bec477578702b62d1 | 3b1473b9aac543acac453a7f17638b57f35eb891 | /countBitsFlip.cpp | 1a9ebb4677f02af8ed4e706949ec8e5effdab44c | [] | no_license | KasatNiraj/DSA-BIT-MAGIC | f811a1605d90237691ecc4ba1e74d63391f33486 | 38544fc3c80a76bbe1a237eb1de2ebb3e232b5d6 | refs/heads/master | 2022-11-06T16:31:23.503528 | 2020-06-24T14:19:49 | 2020-06-24T14:19:49 | 271,485,661 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 313 | cpp | // Function to find number of bits to be flip
// to convert A to B
int countBitsFlip(int a, int b){
int res=a^b; //doing xor will set bits that need to be flipped
int count=0;
while(res){ //counting no of bits to be flipped
res&=res-1;
count++;
}
return count;
}
| [
"noreply@github.com"
] | noreply@github.com |
e2d71e17ca342569cbd1582039b67b4601abd868 | 57936e7850599b5c28cdb4fa0ece8cea989032fe | /SDK/PUBG_Item_Mask_C_01_parameters.hpp | 4956251d303e74eb087e9a8cb92b0d6bd2011e5b | [] | no_license | shleeSS/PUBG-SDK-1 | 2176b5f6f57ba0eb2fb8a47d8564562579c328bd | 893b628e08f6536fc039313290f1a06210a74f7c | refs/heads/master | 2021-09-03T11:23:08.134510 | 2018-01-08T17:38:00 | 2018-01-08T17:38:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 389 | hpp | #pragma once
// PlayerUnknown's Battlegrounds (2.6.23) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "PUBG_Item_Mask_C_01_classes.hpp"
namespace Classes
{
//---------------------------------------------------------------------------
//Parameters
//---------------------------------------------------------------------------
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"collin.mcqueen@yahoo.com"
] | collin.mcqueen@yahoo.com |
f87c7a860b501f2128502c8ecf6f387511c1ae41 | 24bc4990e9d0bef6a42a6f86dc783785b10dbd42 | /chrome/browser/ui/global_media_controls/cast_device_list_host.h | 286c930f7f8ca7ea7512e47eac11cf97ef4ce28a | [
"BSD-3-Clause"
] | permissive | nwjs/chromium.src | 7736ce86a9a0b810449a3b80a4af15de9ef9115d | 454f26d09b2f6204c096b47f778705eab1e3ba46 | refs/heads/nw75 | 2023-08-31T08:01:39.796085 | 2023-04-19T17:25:53 | 2023-04-19T17:25:53 | 50,512,158 | 161 | 201 | BSD-3-Clause | 2023-05-08T03:19:09 | 2016-01-27T14:17:03 | null | UTF-8 | C++ | false | false | 2,109 | h | // Copyright 2023 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_UI_GLOBAL_MEDIA_CONTROLS_CAST_DEVICE_LIST_HOST_H_
#define CHROME_BROWSER_UI_GLOBAL_MEDIA_CONTROLS_CAST_DEVICE_LIST_HOST_H_
#include "chrome/browser/ui/media_router/cast_dialog_controller.h"
#include "chrome/browser/ui/media_router/ui_media_sink.h"
#include "components/global_media_controls/public/mojom/device_service.mojom.h"
#include "mojo/public/cpp/bindings/remote.h"
// Serves as an adapter between Media Router and Global Media Controls UI Mojo
// interfaces:
// - Receives Cast device updates via the CastDialogController::Observer
// interface and forwards them to mojom::DeviceListClient.
// - Receives device picker UI events via the mojom::DeviceListHost interface
// and forwards them to CastDialogController.
class CastDeviceListHost : public global_media_controls::mojom::DeviceListHost,
media_router::CastDialogController::Observer {
public:
using MediaRemotingCallback = base::RepeatingCallback<void()>;
CastDeviceListHost(
std::unique_ptr<media_router::CastDialogController> dialog_controller,
mojo::PendingRemote<global_media_controls::mojom::DeviceListClient>
observer,
MediaRemotingCallback media_remoting_callback);
~CastDeviceListHost() override;
// mojom::DeviceListHost:
void SelectDevice(const std::string& device_id) override;
// media_router::CastDialogController::Observer:
void OnModelUpdated(const media_router::CastDialogModel& model) override;
private:
void StartCasting(const media_router::UIMediaSink& sink);
void DestroyCastController();
std::unique_ptr<media_router::CastDialogController> cast_controller_;
mojo::Remote<global_media_controls::mojom::DeviceListClient> client_;
std::vector<media_router::UIMediaSink> sinks_;
// Called whenever a Media Remoting session is starting.
MediaRemotingCallback media_remoting_callback_;
};
#endif // CHROME_BROWSER_UI_GLOBAL_MEDIA_CONTROLS_CAST_DEVICE_LIST_HOST_H_
| [
"roger@nwjs.io"
] | roger@nwjs.io |
2e99f1d00657b3a2b58ece4315a765a2844be6ea | 64589428b06258be0b9b82a7e7c92c0b3f0778f1 | /Macacário/Paradigms/mergesort.cpp | 79044a68f307cd8e3dc9e379d07807fe6746188d | [] | no_license | splucs/Competitive-Programming | b6def1ec6be720c6fbf93f2618e926e1062fdc48 | 4f41a7fbc71aa6ab8cb943d80e82d9149de7c7d6 | refs/heads/master | 2023-08-31T05:10:09.573198 | 2023-08-31T00:40:32 | 2023-08-31T00:40:32 | 85,239,827 | 141 | 27 | null | 2023-01-08T20:31:49 | 2017-03-16T20:42:37 | C++ | UTF-8 | C++ | false | false | 765 | cpp | #include <cstdio>
#define MAXN 100009
/*
* Merge-sort with inversion count in O(nlogn)
*/
long long inv;
int aux[MAXN];
void mergesort(int arr[], int l, int r) {
if (l == r) return;
int m = (l + r) / 2;
mergesort(arr, l, m);
mergesort(arr, m+1, r);
int i = l, j = m + 1, k = l;
while(i <= m && j <= r) {
if (arr[i] > arr[j]) {
aux[k++] = arr[j++];
inv += j - k;
}
else aux[k++] = arr[i++];
}
while(i <= m) aux[k++] = arr[i++];
for(i = l; i < k; i++) arr[i] = aux[i];
}
/*
* TEST MATRIX
*/
int main() {
int N, vet[MAXN];
inv = 0;
scanf("%d", &N);
for(int i=0; i<N; i++) {
scanf("%d", vet+i);
}
mergesort(vet, 0, N-1);
printf("inv = %lld:", inv);
for(int i=0; i<N; i++) {
printf(" %d", vet[i]);
}
printf("\n");
return 0;
} | [
"lucas.fra.oli18@gmail.com"
] | lucas.fra.oli18@gmail.com |
0e61c53ea4428c63120fe685964984ba0022d802 | 0f08276e557de8437759659970efc829a9cbc669 | /tests/p1335.cpp | a50763e988c62f413f091db1a2624879021f4912 | [] | no_license | petru-d/leetcode-solutions-reboot | 4fb35a58435f18934b9fe7931e01dabcc9d05186 | 680dc63d24df4c0cc58fcad429135e90f7dfe8bd | refs/heads/master | 2023-06-14T21:58:53.553870 | 2021-07-11T20:41:57 | 2021-07-11T20:41:57 | 250,795,996 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 110 | cpp | #include "pch.h"
#include "../problems/p1335.h"
TEST(p1335, t0)
{
[[maybe_unused]] p1335::Solution s;
}
| [
"berserk.ro@gmail.com"
] | berserk.ro@gmail.com |
24f25314467d7c79cd8363fd896e7e5718349401 | 03c907730db96c31f9a82acf722a10315e1ebde1 | /src/plugins/sdl/src/sdl_rw_ops.cpp | 3e6de449f68c6eb0a9d63889e0c3889b5e6f9b78 | [
"Apache-2.0"
] | permissive | tcoxon/halley | 19a391e445ec78334398af30ece19fcd48ce5456 | 490d2699090bfd677c5a00f53f2f12c19c198f7c | refs/heads/master | 2020-03-26T00:17:43.727155 | 2018-08-10T16:59:28 | 2018-08-10T16:59:28 | 144,313,857 | 0 | 0 | Apache-2.0 | 2018-08-10T17:18:37 | 2018-08-10T17:18:36 | null | UTF-8 | C++ | false | false | 1,881 | cpp | #include "sdl_rw_ops.h"
#include "halley/text/string_converter.h"
using namespace Halley;
std::unique_ptr<ResourceDataReader> SDLRWOps::fromPath(const String& path, int64_t start, int64_t end)
{
auto fp = SDL_RWFromFile(path.c_str(), "rb");
if (!fp) {
return std::unique_ptr<ResourceDataReader>();
}
return std::make_unique<SDLRWOps>(fp, start, end, true);
}
std::unique_ptr<ResourceDataReader> SDLRWOps::fromMemory(gsl::span<const gsl::byte> span)
{
auto fp = SDL_RWFromConstMem(span.data(), int(span.size()));
if (!fp) {
return std::unique_ptr<ResourceDataReader>();
}
return std::make_unique<SDLRWOps>(fp, 0, 0, true);
}
SDLRWOps::SDLRWOps(SDL_RWops* _fp, int64_t _start, int64_t _end, bool _closeOnFinish)
: fp(_fp)
, pos(_start)
, start(_start)
, end(_end)
, closeOnFinish(_closeOnFinish)
{
Expects(fp);
if (end == -1) {
SDL_RWseek(fp, 0, SEEK_END);
end = SDL_RWtell(fp);
SDL_RWseek(fp, 0, SEEK_SET);
}
int64_t size = end - start;
if (size < 0) {
throw Exception("Invalid file size for resource: " + toString(size) + " bytes.");
}
}
SDLRWOps::~SDLRWOps()
{
SDLRWOps::close();
}
size_t SDLRWOps::size() const
{
return end - start;
}
int SDLRWOps::read(gsl::span<gsl::byte> dst)
{
if (!fp) return -1;
size_t toRead = std::min(size_t(dst.size()), size_t(end - pos));
SDL_RWseek(fp, pos, SEEK_SET);
int n = static_cast<int>(SDL_RWread(fp, dst.data(), 1, static_cast<int>(toRead)));
if (n > 0) pos += n;
return n;
}
void SDLRWOps::close()
{
if (fp) {
if (closeOnFinish) {
SDL_RWclose(fp);
}
fp = nullptr;
pos = end;
}
}
void SDLRWOps::seek(int64_t offset, int whence)
{
if (whence == SEEK_SET) pos = int(offset + start);
else if (whence == SEEK_CUR) pos += int(offset);
else if (whence == SEEK_END) pos = int(end + offset);
SDL_RWseek(fp, pos, SEEK_SET);
}
size_t SDLRWOps::tell() const
{
return pos - start;
}
| [
"archmagezeratul@gmail.com"
] | archmagezeratul@gmail.com |
77f16ab5d298c658fea37dcec48823a2df3dd085 | 3a2ac36d1c0f7ddeeef562fa1d48c2ca0a62d023 | /Module_06/ex02/Base.cpp | eba5280df01472a6c3b5319cc07af958e193ae28 | [] | no_license | qmarow/Modules | 9db05dd456e0aa92286c5943eeb4de416a21711b | 97968808020b3f5afdd95f2412ebd3879b619baa | refs/heads/main | 2023-03-05T10:09:45.684308 | 2021-02-06T08:58:41 | 2021-02-06T08:58:41 | 326,410,910 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 805 | cpp | #include "Base.hpp"
Base *generate(void)
{
srand(time(NULL));
int r = rand() % 3;
Base *a;
if (!r)
a = new A;
else if (r == 1)
a = new B;
else
a = new C;
return (a);
}
void identify_from_pointer(Base * p)
{
A *a = dynamic_cast<A*>(p);
if (a)
{
std::cout << "A" << std::endl;
return ;
}
B *b = dynamic_cast<B*>(p);
if (b)
{
std::cout << "B" << std::endl;
return ;
}
C *c = dynamic_cast<C*>(p);
if (c)
std::cout << "C" << std::endl;
}
void identify_from_reference(Base & p)
{
A *a = dynamic_cast<A*>(&p);
if (a)
{
std::cout << "A" << std::endl;
return ;
}
B *b = dynamic_cast<B*>(&p);
if (b)
{
std::cout << "B" << std::endl;
return ;
}
C *c = dynamic_cast<C*>(&p);
if (c)
std::cout << "C" << std::endl;
}
| [
"noreply@github.com"
] | noreply@github.com |
eb62279376dec835ce19c0cb1e7e4e2e26a6683c | ad273708d98b1f73b3855cc4317bca2e56456d15 | /aws-cpp-sdk-macie2/include/aws/macie2/model/DefaultDetection.h | 22c7716e40fa40c48c778529d9b8a2cc261179ba | [
"MIT",
"Apache-2.0",
"JSON"
] | permissive | novaquark/aws-sdk-cpp | b390f2e29f86f629f9efcf41c4990169b91f4f47 | a0969508545bec9ae2864c9e1e2bb9aff109f90c | refs/heads/master | 2022-08-28T18:28:12.742810 | 2020-05-27T15:46:18 | 2020-05-27T15:46:18 | 267,351,721 | 1 | 0 | Apache-2.0 | 2020-05-27T15:08:16 | 2020-05-27T15:08:15 | null | UTF-8 | C++ | false | false | 4,058 | h | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#pragma once
#include <aws/macie2/Macie2_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 Macie2
{
namespace Model
{
/**
* <p>Provides information about sensitive data that was detected by managed data
* identifiers and produced a finding.</p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/macie2-2020-01-01/DefaultDetection">AWS
* API Reference</a></p>
*/
class AWS_MACIE2_API DefaultDetection
{
public:
DefaultDetection();
DefaultDetection(Aws::Utils::Json::JsonView jsonValue);
DefaultDetection& operator=(Aws::Utils::Json::JsonView jsonValue);
Aws::Utils::Json::JsonValue Jsonize() const;
/**
* <p>The total number of occurrences of the type of data that was detected.</p>
*/
inline long long GetCount() const{ return m_count; }
/**
* <p>The total number of occurrences of the type of data that was detected.</p>
*/
inline bool CountHasBeenSet() const { return m_countHasBeenSet; }
/**
* <p>The total number of occurrences of the type of data that was detected.</p>
*/
inline void SetCount(long long value) { m_countHasBeenSet = true; m_count = value; }
/**
* <p>The total number of occurrences of the type of data that was detected.</p>
*/
inline DefaultDetection& WithCount(long long value) { SetCount(value); return *this;}
/**
* <p>The type of data that was detected. For example, AWS_CREDENTIALS,
* PHONE_NUMBER, or ADDRESS.</p>
*/
inline const Aws::String& GetType() const{ return m_type; }
/**
* <p>The type of data that was detected. For example, AWS_CREDENTIALS,
* PHONE_NUMBER, or ADDRESS.</p>
*/
inline bool TypeHasBeenSet() const { return m_typeHasBeenSet; }
/**
* <p>The type of data that was detected. For example, AWS_CREDENTIALS,
* PHONE_NUMBER, or ADDRESS.</p>
*/
inline void SetType(const Aws::String& value) { m_typeHasBeenSet = true; m_type = value; }
/**
* <p>The type of data that was detected. For example, AWS_CREDENTIALS,
* PHONE_NUMBER, or ADDRESS.</p>
*/
inline void SetType(Aws::String&& value) { m_typeHasBeenSet = true; m_type = std::move(value); }
/**
* <p>The type of data that was detected. For example, AWS_CREDENTIALS,
* PHONE_NUMBER, or ADDRESS.</p>
*/
inline void SetType(const char* value) { m_typeHasBeenSet = true; m_type.assign(value); }
/**
* <p>The type of data that was detected. For example, AWS_CREDENTIALS,
* PHONE_NUMBER, or ADDRESS.</p>
*/
inline DefaultDetection& WithType(const Aws::String& value) { SetType(value); return *this;}
/**
* <p>The type of data that was detected. For example, AWS_CREDENTIALS,
* PHONE_NUMBER, or ADDRESS.</p>
*/
inline DefaultDetection& WithType(Aws::String&& value) { SetType(std::move(value)); return *this;}
/**
* <p>The type of data that was detected. For example, AWS_CREDENTIALS,
* PHONE_NUMBER, or ADDRESS.</p>
*/
inline DefaultDetection& WithType(const char* value) { SetType(value); return *this;}
private:
long long m_count;
bool m_countHasBeenSet;
Aws::String m_type;
bool m_typeHasBeenSet;
};
} // namespace Model
} // namespace Macie2
} // namespace Aws
| [
"aws-sdk-cpp-automation@github.com"
] | aws-sdk-cpp-automation@github.com |
f3e1858dcaeeeaccab28f493a726e86a07b1ddda | eb1517897d7e9e372538b0982223b7ecaaff46b0 | /chromeos/components/quick_answers/quick_answers_client.cc | 2d63ec68515c51a42ebd71c0d0ee85a3889678ad | [
"BSD-3-Clause"
] | permissive | jiachengii/chromium | c93e9cfa8fb79d6a0b5e66848dc204e87236252c | ead0d3601849269629ff31de4daed20fce453ba7 | refs/heads/master | 2022-11-16T02:35:53.671352 | 2020-06-13T06:43:44 | 2020-06-13T06:43:44 | 271,964,385 | 0 | 0 | BSD-3-Clause | 2020-06-13T07:47:21 | 2020-06-13T07:47:21 | null | UTF-8 | C++ | false | false | 8,014 | cc | // Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chromeos/components/quick_answers/quick_answers_client.h"
#include <utility>
#include "base/strings/stringprintf.h"
#include "chromeos/components/quick_answers/quick_answers_model.h"
#include "chromeos/components/quick_answers/utils/quick_answers_metrics.h"
#include "chromeos/constants/chromeos_features.h"
#include "third_party/icu/source/common/unicode/locid.h"
namespace chromeos {
namespace quick_answers {
namespace {
using network::mojom::URLLoaderFactory;
constexpr char kUnitConversionQueryRewriteTemplate[] = "Convert:%s";
constexpr char kDictionaryQueryRewriteTemplate[] = "Define:%s";
constexpr char kTranslationQueryRewriteTemplate[] = "Translate:%s";
QuickAnswersClient::ResultLoaderFactoryCallback*
g_testing_result_factory_callback = nullptr;
QuickAnswersClient::IntentGeneratorFactoryCallback*
g_testing_intent_generator_factory_callback = nullptr;
const PreprocessedOutput PreprocessRequest(const QuickAnswersRequest& request,
const std::string& intent_text,
IntentType intent_type) {
PreprocessedOutput processed_output;
processed_output.intent_text = intent_text;
processed_output.query = intent_text;
processed_output.intent_type = intent_type;
switch (intent_type) {
case IntentType::kUnit:
processed_output.query = base::StringPrintf(
kUnitConversionQueryRewriteTemplate, intent_text.c_str());
break;
case IntentType::kDictionary:
processed_output.query = base::StringPrintf(
kDictionaryQueryRewriteTemplate, intent_text.c_str());
break;
case IntentType::kTranslation:
processed_output.query = base::StringPrintf(
kTranslationQueryRewriteTemplate, intent_text.c_str());
break;
case IntentType::kUnknown:
// TODO(llin): Update to NOTREACHED after integrating with TCLib.
break;
}
return processed_output;
}
} // namespace
// static
void QuickAnswersClient::SetResultLoaderFactoryForTesting(
ResultLoaderFactoryCallback* factory) {
g_testing_result_factory_callback = factory;
}
void QuickAnswersClient::SetIntentGeneratorFactoryForTesting(
IntentGeneratorFactoryCallback* factory) {
g_testing_intent_generator_factory_callback = factory;
}
QuickAnswersClient::QuickAnswersClient(URLLoaderFactory* url_loader_factory,
ash::AssistantState* assistant_state,
QuickAnswersDelegate* delegate)
: url_loader_factory_(url_loader_factory),
assistant_state_(assistant_state),
delegate_(delegate) {
if (assistant_state_) {
// We observe Assistant state to detect enabling/disabling of Assistant in
// settings as well as enabling/disabling of screen context.
assistant_state_->AddObserver(this);
}
}
QuickAnswersClient::~QuickAnswersClient() {
if (assistant_state_)
assistant_state_->RemoveObserver(this);
}
void QuickAnswersClient::OnAssistantFeatureAllowedChanged(
chromeos::assistant::AssistantAllowedState state) {
assistant_allowed_state_ = state;
NotifyEligibilityChanged();
}
void QuickAnswersClient::OnAssistantSettingsEnabled(bool enabled) {
assistant_enabled_ = enabled;
NotifyEligibilityChanged();
}
void QuickAnswersClient::OnAssistantContextEnabled(bool enabled) {
assistant_context_enabled_ = enabled;
NotifyEligibilityChanged();
}
void QuickAnswersClient::OnAssistantQuickAnswersEnabled(bool enabled) {
quick_answers_settings_enabled_ = enabled;
NotifyEligibilityChanged();
}
void QuickAnswersClient::OnLocaleChanged(const std::string& locale) {
// String literals used in some cases in the array because their
// constant equivalents don't exist in:
// third_party/icu/source/common/unicode/uloc.h
const std::string kAllowedLocales[] = {ULOC_CANADA, ULOC_UK, ULOC_US,
"en_AU", "en_IN", "en_NZ"};
const std::string kRuntimeLocale = icu::Locale::getDefault().getName();
locale_supported_ = (base::Contains(kAllowedLocales, locale) ||
base::Contains(kAllowedLocales, kRuntimeLocale));
NotifyEligibilityChanged();
}
void QuickAnswersClient::OnAssistantStateDestroyed() {
assistant_state_ = nullptr;
}
void QuickAnswersClient::SendRequest(
const QuickAnswersRequest& quick_answers_request) {
RecordSelectedTextLength(quick_answers_request.selected_text.length());
// Generate intent from |quick_answers_request|.
intent_generator_ = CreateIntentGenerator(quick_answers_request);
intent_generator_->GenerateIntent(quick_answers_request);
}
void QuickAnswersClient::OnQuickAnswerClick(ResultType result_type) {
RecordClick(result_type, GetImpressionDuration());
}
void QuickAnswersClient::OnQuickAnswersDismissed(ResultType result_type,
bool is_active) {
if (is_active)
RecordActiveImpression(result_type, GetImpressionDuration());
}
void QuickAnswersClient::NotifyEligibilityChanged() {
DCHECK(delegate_);
bool is_eligible =
(chromeos::features::IsQuickAnswersEnabled() && assistant_state_ &&
assistant_enabled_ && locale_supported_ && assistant_context_enabled_ &&
quick_answers_settings_enabled_ &&
assistant_allowed_state_ ==
chromeos::assistant::AssistantAllowedState::ALLOWED);
if (is_eligible_ != is_eligible) {
is_eligible_ = is_eligible;
delegate_->OnEligibilityChanged(is_eligible);
}
}
std::unique_ptr<ResultLoader> QuickAnswersClient::CreateResultLoader(
IntentType intent_type) {
if (g_testing_result_factory_callback)
return g_testing_result_factory_callback->Run();
return ResultLoader::Create(intent_type, url_loader_factory_, this);
}
std::unique_ptr<IntentGenerator> QuickAnswersClient::CreateIntentGenerator(
const QuickAnswersRequest& request) {
if (g_testing_intent_generator_factory_callback)
return g_testing_intent_generator_factory_callback->Run();
return std::make_unique<IntentGenerator>(
base::BindOnce(&QuickAnswersClient::IntentGeneratorCallback,
weak_factory_.GetWeakPtr(), request));
}
void QuickAnswersClient::OnNetworkError() {
DCHECK(delegate_);
delegate_->OnNetworkError();
}
void QuickAnswersClient::OnQuickAnswerReceived(
std::unique_ptr<QuickAnswer> quick_answer) {
DCHECK(delegate_);
quick_answer_received_time_ = base::TimeTicks::Now();
delegate_->OnQuickAnswerReceived(std::move(quick_answer));
}
void QuickAnswersClient::IntentGeneratorCallback(
const QuickAnswersRequest& quick_answers_request,
const std::string& intent_text,
IntentType intent_type) {
DCHECK(delegate_);
// Preprocess the request.
QuickAnswersRequest processed_request = quick_answers_request;
processed_request.preprocessed_output =
PreprocessRequest(quick_answers_request, intent_text, intent_type);
delegate_->OnRequestPreprocessFinished(processed_request);
if (features::IsQuickAnswersTextAnnotatorEnabled()) {
RecordIntentType(processed_request.preprocessed_output.intent_type);
if (processed_request.preprocessed_output.intent_type ==
IntentType::kUnknown) {
// Don't fetch answer if no intent is generated.
return;
}
}
result_loader_ = CreateResultLoader(intent_type);
// Load and parse search result.
result_loader_->Fetch(processed_request.preprocessed_output.query);
}
base::TimeDelta QuickAnswersClient::GetImpressionDuration() const {
// Use default 0 duration.
base::TimeDelta duration;
if (!quick_answer_received_time_.is_null()) {
// Fetch finish, set the duration to be between fetch finish and now.
duration = base::TimeTicks::Now() - quick_answer_received_time_;
}
return duration;
}
} // namespace quick_answers
} // namespace chromeos
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
decff9ad7e2b03c595bc5582d754b6a67a31c3c4 | c5b7538e5a0baff453fe1a6b261d6a153ed31915 | /hdata.cpp | 079f03ce5b2f960b2a9b51c68c16ed2101da5a71 | [] | no_license | Ronaldotriandes/HotelReservation | 6535bf47e514a70d188965807e4a9004bfbc5bb0 | 1ac4e783bb09287cb71993711b9deef8bb18abb0 | refs/heads/master | 2022-11-16T10:46:00.048948 | 2020-07-15T16:04:41 | 2020-07-15T16:04:41 | 184,260,641 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,256 | cpp | #include "header.h"
addresskota alokasik(infotypeK x)
{
addresskota p=(addresskota)malloc(sizeof(elementkota));
infok(p)=x;
nextk(p)=nil;
nexth(p)=nil;
prevk(p)=nil;
return p;
}
void dealokasik(addresskota &p)
{
delete p;
}
addresshotel alokasih(infotypeH x)
{
addresshotel p=(addresshotel)malloc(sizeof(elementhotel));
infoh(p)=x;
nexth(p)=nil;
nexts(p)=nil;
return p;
}
void dealokasih(addresshotel &p)
{
delete p;
}
addresssuite alokasis(infotypeS x)
{
addresssuite p=(addresssuite)malloc(sizeof(elementsuite));
infos(p)=x;
nexts(p)=nil;
nextr(p)=nil;
return p;
}
addressroomoom alokasir(infotypeR x)
{
addressroomoom p=(addressroomoom)malloc(sizeof(elementroom));
infor(p)=x;
nextr(p)=nil;
return p;
}
addresskota cariK(multilist l,infotypeK a)
{
addresskota k=first(l);
while(k!=nil)
{
if (strcmp(infok(k).kota,a.kota)==0)
return k;
k=nextk(k);
}
return nil;
}
addresshotel cariH(multilist l,addresskota k,infotypeH b)
{
addresshotel h=nexth(k);
while(h!=nil)
{
if (strcmp(infoh(h).hotel,b.hotel)==0)
return h;
h=nexth(h);
}
return nil;
}
addresssuite cariS(multilist l,addresshotel h,infotypeS c)
{
addresssuite s=nexts(h);
while(s!=nil)
{
if (strcmp(infos(s).suite,c.suite)==0)
return s;
s=nexts(s);
}
return nil;
}
addressroomoom cariR(multilist l,addresssuite s,infotypeR d)
{
addressroomoom r=nextr(s);
while(r!=nil)
{
if (strcmp(infor(r).room,d.room)==0)
return r;
r=nextr(r);
}
return nil;
}
/*void cariH(multilist &l)
{
infotypeR r;
addressroomoom rom;
infotypeK k;
addresskota kot;
infotypeH h;
addresshotel hot;
system("cls");
cout<<endl;
cout<<"masukan room berapa : ";
cin>>r.room;
rom=cariR(l,r);
if (rom==NULL)
{
cout<<endl;
cout<<"data tidak ditemukan "<<endl;
}
else
{
system("cls");
cout<<endl;
cout<<infoh()
}
}*/
void InsertKota(multilist &l)
{
infotypeK k;
addresskota kot;
system("cls");
cout<<endl;
cout<<"Masukan nama kota : ";
cin>>k.kota;
kot=cariK(l,k);
if (kot ==NULL)
{
kot=alokasik(k);
if (first(l)== NULL)
{
first(l)=kot;
last(l)=kot;
cout<<endl;
cout<<"kota "<<infok(kot).kota<<" ditambahkan !"<<endl;
getch();
}
else
{
nextk(last(l))=kot;
prevk(kot)=last(l);
last(l)=kot;
cout<<endl;
cout<<"kota "<<infok(kot).kota<<"ditambahkan ! "<<endl;
getch();
}
}
else
{
cout<<endl;
cout<<"Kota sudah ada"<<endl;
getch();
}
}
void InsertHotel(multilist &l)
{
infotypeH b;
infotypeK a;
addresskota k;
addresshotel h;
ShowKota(l);
cout<<endl;
cout<<"Masukkan Nama Kota : ";
cin>>a.kota;
k=cariK(l,a);
if(k==nil)
{
cout<<endl;
cout<<"Kota Tidak Ditemukan";
getch();
}
else
{
system("cls");
ShowHotel(l,k);
cout<<endl;
cout<<"Masukkan Nama Hotel : ";
cin>>b.hotel;
h=cariH(l,k,b);
if(h==nil)
{
b.suites=0;
h=alokasih(b);
if(infok(k).hotels==0)
{
nexth(k)=h;
//prevh(h)= NULL;
nexth(h)=NULL;
infok(k).hotels=1;
cout<<endl;
cout<<"Hotel "<<infoh(h).hotel<<" Pada Kota "<<infok(k).kota<<" Ditambahkan !";
getch();
}
else
{
addresshotel h1=nexth(k);
while(nexth(h1)!=nil)
h1=nexth(h1);
nexth(h1)=h;
nexth(h)=NULL;
infok(k).hotels++;
cout<<endl;
cout<<"Hotel "<<infoh(nexth(h1)).hotel<<" Pada Kota "<<infok(k).kota<<" Ditambahkan !";
getch();
}
}
else
{
cout<<endl;
cout<<"Hotel ada di List"<<endl;
getch();
}
}
}
void InsertSuite(multilist&l)
{
infotypeS c;
infotypeH b;
infotypeK a;
addresskota k;
addresshotel h;
addresssuite s;
ShowKota(l);
cout<<endl;
cout<<"Masukkan Nama Kota : ";
cin>>a.kota;
k=cariK(l,a);
if(k==nil)
{
cout<<endl;
cout<<"Kota Tidak Ditemukan";
getch();
}
else
{
system("cls");
ShowHotel(l,k);
cout<<endl;
cout<<"Masukkan Nama Hotel : ";
cin>>b.hotel;
h=cariH(l,k,b);
if(h==nil)
{
cout<<endl;
cout<<"Hotel Tidak Ditemukan";
getch();
}
else
{
system("cls");
ShowSuite(l,h);
cout<<endl;
cout<<"Masukkan Nama Suite : ";
cin>>c.suite;
s=cariS(l,h,c);
if(s==nil)
{
c.rooms=0;
s=alokasis(c);
if(infoh(h).suites==0)
{
nexts(h)=s;
infoh(h).suites=1;
cout<<endl;
cout<<"Suite "<<infos(s).suite<<" Pada Hotel "<<infoh(h).hotel<<" Ditambahkan !";
getch();
}
else
{
addresssuite s1=nexts(h);
while(nexts(s1)!=nil)
s1=nexts(s1);
nexts(s1)=s;
infoh(h).suites++;
cout<<endl;
cout<<"Suite "<<infos(nexts(s1)).suite<<" Pada Hotel "<<infoh(h).hotel<<" Ditambahkan !";
getch();
}
}
else
{
cout<<endl;
cout<<"Suite ada di List"<<endl;
getch();
}
}
}
}
void InsertRoom(multilist&l)
{
infotypeR d;
infotypeS c;
infotypeH b;
infotypeK a;
addresskota k;
addresshotel h;
addresssuite s;
addressroomoom r;
system("cls");
ShowKota(l);
cout<<endl;
cout<<"Masukkan Nama Kota : ";
cin>>a.kota;
k=cariK(l,a);
if(k==nil)
{
cout<<endl;
cout<<"Kota Tidak Ditemukan";
getch();
}
else
{
system("cls");
ShowHotel(l,k);
cout<<endl;
cout<<"Masukkan Nama Hotel : ";
cin>>b.hotel;
h=cariH(l,k,b);
if(h==nil)
{
cout<<endl;
cout<<"Hotel Tidak Ditemukan";
getch();
}
else
{
system("cls");
ShowSuite(l,h);
cout<<endl;
cout<<"Masukkan Nama Suite : ";
cin>>c.suite;
s=cariS(l,h,c);
if(s==nil)
{
cout<<endl;
cout<<"Suite Tidak Ditemukan";
getch();
}
else
{
system("cls");
ShowRoom(l,s);
cout<<endl;
cout<<"Masukkan Nomor Kamar : ";
cin>>d.room;
cout<<"Masukkan Rate Kamar : ";
cin>>d.rate;
r=cariR(l,s,d);
if(r==nil)
{
d.stats=false;
r=alokasir(d);
if(infos(s).rooms==0)
{
nextr(s)=r;
infos(s).rooms=1;
cout<<endl;
cout<<"Room "<<infor(r).room<<" Pada Suite "<<infos(s).suite<<" Ditambahkan !";
getch();
}
else
{
addressroomoom r1=nextr(s);
while(nextr(r1)!=nil)
r1=nextr(r1);
nextr(r1)=r;
infos(s).rooms++;
cout<<endl;
cout<<"Room "<<infor(nextr(r1)).room<<" Pada Suite "<<infos(s).suite<<" Ditambahkan !";
getch();
}
}
else
{
cout<<endl;
cout<<"Room ada di List"<<endl;
getch();
}
}
}
}
}
void DeleteKota(multilist &l)
{
infotypeK a;
addresskota k,x;
cout<<"Masukkan Nama Kota : ";
cin>>a.kota;
k=cariK(l,a);
if(k==nil)
{
a.hotels=0;
k=alokasik(a);
if(first(l)==nil)
{
cout<<"Tidak ada kota yang ada"<<endl;
}
cout<<endl;
cout<<"Tidak ada kota yang ada"<<endl;
getch();
}
else
{
cout<<endl;
if (first(l) == k && first(l) != last(l))
{
x= first(l);
first(l)= nextk(first(l));
prevk(first(l))=NULL;
nextk(x)=NULL;
prevk(x)=NULL;
//dealokasik(x);
}
else if (first(l) == k && first(l) == last(l))
{
x= first(l);
nextk(x)=NULL;
first(l)=NULL;
}
else if (last(l)== k)
{
x= last(l);
last(l)= prevk(last(l));
prevk(x)=NULL;
nextk(last(l))=NULL;
//dealokasik(x);
}
else
{
addresskota q,i,m;
q=k;
i= prevk(q);
m=nextk(q);
x= q;
nextk(i)= nextk(x);
prevk(m)= i;
nextk(x)= NULL;
prevk(x)=NULL;
//dealokasik(x);
}
cout<<endl;
cout<<"Kota "<<infok(x).kota<<" Dihapus"<<endl;
dealokasik(x);
getch();
}
}
| [
"ronaldotriandes@gmail.com"
] | ronaldotriandes@gmail.com |
e77ba6c568cc421606b91733927e902edc5a0945 | 272274a37c6f4ea031dea803cf8fc8ee689ac471 | /fuchsia/runners/cast/named_message_port_connector.cc | 5c1f7d05d87d74641e0d004d45830654133706bd | [
"BSD-3-Clause"
] | permissive | zjh19861014/chromium | 6db9890f3b2981df3e8a0a56883adc93f6761fd5 | 8d48b756239d336d8724f8f593a7b22959c506b4 | refs/heads/master | 2023-01-09T06:34:30.549622 | 2019-04-13T06:55:11 | 2019-04-13T06:55:11 | 181,134,794 | 1 | 0 | NOASSERTION | 2019-04-13T07:12:06 | 2019-04-13T07:12:06 | null | UTF-8 | C++ | false | false | 4,608 | cc | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "fuchsia/runners/cast/named_message_port_connector.h"
#include <memory>
#include <utility>
#include <vector>
#include "base/callback.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/macros.h"
#include "base/path_service.h"
#include "base/threading/thread_restrictions.h"
#include "fuchsia/base/mem_buffer_util.h"
#include "fuchsia/fidl/chromium/web/cpp/fidl.h"
#include "fuchsia/runners/cast/cast_platform_bindings_ids.h"
namespace {
const char kBindingsJsPath[] =
FILE_PATH_LITERAL("fuchsia/runners/cast/named_message_port_connector.js");
const char kConnectedMessage[] = "connected";
} // namespace
NamedMessagePortConnector::NamedMessagePortConnector() {
base::FilePath assets_path;
CHECK(base::PathService::Get(base::DIR_ASSETS, &assets_path));
bindings_script_ = cr_fuchsia::MemBufferFromFile(
base::File(assets_path.AppendASCII(kBindingsJsPath),
base::File::FLAG_OPEN | base::File::FLAG_READ));
}
NamedMessagePortConnector::~NamedMessagePortConnector() = default;
void NamedMessagePortConnector::Register(const std::string& id,
PortConnectedCallback handler,
chromium::web::Frame* frame) {
DCHECK(handler);
DCHECK(!id.empty() && id.find(' ') == std::string::npos);
if (registrations_.find(frame) == registrations_.end())
InjectBindings(frame);
RegistrationEntry entry;
entry.id = id;
entry.handler = std::move(handler);
registrations_.insert(std::make_pair(std::move(frame), std::move(entry)));
}
void NamedMessagePortConnector::Unregister(chromium::web::Frame* frame,
const std::string& id) {
auto port_range = registrations_.equal_range(frame);
auto it = port_range.first;
while (it != port_range.second) {
if (it->second.id == id) {
it = registrations_.erase(it);
continue;
}
it++;
}
}
void NamedMessagePortConnector::NotifyPageLoad(chromium::web::Frame* frame) {
auto registration_range = registrations_.equal_range(frame);
// Push all bound MessagePorts to the page after every page load.
for (auto it = registration_range.first; it != registration_range.second;
++it) {
const RegistrationEntry& registration = it->second;
chromium::web::WebMessage message;
message.data =
cr_fuchsia::MemBufferFromString("connect " + registration.id);
// Call the handler callback, with the MessagePort client object.
message.outgoing_transfer =
std::make_unique<chromium::web::OutgoingTransferable>();
chromium::web::MessagePortPtr message_port;
message.outgoing_transfer->set_message_port(message_port.NewRequest());
// Send the port to the handler once a "connected" message is received from
// the peer, so that the caller has a stronger guarantee that the content is
// healthy and capable of processing messages.
message_port->ReceiveMessage(
[message_port = std::move(message_port),
handler =
registration.handler](chromium::web::WebMessage message) mutable {
std::string message_str;
if (!cr_fuchsia::StringFromMemBuffer(message.data, &message_str)) {
LOG(ERROR) << "Couldn't read from message VMO.";
return;
}
if (message_str != kConnectedMessage) {
LOG(ERROR) << "Unexpected message from port: " << message_str;
return;
}
handler.Run(std::move(message_port));
});
// Pass the other half of the MessagePort connection to the document.
it->first->PostMessage(std::move(message), "*",
[](bool result) { CHECK(result); });
}
}
void NamedMessagePortConnector::InjectBindings(chromium::web::Frame* frame) {
DCHECK(frame);
std::vector<std::string> origins = {"*"};
frame->AddJavaScriptBindings(
static_cast<uint64_t>(
CastPlatformBindingsId::NAMED_MESSAGE_PORT_CONNECTOR),
std::move(origins), cr_fuchsia::CloneBuffer(bindings_script_),
[](bool success) { CHECK(success) << "Couldn't inject bindings."; });
}
NamedMessagePortConnector::RegistrationEntry::RegistrationEntry() = default;
NamedMessagePortConnector::RegistrationEntry::~RegistrationEntry() = default;
NamedMessagePortConnector::RegistrationEntry::RegistrationEntry(
const RegistrationEntry& other) = default;
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
7538d8171fa50a29944b2613f4ce928fbe9c7c70 | f2a4291d62cc6d61522020dad521775c4f3a218a | /src/lemon/elevator.h | b0e666a57617f9130f6033640925ca7d4649516d | [
"BSL-1.0"
] | permissive | wangfeng012316/networkx-lemon | 262b813ba61055314d3937391f7506369e62d848 | d27f200bed4d23ff19f3b37002269998ead22665 | refs/heads/master | 2021-05-29T12:59:47.745382 | 2015-07-27T04:30:46 | 2015-07-27T04:30:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 27,039 | h | /* -*- mode: C++; indent-tabs-mode: nil; -*-
*
* This file is a part of LEMON, a generic C++ optimization library.
*
* Copyright (C) 2003-2009
* Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
* (Egervary Research Group on Combinatorial Optimization, EGRES).
*
* Permission to use, modify and distribute this software is granted
* provided that this copyright notice appears in all copies. For
* precise terms see the accompanying LICENSE file.
*
* This software is provided "AS IS" with no warranty of any kind,
* express or implied, and with no claim as to its suitability for any
* purpose.
*
*/
#ifndef LEMON_ELEVATOR_H
#define LEMON_ELEVATOR_H
///\ingroup auxdat
///\file
///\brief Elevator class
///
///Elevator class implements an efficient data structure
///for labeling items in push-relabel type algorithms.
///
#include "lemon/core.h"
#include "lemon/bits/traits.h"
namespace lemon {
///Class for handling "labels" in push-relabel type algorithms.
///A class for handling "labels" in push-relabel type algorithms.
///
///\ingroup auxdat
///Using this class you can assign "labels" (nonnegative integer numbers)
///to the edges or nodes of a graph, manipulate and query them through
///operations typically arising in "push-relabel" type algorithms.
///
///Each item is either \em active or not, and you can also choose a
///highest level active item.
///
///\sa LinkedElevator
///
///\param GR Type of the underlying graph.
///\param Item Type of the items the data is assigned to (\c GR::Node,
///\c GR::Arc or \c GR::Edge).
template<class GR, class Item>
class Elevator
{
public:
typedef Item Key;
typedef int Value;
private:
typedef Item *Vit;
typedef typename ItemSetTraits<GR,Item>::template Map<Vit>::Type VitMap;
typedef typename ItemSetTraits<GR,Item>::template Map<int>::Type IntMap;
const GR &_g;
int _max_level;
int _item_num;
VitMap _where;
IntMap _level;
std::vector<Item> _items;
std::vector<Vit> _first;
std::vector<Vit> _last_active;
int _highest_active;
void copy(Item i, Vit p)
{
_where[*p=i] = p;
}
void copy(Vit s, Vit p)
{
if(s!=p)
{
Item i=*s;
*p=i;
_where[i] = p;
}
}
void swap(Vit i, Vit j)
{
Item ti=*i;
Vit ct = _where[ti];
_where[ti] = _where[*i=*j];
_where[*j] = ct;
*j=ti;
}
public:
///Constructor with given maximum level.
///Constructor with given maximum level.
///
///\param graph The underlying graph.
///\param max_level The maximum allowed level.
///Set the range of the possible labels to <tt>[0..max_level]</tt>.
Elevator(const GR &graph,int max_level) :
_g(graph),
_max_level(max_level),
_item_num(_max_level),
_where(graph),
_level(graph,0),
_items(_max_level),
_first(_max_level+2),
_last_active(_max_level+2),
_highest_active(-1) {}
///Constructor.
///Constructor.
///
///\param graph The underlying graph.
///Set the range of the possible labels to <tt>[0..max_level]</tt>,
///where \c max_level is equal to the number of labeled items in the graph.
Elevator(const GR &graph) :
_g(graph),
_max_level(countItems<GR, Item>(graph)),
_item_num(_max_level),
_where(graph),
_level(graph,0),
_items(_max_level),
_first(_max_level+2),
_last_active(_max_level+2),
_highest_active(-1)
{
}
///Activate item \c i.
///Activate item \c i.
///\pre Item \c i shouldn't be active before.
void activate(Item i)
{
const int l=_level[i];
swap(_where[i],++_last_active[l]);
if(l>_highest_active) _highest_active=l;
}
///Deactivate item \c i.
///Deactivate item \c i.
///\pre Item \c i must be active before.
void deactivate(Item i)
{
swap(_where[i],_last_active[_level[i]]--);
while(_highest_active>=0 &&
_last_active[_highest_active]<_first[_highest_active])
_highest_active--;
}
///Query whether item \c i is active
bool active(Item i) const { return _where[i]<=_last_active[_level[i]]; }
///Return the level of item \c i.
int operator[](Item i) const { return _level[i]; }
///Return the number of items on level \c l.
int onLevel(int l) const
{
return _first[l+1]-_first[l];
}
///Return true if level \c l is empty.
bool emptyLevel(int l) const
{
return _first[l+1]-_first[l]==0;
}
///Return the number of items above level \c l.
int aboveLevel(int l) const
{
return _first[_max_level+1]-_first[l+1];
}
///Return the number of active items on level \c l.
int activesOnLevel(int l) const
{
return _last_active[l]-_first[l]+1;
}
///Return true if there is no active item on level \c l.
bool activeFree(int l) const
{
return _last_active[l]<_first[l];
}
///Return the maximum allowed level.
int maxLevel() const
{
return _max_level;
}
///\name Highest Active Item
///Functions for working with the highest level
///active item.
///@{
///Return a highest level active item.
///Return a highest level active item or INVALID if there is no active
///item.
Item highestActive() const
{
return _highest_active>=0?*_last_active[_highest_active]:INVALID;
}
///Return the highest active level.
///Return the level of the highest active item or -1 if there is no active
///item.
int highestActiveLevel() const
{
return _highest_active;
}
///Lift the highest active item by one.
///Lift the item returned by highestActive() by one.
///
void liftHighestActive()
{
Item it = *_last_active[_highest_active];
++_level[it];
swap(_last_active[_highest_active]--,_last_active[_highest_active+1]);
--_first[++_highest_active];
}
///Lift the highest active item to the given level.
///Lift the item returned by highestActive() to level \c new_level.
///
///\warning \c new_level must be strictly higher
///than the current level.
///
void liftHighestActive(int new_level)
{
const Item li = *_last_active[_highest_active];
copy(--_first[_highest_active+1],_last_active[_highest_active]--);
for(int l=_highest_active+1;l<new_level;l++)
{
copy(--_first[l+1],_first[l]);
--_last_active[l];
}
copy(li,_first[new_level]);
_level[li] = new_level;
_highest_active=new_level;
}
///Lift the highest active item to the top level.
///Lift the item returned by highestActive() to the top level and
///deactivate it.
void liftHighestActiveToTop()
{
const Item li = *_last_active[_highest_active];
copy(--_first[_highest_active+1],_last_active[_highest_active]--);
for(int l=_highest_active+1;l<_max_level;l++)
{
copy(--_first[l+1],_first[l]);
--_last_active[l];
}
copy(li,_first[_max_level]);
--_last_active[_max_level];
_level[li] = _max_level;
while(_highest_active>=0 &&
_last_active[_highest_active]<_first[_highest_active])
_highest_active--;
}
///@}
///\name Active Item on Certain Level
///Functions for working with the active items.
///@{
///Return an active item on level \c l.
///Return an active item on level \c l or \ref INVALID if there is no such
///an item. (\c l must be from the range [0...\c max_level].
Item activeOn(int l) const
{
return _last_active[l]>=_first[l]?*_last_active[l]:INVALID;
}
///Lift the active item returned by \c activeOn(level) by one.
///Lift the active item returned by \ref activeOn() "activeOn(level)"
///by one.
Item liftActiveOn(int level)
{
Item it =*_last_active[level];
++_level[it];
swap(_last_active[level]--, --_first[level+1]);
if (level+1>_highest_active) ++_highest_active;
}
///Lift the active item returned by \c activeOn(level) to the given level.
///Lift the active item returned by \ref activeOn() "activeOn(level)"
///to the given level.
void liftActiveOn(int level, int new_level)
{
const Item ai = *_last_active[level];
copy(--_first[level+1], _last_active[level]--);
for(int l=level+1;l<new_level;l++)
{
copy(_last_active[l],_first[l]);
copy(--_first[l+1], _last_active[l]--);
}
copy(ai,_first[new_level]);
_level[ai] = new_level;
if (new_level>_highest_active) _highest_active=new_level;
}
///Lift the active item returned by \c activeOn(level) to the top level.
///Lift the active item returned by \ref activeOn() "activeOn(level)"
///to the top level and deactivate it.
void liftActiveToTop(int level)
{
const Item ai = *_last_active[level];
copy(--_first[level+1],_last_active[level]--);
for(int l=level+1;l<_max_level;l++)
{
copy(_last_active[l],_first[l]);
copy(--_first[l+1], _last_active[l]--);
}
copy(ai,_first[_max_level]);
--_last_active[_max_level];
_level[ai] = _max_level;
if (_highest_active==level) {
while(_highest_active>=0 &&
_last_active[_highest_active]<_first[_highest_active])
_highest_active--;
}
}
///@}
///Lift an active item to a higher level.
///Lift an active item to a higher level.
///\param i The item to be lifted. It must be active.
///\param new_level The new level of \c i. It must be strictly higher
///than the current level.
///
void lift(Item i, int new_level)
{
const int lo = _level[i];
const Vit w = _where[i];
copy(_last_active[lo],w);
copy(--_first[lo+1],_last_active[lo]--);
for(int l=lo+1;l<new_level;l++)
{
copy(_last_active[l],_first[l]);
copy(--_first[l+1],_last_active[l]--);
}
copy(i,_first[new_level]);
_level[i] = new_level;
if(new_level>_highest_active) _highest_active=new_level;
}
///Move an inactive item to the top but one level (in a dirty way).
///This function moves an inactive item from the top level to the top
///but one level (in a dirty way).
///\warning It makes the underlying datastructure corrupt, so use it
///only if you really know what it is for.
///\pre The item is on the top level.
void dirtyTopButOne(Item i) {
_level[i] = _max_level - 1;
}
///Lift all items on and above the given level to the top level.
///This function lifts all items on and above level \c l to the top
///level and deactivates them.
void liftToTop(int l)
{
const Vit f=_first[l];
const Vit tl=_first[_max_level];
for(Vit i=f;i!=tl;++i)
_level[*i] = _max_level;
for(int i=l;i<=_max_level;i++)
{
_first[i]=f;
_last_active[i]=f-1;
}
for(_highest_active=l-1;
_highest_active>=0 &&
_last_active[_highest_active]<_first[_highest_active];
_highest_active--) ;
}
private:
int _init_lev;
Vit _init_num;
public:
///\name Initialization
///Using these functions you can initialize the levels of the items.
///\n
///The initialization must be started with calling \c initStart().
///Then the items should be listed level by level starting with the
///lowest one (level 0) using \c initAddItem() and \c initNewLevel().
///Finally \c initFinish() must be called.
///The items not listed are put on the highest level.
///@{
///Start the initialization process.
void initStart()
{
_init_lev=0;
_init_num=&_items[0];
_first[0]=&_items[0];
_last_active[0]=&_items[0]-1;
Vit n=&_items[0];
for(typename ItemSetTraits<GR,Item>::ItemIt i(_g);i!=INVALID;++i)
{
*n=i;
_where[i] = n;
_level[i] = _max_level;
++n;
}
}
///Add an item to the current level.
void initAddItem(Item i)
{
swap(_where[i],_init_num);
_level[i] = _init_lev;
++_init_num;
}
///Start a new level.
///Start a new level.
///It shouldn't be used before the items on level 0 are listed.
void initNewLevel()
{
_init_lev++;
_first[_init_lev]=_init_num;
_last_active[_init_lev]=_init_num-1;
}
///Finalize the initialization process.
void initFinish()
{
for(_init_lev++;_init_lev<=_max_level;_init_lev++)
{
_first[_init_lev]=_init_num;
_last_active[_init_lev]=_init_num-1;
}
_first[_max_level+1]=&_items[0]+_item_num;
_last_active[_max_level+1]=&_items[0]+_item_num-1;
_highest_active = -1;
}
///@}
};
///Class for handling "labels" in push-relabel type algorithms.
///A class for handling "labels" in push-relabel type algorithms.
///
///\ingroup auxdat
///Using this class you can assign "labels" (nonnegative integer numbers)
///to the edges or nodes of a graph, manipulate and query them through
///operations typically arising in "push-relabel" type algorithms.
///
///Each item is either \em active or not, and you can also choose a
///highest level active item.
///
///\sa Elevator
///
///\param GR Type of the underlying graph.
///\param Item Type of the items the data is assigned to (\c GR::Node,
///\c GR::Arc or \c GR::Edge).
template <class GR, class Item>
class LinkedElevator {
public:
typedef Item Key;
typedef int Value;
private:
typedef typename ItemSetTraits<GR,Item>::
template Map<Item>::Type ItemMap;
typedef typename ItemSetTraits<GR,Item>::
template Map<int>::Type IntMap;
typedef typename ItemSetTraits<GR,Item>::
template Map<bool>::Type BoolMap;
const GR &_graph;
int _max_level;
int _item_num;
std::vector<Item> _first, _last;
ItemMap _prev, _next;
int _highest_active;
IntMap _level;
BoolMap _active;
public:
///Constructor with given maximum level.
///Constructor with given maximum level.
///
///\param graph The underlying graph.
///\param max_level The maximum allowed level.
///Set the range of the possible labels to <tt>[0..max_level]</tt>.
LinkedElevator(const GR& graph, int max_level)
: _graph(graph), _max_level(max_level), _item_num(_max_level),
_first(_max_level + 1), _last(_max_level + 1),
_prev(graph), _next(graph),
_highest_active(-1), _level(graph), _active(graph) {}
///Constructor.
///Constructor.
///
///\param graph The underlying graph.
///Set the range of the possible labels to <tt>[0..max_level]</tt>,
///where \c max_level is equal to the number of labeled items in the graph.
LinkedElevator(const GR& graph)
: _graph(graph), _max_level(countItems<GR, Item>(graph)),
_item_num(_max_level),
_first(_max_level + 1), _last(_max_level + 1),
_prev(graph, INVALID), _next(graph, INVALID),
_highest_active(-1), _level(graph), _active(graph) {}
///Activate item \c i.
///Activate item \c i.
///\pre Item \c i shouldn't be active before.
void activate(Item i) {
_active[i] = true;
int level = _level[i];
if (level > _highest_active) {
_highest_active = level;
}
if (_prev[i] == INVALID || _active[_prev[i]]) return;
//unlace
_next[_prev[i]] = _next[i];
if (_next[i] != INVALID) {
_prev[_next[i]] = _prev[i];
} else {
_last[level] = _prev[i];
}
//lace
_next[i] = _first[level];
_prev[_first[level]] = i;
_prev[i] = INVALID;
_first[level] = i;
}
///Deactivate item \c i.
///Deactivate item \c i.
///\pre Item \c i must be active before.
void deactivate(Item i) {
_active[i] = false;
int level = _level[i];
if (_next[i] == INVALID || !_active[_next[i]])
goto find_highest_level;
//unlace
_prev[_next[i]] = _prev[i];
if (_prev[i] != INVALID) {
_next[_prev[i]] = _next[i];
} else {
_first[_level[i]] = _next[i];
}
//lace
_prev[i] = _last[level];
_next[_last[level]] = i;
_next[i] = INVALID;
_last[level] = i;
find_highest_level:
if (level == _highest_active) {
while (_highest_active >= 0 && activeFree(_highest_active))
--_highest_active;
}
}
///Query whether item \c i is active
bool active(Item i) const { return _active[i]; }
///Return the level of item \c i.
int operator[](Item i) const { return _level[i]; }
///Return the number of items on level \c l.
int onLevel(int l) const {
int num = 0;
Item n = _first[l];
while (n != INVALID) {
++num;
n = _next[n];
}
return num;
}
///Return true if the level is empty.
bool emptyLevel(int l) const {
return _first[l] == INVALID;
}
///Return the number of items above level \c l.
int aboveLevel(int l) const {
int num = 0;
for (int level = l + 1; level < _max_level; ++level)
num += onLevel(level);
return num;
}
///Return the number of active items on level \c l.
int activesOnLevel(int l) const {
int num = 0;
Item n = _first[l];
while (n != INVALID && _active[n]) {
++num;
n = _next[n];
}
return num;
}
///Return true if there is no active item on level \c l.
bool activeFree(int l) const {
return _first[l] == INVALID || !_active[_first[l]];
}
///Return the maximum allowed level.
int maxLevel() const {
return _max_level;
}
///\name Highest Active Item
///Functions for working with the highest level
///active item.
///@{
///Return a highest level active item.
///Return a highest level active item or INVALID if there is no active
///item.
Item highestActive() const {
return _highest_active >= 0 ? _first[_highest_active] : INVALID;
}
///Return the highest active level.
///Return the level of the highest active item or -1 if there is no active
///item.
int highestActiveLevel() const {
return _highest_active;
}
///Lift the highest active item by one.
///Lift the item returned by highestActive() by one.
///
void liftHighestActive() {
Item i = _first[_highest_active];
if (_next[i] != INVALID) {
_prev[_next[i]] = INVALID;
_first[_highest_active] = _next[i];
} else {
_first[_highest_active] = INVALID;
_last[_highest_active] = INVALID;
}
_level[i] = ++_highest_active;
if (_first[_highest_active] == INVALID) {
_first[_highest_active] = i;
_last[_highest_active] = i;
_prev[i] = INVALID;
_next[i] = INVALID;
} else {
_prev[_first[_highest_active]] = i;
_next[i] = _first[_highest_active];
_first[_highest_active] = i;
}
}
///Lift the highest active item to the given level.
///Lift the item returned by highestActive() to level \c new_level.
///
///\warning \c new_level must be strictly higher
///than the current level.
///
void liftHighestActive(int new_level) {
Item i = _first[_highest_active];
if (_next[i] != INVALID) {
_prev[_next[i]] = INVALID;
_first[_highest_active] = _next[i];
} else {
_first[_highest_active] = INVALID;
_last[_highest_active] = INVALID;
}
_level[i] = _highest_active = new_level;
if (_first[_highest_active] == INVALID) {
_first[_highest_active] = _last[_highest_active] = i;
_prev[i] = INVALID;
_next[i] = INVALID;
} else {
_prev[_first[_highest_active]] = i;
_next[i] = _first[_highest_active];
_first[_highest_active] = i;
}
}
///Lift the highest active item to the top level.
///Lift the item returned by highestActive() to the top level and
///deactivate it.
void liftHighestActiveToTop() {
Item i = _first[_highest_active];
_level[i] = _max_level;
if (_next[i] != INVALID) {
_prev[_next[i]] = INVALID;
_first[_highest_active] = _next[i];
} else {
_first[_highest_active] = INVALID;
_last[_highest_active] = INVALID;
}
while (_highest_active >= 0 && activeFree(_highest_active))
--_highest_active;
}
///@}
///\name Active Item on Certain Level
///Functions for working with the active items.
///@{
///Return an active item on level \c l.
///Return an active item on level \c l or \ref INVALID if there is no such
///an item. (\c l must be from the range [0...\c max_level].
Item activeOn(int l) const
{
return _active[_first[l]] ? _first[l] : INVALID;
}
///Lift the active item returned by \c activeOn(l) by one.
///Lift the active item returned by \ref activeOn() "activeOn(l)"
///by one.
Item liftActiveOn(int l)
{
Item i = _first[l];
if (_next[i] != INVALID) {
_prev[_next[i]] = INVALID;
_first[l] = _next[i];
} else {
_first[l] = INVALID;
_last[l] = INVALID;
}
_level[i] = ++l;
if (_first[l] == INVALID) {
_first[l] = _last[l] = i;
_prev[i] = INVALID;
_next[i] = INVALID;
} else {
_prev[_first[l]] = i;
_next[i] = _first[l];
_first[l] = i;
}
if (_highest_active < l) {
_highest_active = l;
}
}
///Lift the active item returned by \c activeOn(l) to the given level.
///Lift the active item returned by \ref activeOn() "activeOn(l)"
///to the given level.
void liftActiveOn(int l, int new_level)
{
Item i = _first[l];
if (_next[i] != INVALID) {
_prev[_next[i]] = INVALID;
_first[l] = _next[i];
} else {
_first[l] = INVALID;
_last[l] = INVALID;
}
_level[i] = l = new_level;
if (_first[l] == INVALID) {
_first[l] = _last[l] = i;
_prev[i] = INVALID;
_next[i] = INVALID;
} else {
_prev[_first[l]] = i;
_next[i] = _first[l];
_first[l] = i;
}
if (_highest_active < l) {
_highest_active = l;
}
}
///Lift the active item returned by \c activeOn(l) to the top level.
///Lift the active item returned by \ref activeOn() "activeOn(l)"
///to the top level and deactivate it.
void liftActiveToTop(int l)
{
Item i = _first[l];
if (_next[i] != INVALID) {
_prev[_next[i]] = INVALID;
_first[l] = _next[i];
} else {
_first[l] = INVALID;
_last[l] = INVALID;
}
_level[i] = _max_level;
if (l == _highest_active) {
while (_highest_active >= 0 && activeFree(_highest_active))
--_highest_active;
}
}
///@}
/// \brief Lift an active item to a higher level.
///
/// Lift an active item to a higher level.
/// \param i The item to be lifted. It must be active.
/// \param new_level The new level of \c i. It must be strictly higher
/// than the current level.
///
void lift(Item i, int new_level) {
if (_next[i] != INVALID) {
_prev[_next[i]] = _prev[i];
} else {
_last[new_level] = _prev[i];
}
if (_prev[i] != INVALID) {
_next[_prev[i]] = _next[i];
} else {
_first[new_level] = _next[i];
}
_level[i] = new_level;
if (_first[new_level] == INVALID) {
_first[new_level] = _last[new_level] = i;
_prev[i] = INVALID;
_next[i] = INVALID;
} else {
_prev[_first[new_level]] = i;
_next[i] = _first[new_level];
_first[new_level] = i;
}
if (_highest_active < new_level) {
_highest_active = new_level;
}
}
///Move an inactive item to the top but one level (in a dirty way).
///This function moves an inactive item from the top level to the top
///but one level (in a dirty way).
///\warning It makes the underlying datastructure corrupt, so use it
///only if you really know what it is for.
///\pre The item is on the top level.
void dirtyTopButOne(Item i) {
_level[i] = _max_level - 1;
}
///Lift all items on and above the given level to the top level.
///This function lifts all items on and above level \c l to the top
///level and deactivates them.
void liftToTop(int l) {
for (int i = l + 1; _first[i] != INVALID; ++i) {
Item n = _first[i];
while (n != INVALID) {
_level[n] = _max_level;
n = _next[n];
}
_first[i] = INVALID;
_last[i] = INVALID;
}
if (_highest_active > l - 1) {
_highest_active = l - 1;
while (_highest_active >= 0 && activeFree(_highest_active))
--_highest_active;
}
}
private:
int _init_level;
public:
///\name Initialization
///Using these functions you can initialize the levels of the items.
///\n
///The initialization must be started with calling \c initStart().
///Then the items should be listed level by level starting with the
///lowest one (level 0) using \c initAddItem() and \c initNewLevel().
///Finally \c initFinish() must be called.
///The items not listed are put on the highest level.
///@{
///Start the initialization process.
void initStart() {
for (int i = 0; i <= _max_level; ++i) {
_first[i] = _last[i] = INVALID;
}
_init_level = 0;
for(typename ItemSetTraits<GR,Item>::ItemIt i(_graph);
i != INVALID; ++i) {
_level[i] = _max_level;
_active[i] = false;
}
}
///Add an item to the current level.
void initAddItem(Item i) {
_level[i] = _init_level;
if (_last[_init_level] == INVALID) {
_first[_init_level] = i;
_last[_init_level] = i;
_prev[i] = INVALID;
_next[i] = INVALID;
} else {
_prev[i] = _last[_init_level];
_next[i] = INVALID;
_next[_last[_init_level]] = i;
_last[_init_level] = i;
}
}
///Start a new level.
///Start a new level.
///It shouldn't be used before the items on level 0 are listed.
void initNewLevel() {
++_init_level;
}
///Finalize the initialization process.
void initFinish() {
_highest_active = -1;
}
///@}
};
} //END OF NAMESPACE LEMON
#endif
| [
"himanshu2014iit@gmail.com"
] | himanshu2014iit@gmail.com |
82ebc6358b7aaef2daab9b27671460f70e3f6a79 | 8edbf488e95a2f7c2b5e1d679909d2f3967eb515 | /src/miner.cpp | 5a4538b6648500a46a8d77665b8a19532307c181 | [
"MIT"
] | permissive | danigarcia3k/Sikacoin | 34a30f977b629c318eca44b4c387612a4a7b1260 | 82ef600cfeed1d8f163df6071d8d080fb9dac6b0 | refs/heads/master | 2020-06-13T02:51:38.216755 | 2019-06-30T12:00:00 | 2019-06-30T12:00:00 | 194,507,821 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,414 | cpp | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2016 The Sikacoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "miner.h"
#include "amount.h"
#include "chain.h"
#include "chainparams.h"
#include "coins.h"
#include "consensus/consensus.h"
#include "consensus/tx_verify.h"
#include "consensus/merkle.h"
#include "consensus/validation.h"
#include "hash.h"
#include "validation.h"
#include "net.h"
#include "policy/feerate.h"
#include "policy/policy.h"
#include "pow.h"
#include "primitives/transaction.h"
#include "script/standard.h"
#include "timedata.h"
#include "txmempool.h"
#include "util.h"
#include "utilmoneystr.h"
#include "validationinterface.h"
#include <algorithm>
#include <queue>
#include <utility>
//////////////////////////////////////////////////////////////////////////////
//
// SikacoinMiner
//
//
// Unconfirmed transactions in the memory pool often depend on other
// transactions in the memory pool. When we select transactions from the
// pool, we select by highest fee rate of a transaction combined with all
// its ancestors.
uint64_t nLastBlockTx = 0;
uint64_t nLastBlockWeight = 0;
int64_t UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
{
int64_t nOldTime = pblock->nTime;
int64_t nNewTime = std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
if (nOldTime < nNewTime)
pblock->nTime = nNewTime;
// Updating time can change work required on testnet:
if (consensusParams.fPowAllowMinDifficultyBlocks)
pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, consensusParams);
return nNewTime - nOldTime;
}
BlockAssembler::Options::Options() {
blockMinFeeRate = CFeeRate(DEFAULT_BLOCK_MIN_TX_FEE);
nBlockMaxWeight = DEFAULT_BLOCK_MAX_WEIGHT;
}
BlockAssembler::BlockAssembler(const CChainParams& params, const Options& options) : chainparams(params)
{
blockMinFeeRate = options.blockMinFeeRate;
// Limit weight to between 4K and MAX_BLOCK_WEIGHT-4K for sanity:
nBlockMaxWeight = std::max<size_t>(4000, std::min<size_t>(MAX_BLOCK_WEIGHT - 4000, options.nBlockMaxWeight));
}
static BlockAssembler::Options DefaultOptions(const CChainParams& params)
{
// Block resource limits
// If neither -blockmaxsize or -blockmaxweight is given, limit to DEFAULT_BLOCK_MAX_*
// If only one is given, only restrict the specified resource.
// If both are given, restrict both.
BlockAssembler::Options options;
options.nBlockMaxWeight = gArgs.GetArg("-blockmaxweight", DEFAULT_BLOCK_MAX_WEIGHT);
if (gArgs.IsArgSet("-blockmintxfee")) {
CAmount n = 0;
ParseMoney(gArgs.GetArg("-blockmintxfee", ""), n);
options.blockMinFeeRate = CFeeRate(n);
} else {
options.blockMinFeeRate = CFeeRate(DEFAULT_BLOCK_MIN_TX_FEE);
}
return options;
}
BlockAssembler::BlockAssembler(const CChainParams& params) : BlockAssembler(params, DefaultOptions(params)) {}
void BlockAssembler::resetBlock()
{
inBlock.clear();
// Reserve space for coinbase tx
nBlockWeight = 4000;
nBlockSigOpsCost = 400;
fIncludeWitness = false;
// These counters do not include coinbase tx
nBlockTx = 0;
nFees = 0;
}
std::unique_ptr<CBlockTemplate> BlockAssembler::CreateNewBlock(const CScript& scriptPubKeyIn, bool fMineWitnessTx)
{
int64_t nTimeStart = GetTimeMicros();
resetBlock();
pblocktemplate.reset(new CBlockTemplate());
if(!pblocktemplate.get())
return nullptr;
pblock = &pblocktemplate->block; // pointer for convenience
// Add dummy coinbase tx as first transaction
pblock->vtx.emplace_back();
pblocktemplate->vTxFees.push_back(-1); // updated at end
pblocktemplate->vTxSigOpsCost.push_back(-1); // updated at end
LOCK2(cs_main, mempool.cs);
CBlockIndex* pindexPrev = chainActive.Tip();
nHeight = pindexPrev->nHeight + 1;
pblock->nVersion = ComputeBlockVersion(pindexPrev, chainparams.GetConsensus());
// -regtest only: allow overriding block.nVersion with
// -blockversion=N to test forking scenarios
if (chainparams.MineBlocksOnDemand())
pblock->nVersion = gArgs.GetArg("-blockversion", pblock->nVersion);
pblock->nTime = GetAdjustedTime();
const int64_t nMedianTimePast = pindexPrev->GetMedianTimePast();
nLockTimeCutoff = (STANDARD_LOCKTIME_VERIFY_FLAGS & LOCKTIME_MEDIAN_TIME_PAST)
? nMedianTimePast
: pblock->GetBlockTime();
// Decide whether to include witness transactions
// This is only needed in case the witness softfork activation is reverted
// (which would require a very deep reorganization) or when
// -promiscuousmempoolflags is used.
// TODO: replace this with a call to main to assess validity of a mempool
// transaction (which in most cases can be a no-op).
fIncludeWitness = IsWitnessEnabled(pindexPrev, chainparams.GetConsensus()) && fMineWitnessTx;
int nPackagesSelected = 0;
int nDescendantsUpdated = 0;
addPackageTxs(nPackagesSelected, nDescendantsUpdated);
int64_t nTime1 = GetTimeMicros();
nLastBlockTx = nBlockTx;
nLastBlockWeight = nBlockWeight;
// Create coinbase transaction.
CMutableTransaction coinbaseTx;
coinbaseTx.vin.resize(1);
coinbaseTx.vin[0].prevout.SetNull();
coinbaseTx.vout.resize(1);
coinbaseTx.vout[0].scriptPubKey = scriptPubKeyIn;
coinbaseTx.vout[0].nValue = nFees + GetBlockSubsidy(nHeight, chainparams.GetConsensus());
coinbaseTx.vin[0].scriptSig = CScript() << nHeight << OP_0;
pblock->vtx[0] = MakeTransactionRef(std::move(coinbaseTx));
pblocktemplate->vchCoinbaseCommitment = GenerateCoinbaseCommitment(*pblock, pindexPrev, chainparams.GetConsensus());
pblocktemplate->vTxFees[0] = -nFees;
LogPrintf("CreateNewBlock(): block weight: %u txs: %u fees: %ld sigops %d\n", GetBlockWeight(*pblock), nBlockTx, nFees, nBlockSigOpsCost);
// Fill in header
pblock->hashPrevBlock = pindexPrev->GetBlockHash();
UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev);
pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, chainparams.GetConsensus());
pblock->nNonce = 0;
pblocktemplate->vTxSigOpsCost[0] = WITNESS_SCALE_FACTOR * GetLegacySigOpCount(*pblock->vtx[0]);
CValidationState state;
if (!TestBlockValidity(state, chainparams, *pblock, pindexPrev, false, false)) {
throw std::runtime_error(strprintf("%s: TestBlockValidity failed: %s", __func__, FormatStateMessage(state)));
}
int64_t nTime2 = GetTimeMicros();
LogPrint(BCLog::BENCH, "CreateNewBlock() packages: %.2fms (%d packages, %d updated descendants), validity: %.2fms (total %.2fms)\n", 0.001 * (nTime1 - nTimeStart), nPackagesSelected, nDescendantsUpdated, 0.001 * (nTime2 - nTime1), 0.001 * (nTime2 - nTimeStart));
return std::move(pblocktemplate);
}
void BlockAssembler::onlyUnconfirmed(CTxMemPool::setEntries& testSet)
{
for (CTxMemPool::setEntries::iterator iit = testSet.begin(); iit != testSet.end(); ) {
// Only test txs not already in the block
if (inBlock.count(*iit)) {
testSet.erase(iit++);
}
else {
iit++;
}
}
}
bool BlockAssembler::TestPackage(uint64_t packageSize, int64_t packageSigOpsCost)
{
// TODO: switch to weight-based accounting for packages instead of vsize-based accounting.
if (nBlockWeight + WITNESS_SCALE_FACTOR * packageSize >= nBlockMaxWeight)
return false;
if (nBlockSigOpsCost + packageSigOpsCost >= MAX_BLOCK_SIGOPS_COST)
return false;
return true;
}
// Perform transaction-level checks before adding to block:
// - transaction finality (locktime)
// - premature witness (in case segwit transactions are added to mempool before
// segwit activation)
bool BlockAssembler::TestPackageTransactions(const CTxMemPool::setEntries& package)
{
for (const CTxMemPool::txiter it : package) {
if (!IsFinalTx(it->GetTx(), nHeight, nLockTimeCutoff))
return false;
if (!fIncludeWitness && it->GetTx().HasWitness())
return false;
}
return true;
}
void BlockAssembler::AddToBlock(CTxMemPool::txiter iter)
{
pblock->vtx.emplace_back(iter->GetSharedTx());
pblocktemplate->vTxFees.push_back(iter->GetFee());
pblocktemplate->vTxSigOpsCost.push_back(iter->GetSigOpCost());
nBlockWeight += iter->GetTxWeight();
++nBlockTx;
nBlockSigOpsCost += iter->GetSigOpCost();
nFees += iter->GetFee();
inBlock.insert(iter);
bool fPrintPriority = gArgs.GetBoolArg("-printpriority", DEFAULT_PRINTPRIORITY);
if (fPrintPriority) {
LogPrintf("fee %s txid %s\n",
CFeeRate(iter->GetModifiedFee(), iter->GetTxSize()).ToString(),
iter->GetTx().GetHash().ToString());
}
}
int BlockAssembler::UpdatePackagesForAdded(const CTxMemPool::setEntries& alreadyAdded,
indexed_modified_transaction_set &mapModifiedTx)
{
int nDescendantsUpdated = 0;
for (const CTxMemPool::txiter it : alreadyAdded) {
CTxMemPool::setEntries descendants;
mempool.CalculateDescendants(it, descendants);
// Insert all descendants (not yet in block) into the modified set
for (CTxMemPool::txiter desc : descendants) {
if (alreadyAdded.count(desc))
continue;
++nDescendantsUpdated;
modtxiter mit = mapModifiedTx.find(desc);
if (mit == mapModifiedTx.end()) {
CTxMemPoolModifiedEntry modEntry(desc);
modEntry.nSizeWithAncestors -= it->GetTxSize();
modEntry.nModFeesWithAncestors -= it->GetModifiedFee();
modEntry.nSigOpCostWithAncestors -= it->GetSigOpCost();
mapModifiedTx.insert(modEntry);
} else {
mapModifiedTx.modify(mit, update_for_parent_inclusion(it));
}
}
}
return nDescendantsUpdated;
}
// Skip entries in mapTx that are already in a block or are present
// in mapModifiedTx (which implies that the mapTx ancestor state is
// stale due to ancestor inclusion in the block)
// Also skip transactions that we've already failed to add. This can happen if
// we consider a transaction in mapModifiedTx and it fails: we can then
// potentially consider it again while walking mapTx. It's currently
// guaranteed to fail again, but as a belt-and-suspenders check we put it in
// failedTx and avoid re-evaluation, since the re-evaluation would be using
// cached size/sigops/fee values that are not actually correct.
bool BlockAssembler::SkipMapTxEntry(CTxMemPool::txiter it, indexed_modified_transaction_set &mapModifiedTx, CTxMemPool::setEntries &failedTx)
{
assert (it != mempool.mapTx.end());
return mapModifiedTx.count(it) || inBlock.count(it) || failedTx.count(it);
}
void BlockAssembler::SortForBlock(const CTxMemPool::setEntries& package, CTxMemPool::txiter entry, std::vector<CTxMemPool::txiter>& sortedEntries)
{
// Sort package by ancestor count
// If a transaction A depends on transaction B, then A's ancestor count
// must be greater than B's. So this is sufficient to validly order the
// transactions for block inclusion.
sortedEntries.clear();
sortedEntries.insert(sortedEntries.begin(), package.begin(), package.end());
std::sort(sortedEntries.begin(), sortedEntries.end(), CompareTxIterByAncestorCount());
}
// This transaction selection algorithm orders the mempool based
// on feerate of a transaction including all unconfirmed ancestors.
// Since we don't remove transactions from the mempool as we select them
// for block inclusion, we need an alternate method of updating the feerate
// of a transaction with its not-yet-selected ancestors as we go.
// This is accomplished by walking the in-mempool descendants of selected
// transactions and storing a temporary modified state in mapModifiedTxs.
// Each time through the loop, we compare the best transaction in
// mapModifiedTxs with the next transaction in the mempool to decide what
// transaction package to work on next.
void BlockAssembler::addPackageTxs(int &nPackagesSelected, int &nDescendantsUpdated)
{
// mapModifiedTx will store sorted packages after they are modified
// because some of their txs are already in the block
indexed_modified_transaction_set mapModifiedTx;
// Keep track of entries that failed inclusion, to avoid duplicate work
CTxMemPool::setEntries failedTx;
// Start by adding all descendants of previously added txs to mapModifiedTx
// and modifying them for their already included ancestors
UpdatePackagesForAdded(inBlock, mapModifiedTx);
CTxMemPool::indexed_transaction_set::index<ancestor_score>::type::iterator mi = mempool.mapTx.get<ancestor_score>().begin();
CTxMemPool::txiter iter;
// Limit the number of attempts to add transactions to the block when it is
// close to full; this is just a simple heuristic to finish quickly if the
// mempool has a lot of entries.
const int64_t MAX_CONSECUTIVE_FAILURES = 1000;
int64_t nConsecutiveFailed = 0;
while (mi != mempool.mapTx.get<ancestor_score>().end() || !mapModifiedTx.empty())
{
// First try to find a new transaction in mapTx to evaluate.
if (mi != mempool.mapTx.get<ancestor_score>().end() &&
SkipMapTxEntry(mempool.mapTx.project<0>(mi), mapModifiedTx, failedTx)) {
++mi;
continue;
}
// Now that mi is not stale, determine which transaction to evaluate:
// the next entry from mapTx, or the best from mapModifiedTx?
bool fUsingModified = false;
modtxscoreiter modit = mapModifiedTx.get<ancestor_score>().begin();
if (mi == mempool.mapTx.get<ancestor_score>().end()) {
// We're out of entries in mapTx; use the entry from mapModifiedTx
iter = modit->iter;
fUsingModified = true;
} else {
// Try to compare the mapTx entry to the mapModifiedTx entry
iter = mempool.mapTx.project<0>(mi);
if (modit != mapModifiedTx.get<ancestor_score>().end() &&
CompareModifiedEntry()(*modit, CTxMemPoolModifiedEntry(iter))) {
// The best entry in mapModifiedTx has higher score
// than the one from mapTx.
// Switch which transaction (package) to consider
iter = modit->iter;
fUsingModified = true;
} else {
// Either no entry in mapModifiedTx, or it's worse than mapTx.
// Increment mi for the next loop iteration.
++mi;
}
}
// We skip mapTx entries that are inBlock, and mapModifiedTx shouldn't
// contain anything that is inBlock.
assert(!inBlock.count(iter));
uint64_t packageSize = iter->GetSizeWithAncestors();
CAmount packageFees = iter->GetModFeesWithAncestors();
int64_t packageSigOpsCost = iter->GetSigOpCostWithAncestors();
if (fUsingModified) {
packageSize = modit->nSizeWithAncestors;
packageFees = modit->nModFeesWithAncestors;
packageSigOpsCost = modit->nSigOpCostWithAncestors;
}
if (packageFees < blockMinFeeRate.GetFee(packageSize)) {
// Everything else we might consider has a lower fee rate
return;
}
if (!TestPackage(packageSize, packageSigOpsCost)) {
if (fUsingModified) {
// Since we always look at the best entry in mapModifiedTx,
// we must erase failed entries so that we can consider the
// next best entry on the next loop iteration
mapModifiedTx.get<ancestor_score>().erase(modit);
failedTx.insert(iter);
}
++nConsecutiveFailed;
if (nConsecutiveFailed > MAX_CONSECUTIVE_FAILURES && nBlockWeight >
nBlockMaxWeight - 4000) {
// Give up if we're close to full and haven't succeeded in a while
break;
}
continue;
}
CTxMemPool::setEntries ancestors;
uint64_t nNoLimit = std::numeric_limits<uint64_t>::max();
std::string dummy;
mempool.CalculateMemPoolAncestors(*iter, ancestors, nNoLimit, nNoLimit, nNoLimit, nNoLimit, dummy, false);
onlyUnconfirmed(ancestors);
ancestors.insert(iter);
// Test if all tx's are Final
if (!TestPackageTransactions(ancestors)) {
if (fUsingModified) {
mapModifiedTx.get<ancestor_score>().erase(modit);
failedTx.insert(iter);
}
continue;
}
// This transaction will make it in; reset the failed counter.
nConsecutiveFailed = 0;
// Package can be added. Sort the entries in a valid order.
std::vector<CTxMemPool::txiter> sortedEntries;
SortForBlock(ancestors, iter, sortedEntries);
for (size_t i=0; i<sortedEntries.size(); ++i) {
AddToBlock(sortedEntries[i]);
// Erase from the modified set, if present
mapModifiedTx.erase(sortedEntries[i]);
}
++nPackagesSelected;
// Update transactions that depend on each of these
nDescendantsUpdated += UpdatePackagesForAdded(ancestors, mapModifiedTx);
}
}
void IncrementExtraNonce(CBlock* pblock, const CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
{
// Update nExtraNonce
static uint256 hashPrevBlock;
if (hashPrevBlock != pblock->hashPrevBlock)
{
nExtraNonce = 0;
hashPrevBlock = pblock->hashPrevBlock;
}
++nExtraNonce;
unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
CMutableTransaction txCoinbase(*pblock->vtx[0]);
txCoinbase.vin[0].scriptSig = (CScript() << nHeight << CScriptNum(nExtraNonce)) + COINBASE_FLAGS;
assert(txCoinbase.vin[0].scriptSig.size() <= 100);
pblock->vtx[0] = MakeTransactionRef(std::move(txCoinbase));
pblock->hashMerkleRoot = BlockMerkleRoot(*pblock);
}
| [
"danigarcia3k@gmail.com"
] | danigarcia3k@gmail.com |
feed24664a19d73c5a52513407fb8c64a79b0800 | 7ea74c5ff02dc80f28d0b502c9fb0fa969d507f8 | /parsetable.pb.h | 2f83a759a286cb1135996f81d6daa271200f63a0 | [
"MIT"
] | permissive | anas-harby/Kompiler | 5f26abf98da88d88880f11f0ee5e4e9d670048fc | d4165e687fa1fc85cd69fb1c9b8483ec4c5611e8 | refs/heads/master | 2020-03-25T15:38:50.950987 | 2018-04-28T10:08:52 | 2018-04-28T10:08:52 | 143,894,142 | 0 | 1 | null | 2018-08-07T15:37:02 | 2018-08-07T15:37:02 | null | UTF-8 | C++ | false | true | 29,642 | h | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: parsetable.proto
#ifndef PROTOBUF_parsetable_2eproto__INCLUDED
#define PROTOBUF_parsetable_2eproto__INCLUDED
#include <string>
#include <google/protobuf/stubs/common.h>
#if GOOGLE_PROTOBUF_VERSION < 3005000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
#if 3005001 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
#endif
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/arena.h>
#include <google/protobuf/arenastring.h>
#include <google/protobuf/generated_message_table_driven.h>
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/metadata.h>
#include <google/protobuf/message.h>
#include <google/protobuf/repeated_field.h> // IWYU pragma: export
#include <google/protobuf/extension_set.h> // IWYU pragma: export
#include <google/protobuf/generated_enum_reflection.h>
#include <google/protobuf/unknown_field_set.h>
// @@protoc_insertion_point(includes)
namespace protobuf_parsetable_2eproto {
// Internal implementation detail -- do not use these members.
struct TableStruct {
static const ::google::protobuf::internal::ParseTableField entries[];
static const ::google::protobuf::internal::AuxillaryParseTableField aux[];
static const ::google::protobuf::internal::ParseTable schema[2];
static const ::google::protobuf::internal::FieldMetadata field_metadata[];
static const ::google::protobuf::internal::SerializationTable serialization_table[];
static const ::google::protobuf::uint32 offsets[];
};
void AddDescriptors();
void InitDefaultsParseTable_EntryImpl();
void InitDefaultsParseTable_Entry();
void InitDefaultsParseTableImpl();
void InitDefaultsParseTable();
inline void InitDefaults() {
InitDefaultsParseTable_Entry();
InitDefaultsParseTable();
}
} // namespace protobuf_parsetable_2eproto
namespace parser {
class ParseTable;
class ParseTableDefaultTypeInternal;
extern ParseTableDefaultTypeInternal _ParseTable_default_instance_;
class ParseTable_Entry;
class ParseTable_EntryDefaultTypeInternal;
extern ParseTable_EntryDefaultTypeInternal _ParseTable_Entry_default_instance_;
} // namespace parser
namespace parser {
enum ParseTable_Entry_States {
ParseTable_Entry_States_ERROR = 0,
ParseTable_Entry_States_SYNC = 1,
ParseTable_Entry_States_PROD = 2
};
bool ParseTable_Entry_States_IsValid(int value);
const ParseTable_Entry_States ParseTable_Entry_States_States_MIN = ParseTable_Entry_States_ERROR;
const ParseTable_Entry_States ParseTable_Entry_States_States_MAX = ParseTable_Entry_States_PROD;
const int ParseTable_Entry_States_States_ARRAYSIZE = ParseTable_Entry_States_States_MAX + 1;
const ::google::protobuf::EnumDescriptor* ParseTable_Entry_States_descriptor();
inline const ::std::string& ParseTable_Entry_States_Name(ParseTable_Entry_States value) {
return ::google::protobuf::internal::NameOfEnum(
ParseTable_Entry_States_descriptor(), value);
}
inline bool ParseTable_Entry_States_Parse(
const ::std::string& name, ParseTable_Entry_States* value) {
return ::google::protobuf::internal::ParseNamedEnum<ParseTable_Entry_States>(
ParseTable_Entry_States_descriptor(), name, value);
}
// ===================================================================
class ParseTable_Entry : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:parser.ParseTable.Entry) */ {
public:
ParseTable_Entry();
virtual ~ParseTable_Entry();
ParseTable_Entry(const ParseTable_Entry& from);
inline ParseTable_Entry& operator=(const ParseTable_Entry& from) {
CopyFrom(from);
return *this;
}
#if LANG_CXX11
ParseTable_Entry(ParseTable_Entry&& from) noexcept
: ParseTable_Entry() {
*this = ::std::move(from);
}
inline ParseTable_Entry& operator=(ParseTable_Entry&& from) noexcept {
if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
#endif
inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
return _internal_metadata_.unknown_fields();
}
inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {
return _internal_metadata_.mutable_unknown_fields();
}
static const ::google::protobuf::Descriptor* descriptor();
static const ParseTable_Entry& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const ParseTable_Entry* internal_default_instance() {
return reinterpret_cast<const ParseTable_Entry*>(
&_ParseTable_Entry_default_instance_);
}
static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
0;
void Swap(ParseTable_Entry* other);
friend void swap(ParseTable_Entry& a, ParseTable_Entry& b) {
a.Swap(&b);
}
// implements Message ----------------------------------------------
inline ParseTable_Entry* New() const PROTOBUF_FINAL { return New(NULL); }
ParseTable_Entry* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
void CopyFrom(const ParseTable_Entry& from);
void MergeFrom(const ParseTable_Entry& from);
void Clear() PROTOBUF_FINAL;
bool IsInitialized() const PROTOBUF_FINAL;
size_t ByteSizeLong() const PROTOBUF_FINAL;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const PROTOBUF_FINAL;
void InternalSwap(ParseTable_Entry* other);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return NULL;
}
inline void* MaybeArenaPtr() const {
return NULL;
}
public:
::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;
// nested types ----------------------------------------------------
typedef ParseTable_Entry_States States;
static const States ERROR =
ParseTable_Entry_States_ERROR;
static const States SYNC =
ParseTable_Entry_States_SYNC;
static const States PROD =
ParseTable_Entry_States_PROD;
static inline bool States_IsValid(int value) {
return ParseTable_Entry_States_IsValid(value);
}
static const States States_MIN =
ParseTable_Entry_States_States_MIN;
static const States States_MAX =
ParseTable_Entry_States_States_MAX;
static const int States_ARRAYSIZE =
ParseTable_Entry_States_States_ARRAYSIZE;
static inline const ::google::protobuf::EnumDescriptor*
States_descriptor() {
return ParseTable_Entry_States_descriptor();
}
static inline const ::std::string& States_Name(States value) {
return ParseTable_Entry_States_Name(value);
}
static inline bool States_Parse(const ::std::string& name,
States* value) {
return ParseTable_Entry_States_Parse(name, value);
}
// accessors -------------------------------------------------------
// repeated string productions = 4;
int productions_size() const;
void clear_productions();
static const int kProductionsFieldNumber = 4;
const ::std::string& productions(int index) const;
::std::string* mutable_productions(int index);
void set_productions(int index, const ::std::string& value);
#if LANG_CXX11
void set_productions(int index, ::std::string&& value);
#endif
void set_productions(int index, const char* value);
void set_productions(int index, const char* value, size_t size);
::std::string* add_productions();
void add_productions(const ::std::string& value);
#if LANG_CXX11
void add_productions(::std::string&& value);
#endif
void add_productions(const char* value);
void add_productions(const char* value, size_t size);
const ::google::protobuf::RepeatedPtrField< ::std::string>& productions() const;
::google::protobuf::RepeatedPtrField< ::std::string>* mutable_productions();
// required string nonterm = 2;
bool has_nonterm() const;
void clear_nonterm();
static const int kNontermFieldNumber = 2;
const ::std::string& nonterm() const;
void set_nonterm(const ::std::string& value);
#if LANG_CXX11
void set_nonterm(::std::string&& value);
#endif
void set_nonterm(const char* value);
void set_nonterm(const char* value, size_t size);
::std::string* mutable_nonterm();
::std::string* release_nonterm();
void set_allocated_nonterm(::std::string* nonterm);
// required string term = 3;
bool has_term() const;
void clear_term();
static const int kTermFieldNumber = 3;
const ::std::string& term() const;
void set_term(const ::std::string& value);
#if LANG_CXX11
void set_term(::std::string&& value);
#endif
void set_term(const char* value);
void set_term(const char* value, size_t size);
::std::string* mutable_term();
::std::string* release_term();
void set_allocated_term(::std::string* term);
// required .parser.ParseTable.Entry.States state = 1;
bool has_state() const;
void clear_state();
static const int kStateFieldNumber = 1;
::parser::ParseTable_Entry_States state() const;
void set_state(::parser::ParseTable_Entry_States value);
// @@protoc_insertion_point(class_scope:parser.ParseTable.Entry)
private:
void set_has_state();
void clear_has_state();
void set_has_nonterm();
void clear_has_nonterm();
void set_has_term();
void clear_has_term();
// helper for ByteSizeLong()
size_t RequiredFieldsByteSizeFallback() const;
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
::google::protobuf::internal::HasBits<1> _has_bits_;
mutable int _cached_size_;
::google::protobuf::RepeatedPtrField< ::std::string> productions_;
::google::protobuf::internal::ArenaStringPtr nonterm_;
::google::protobuf::internal::ArenaStringPtr term_;
int state_;
friend struct ::protobuf_parsetable_2eproto::TableStruct;
friend void ::protobuf_parsetable_2eproto::InitDefaultsParseTable_EntryImpl();
};
// -------------------------------------------------------------------
class ParseTable : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:parser.ParseTable) */ {
public:
ParseTable();
virtual ~ParseTable();
ParseTable(const ParseTable& from);
inline ParseTable& operator=(const ParseTable& from) {
CopyFrom(from);
return *this;
}
#if LANG_CXX11
ParseTable(ParseTable&& from) noexcept
: ParseTable() {
*this = ::std::move(from);
}
inline ParseTable& operator=(ParseTable&& from) noexcept {
if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
#endif
inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
return _internal_metadata_.unknown_fields();
}
inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {
return _internal_metadata_.mutable_unknown_fields();
}
static const ::google::protobuf::Descriptor* descriptor();
static const ParseTable& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const ParseTable* internal_default_instance() {
return reinterpret_cast<const ParseTable*>(
&_ParseTable_default_instance_);
}
static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
1;
void Swap(ParseTable* other);
friend void swap(ParseTable& a, ParseTable& b) {
a.Swap(&b);
}
// implements Message ----------------------------------------------
inline ParseTable* New() const PROTOBUF_FINAL { return New(NULL); }
ParseTable* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
void CopyFrom(const ParseTable& from);
void MergeFrom(const ParseTable& from);
void Clear() PROTOBUF_FINAL;
bool IsInitialized() const PROTOBUF_FINAL;
size_t ByteSizeLong() const PROTOBUF_FINAL;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const PROTOBUF_FINAL;
void InternalSwap(ParseTable* other);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return NULL;
}
inline void* MaybeArenaPtr() const {
return NULL;
}
public:
::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;
// nested types ----------------------------------------------------
typedef ParseTable_Entry Entry;
// accessors -------------------------------------------------------
// repeated .parser.ParseTable.Entry entries = 2;
int entries_size() const;
void clear_entries();
static const int kEntriesFieldNumber = 2;
const ::parser::ParseTable_Entry& entries(int index) const;
::parser::ParseTable_Entry* mutable_entries(int index);
::parser::ParseTable_Entry* add_entries();
::google::protobuf::RepeatedPtrField< ::parser::ParseTable_Entry >*
mutable_entries();
const ::google::protobuf::RepeatedPtrField< ::parser::ParseTable_Entry >&
entries() const;
// required string starting_symbol = 1;
bool has_starting_symbol() const;
void clear_starting_symbol();
static const int kStartingSymbolFieldNumber = 1;
const ::std::string& starting_symbol() const;
void set_starting_symbol(const ::std::string& value);
#if LANG_CXX11
void set_starting_symbol(::std::string&& value);
#endif
void set_starting_symbol(const char* value);
void set_starting_symbol(const char* value, size_t size);
::std::string* mutable_starting_symbol();
::std::string* release_starting_symbol();
void set_allocated_starting_symbol(::std::string* starting_symbol);
// @@protoc_insertion_point(class_scope:parser.ParseTable)
private:
void set_has_starting_symbol();
void clear_has_starting_symbol();
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
::google::protobuf::internal::HasBits<1> _has_bits_;
mutable int _cached_size_;
::google::protobuf::RepeatedPtrField< ::parser::ParseTable_Entry > entries_;
::google::protobuf::internal::ArenaStringPtr starting_symbol_;
friend struct ::protobuf_parsetable_2eproto::TableStruct;
friend void ::protobuf_parsetable_2eproto::InitDefaultsParseTableImpl();
};
// ===================================================================
// ===================================================================
#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wstrict-aliasing"
#endif // __GNUC__
// ParseTable_Entry
// required .parser.ParseTable.Entry.States state = 1;
inline bool ParseTable_Entry::has_state() const {
return (_has_bits_[0] & 0x00000004u) != 0;
}
inline void ParseTable_Entry::set_has_state() {
_has_bits_[0] |= 0x00000004u;
}
inline void ParseTable_Entry::clear_has_state() {
_has_bits_[0] &= ~0x00000004u;
}
inline void ParseTable_Entry::clear_state() {
state_ = 0;
clear_has_state();
}
inline ::parser::ParseTable_Entry_States ParseTable_Entry::state() const {
// @@protoc_insertion_point(field_get:parser.ParseTable.Entry.state)
return static_cast< ::parser::ParseTable_Entry_States >(state_);
}
inline void ParseTable_Entry::set_state(::parser::ParseTable_Entry_States value) {
assert(::parser::ParseTable_Entry_States_IsValid(value));
set_has_state();
state_ = value;
// @@protoc_insertion_point(field_set:parser.ParseTable.Entry.state)
}
// required string nonterm = 2;
inline bool ParseTable_Entry::has_nonterm() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
inline void ParseTable_Entry::set_has_nonterm() {
_has_bits_[0] |= 0x00000001u;
}
inline void ParseTable_Entry::clear_has_nonterm() {
_has_bits_[0] &= ~0x00000001u;
}
inline void ParseTable_Entry::clear_nonterm() {
nonterm_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
clear_has_nonterm();
}
inline const ::std::string& ParseTable_Entry::nonterm() const {
// @@protoc_insertion_point(field_get:parser.ParseTable.Entry.nonterm)
return nonterm_.GetNoArena();
}
inline void ParseTable_Entry::set_nonterm(const ::std::string& value) {
set_has_nonterm();
nonterm_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:parser.ParseTable.Entry.nonterm)
}
#if LANG_CXX11
inline void ParseTable_Entry::set_nonterm(::std::string&& value) {
set_has_nonterm();
nonterm_.SetNoArena(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
// @@protoc_insertion_point(field_set_rvalue:parser.ParseTable.Entry.nonterm)
}
#endif
inline void ParseTable_Entry::set_nonterm(const char* value) {
GOOGLE_DCHECK(value != NULL);
set_has_nonterm();
nonterm_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:parser.ParseTable.Entry.nonterm)
}
inline void ParseTable_Entry::set_nonterm(const char* value, size_t size) {
set_has_nonterm();
nonterm_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:parser.ParseTable.Entry.nonterm)
}
inline ::std::string* ParseTable_Entry::mutable_nonterm() {
set_has_nonterm();
// @@protoc_insertion_point(field_mutable:parser.ParseTable.Entry.nonterm)
return nonterm_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline ::std::string* ParseTable_Entry::release_nonterm() {
// @@protoc_insertion_point(field_release:parser.ParseTable.Entry.nonterm)
clear_has_nonterm();
return nonterm_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline void ParseTable_Entry::set_allocated_nonterm(::std::string* nonterm) {
if (nonterm != NULL) {
set_has_nonterm();
} else {
clear_has_nonterm();
}
nonterm_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), nonterm);
// @@protoc_insertion_point(field_set_allocated:parser.ParseTable.Entry.nonterm)
}
// required string term = 3;
inline bool ParseTable_Entry::has_term() const {
return (_has_bits_[0] & 0x00000002u) != 0;
}
inline void ParseTable_Entry::set_has_term() {
_has_bits_[0] |= 0x00000002u;
}
inline void ParseTable_Entry::clear_has_term() {
_has_bits_[0] &= ~0x00000002u;
}
inline void ParseTable_Entry::clear_term() {
term_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
clear_has_term();
}
inline const ::std::string& ParseTable_Entry::term() const {
// @@protoc_insertion_point(field_get:parser.ParseTable.Entry.term)
return term_.GetNoArena();
}
inline void ParseTable_Entry::set_term(const ::std::string& value) {
set_has_term();
term_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:parser.ParseTable.Entry.term)
}
#if LANG_CXX11
inline void ParseTable_Entry::set_term(::std::string&& value) {
set_has_term();
term_.SetNoArena(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
// @@protoc_insertion_point(field_set_rvalue:parser.ParseTable.Entry.term)
}
#endif
inline void ParseTable_Entry::set_term(const char* value) {
GOOGLE_DCHECK(value != NULL);
set_has_term();
term_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:parser.ParseTable.Entry.term)
}
inline void ParseTable_Entry::set_term(const char* value, size_t size) {
set_has_term();
term_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:parser.ParseTable.Entry.term)
}
inline ::std::string* ParseTable_Entry::mutable_term() {
set_has_term();
// @@protoc_insertion_point(field_mutable:parser.ParseTable.Entry.term)
return term_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline ::std::string* ParseTable_Entry::release_term() {
// @@protoc_insertion_point(field_release:parser.ParseTable.Entry.term)
clear_has_term();
return term_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline void ParseTable_Entry::set_allocated_term(::std::string* term) {
if (term != NULL) {
set_has_term();
} else {
clear_has_term();
}
term_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), term);
// @@protoc_insertion_point(field_set_allocated:parser.ParseTable.Entry.term)
}
// repeated string productions = 4;
inline int ParseTable_Entry::productions_size() const {
return productions_.size();
}
inline void ParseTable_Entry::clear_productions() {
productions_.Clear();
}
inline const ::std::string& ParseTable_Entry::productions(int index) const {
// @@protoc_insertion_point(field_get:parser.ParseTable.Entry.productions)
return productions_.Get(index);
}
inline ::std::string* ParseTable_Entry::mutable_productions(int index) {
// @@protoc_insertion_point(field_mutable:parser.ParseTable.Entry.productions)
return productions_.Mutable(index);
}
inline void ParseTable_Entry::set_productions(int index, const ::std::string& value) {
// @@protoc_insertion_point(field_set:parser.ParseTable.Entry.productions)
productions_.Mutable(index)->assign(value);
}
#if LANG_CXX11
inline void ParseTable_Entry::set_productions(int index, ::std::string&& value) {
// @@protoc_insertion_point(field_set:parser.ParseTable.Entry.productions)
productions_.Mutable(index)->assign(std::move(value));
}
#endif
inline void ParseTable_Entry::set_productions(int index, const char* value) {
GOOGLE_DCHECK(value != NULL);
productions_.Mutable(index)->assign(value);
// @@protoc_insertion_point(field_set_char:parser.ParseTable.Entry.productions)
}
inline void ParseTable_Entry::set_productions(int index, const char* value, size_t size) {
productions_.Mutable(index)->assign(
reinterpret_cast<const char*>(value), size);
// @@protoc_insertion_point(field_set_pointer:parser.ParseTable.Entry.productions)
}
inline ::std::string* ParseTable_Entry::add_productions() {
// @@protoc_insertion_point(field_add_mutable:parser.ParseTable.Entry.productions)
return productions_.Add();
}
inline void ParseTable_Entry::add_productions(const ::std::string& value) {
productions_.Add()->assign(value);
// @@protoc_insertion_point(field_add:parser.ParseTable.Entry.productions)
}
#if LANG_CXX11
inline void ParseTable_Entry::add_productions(::std::string&& value) {
productions_.Add(std::move(value));
// @@protoc_insertion_point(field_add:parser.ParseTable.Entry.productions)
}
#endif
inline void ParseTable_Entry::add_productions(const char* value) {
GOOGLE_DCHECK(value != NULL);
productions_.Add()->assign(value);
// @@protoc_insertion_point(field_add_char:parser.ParseTable.Entry.productions)
}
inline void ParseTable_Entry::add_productions(const char* value, size_t size) {
productions_.Add()->assign(reinterpret_cast<const char*>(value), size);
// @@protoc_insertion_point(field_add_pointer:parser.ParseTable.Entry.productions)
}
inline const ::google::protobuf::RepeatedPtrField< ::std::string>&
ParseTable_Entry::productions() const {
// @@protoc_insertion_point(field_list:parser.ParseTable.Entry.productions)
return productions_;
}
inline ::google::protobuf::RepeatedPtrField< ::std::string>*
ParseTable_Entry::mutable_productions() {
// @@protoc_insertion_point(field_mutable_list:parser.ParseTable.Entry.productions)
return &productions_;
}
// -------------------------------------------------------------------
// ParseTable
// required string starting_symbol = 1;
inline bool ParseTable::has_starting_symbol() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
inline void ParseTable::set_has_starting_symbol() {
_has_bits_[0] |= 0x00000001u;
}
inline void ParseTable::clear_has_starting_symbol() {
_has_bits_[0] &= ~0x00000001u;
}
inline void ParseTable::clear_starting_symbol() {
starting_symbol_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
clear_has_starting_symbol();
}
inline const ::std::string& ParseTable::starting_symbol() const {
// @@protoc_insertion_point(field_get:parser.ParseTable.starting_symbol)
return starting_symbol_.GetNoArena();
}
inline void ParseTable::set_starting_symbol(const ::std::string& value) {
set_has_starting_symbol();
starting_symbol_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:parser.ParseTable.starting_symbol)
}
#if LANG_CXX11
inline void ParseTable::set_starting_symbol(::std::string&& value) {
set_has_starting_symbol();
starting_symbol_.SetNoArena(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
// @@protoc_insertion_point(field_set_rvalue:parser.ParseTable.starting_symbol)
}
#endif
inline void ParseTable::set_starting_symbol(const char* value) {
GOOGLE_DCHECK(value != NULL);
set_has_starting_symbol();
starting_symbol_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:parser.ParseTable.starting_symbol)
}
inline void ParseTable::set_starting_symbol(const char* value, size_t size) {
set_has_starting_symbol();
starting_symbol_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:parser.ParseTable.starting_symbol)
}
inline ::std::string* ParseTable::mutable_starting_symbol() {
set_has_starting_symbol();
// @@protoc_insertion_point(field_mutable:parser.ParseTable.starting_symbol)
return starting_symbol_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline ::std::string* ParseTable::release_starting_symbol() {
// @@protoc_insertion_point(field_release:parser.ParseTable.starting_symbol)
clear_has_starting_symbol();
return starting_symbol_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline void ParseTable::set_allocated_starting_symbol(::std::string* starting_symbol) {
if (starting_symbol != NULL) {
set_has_starting_symbol();
} else {
clear_has_starting_symbol();
}
starting_symbol_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), starting_symbol);
// @@protoc_insertion_point(field_set_allocated:parser.ParseTable.starting_symbol)
}
// repeated .parser.ParseTable.Entry entries = 2;
inline int ParseTable::entries_size() const {
return entries_.size();
}
inline void ParseTable::clear_entries() {
entries_.Clear();
}
inline const ::parser::ParseTable_Entry& ParseTable::entries(int index) const {
// @@protoc_insertion_point(field_get:parser.ParseTable.entries)
return entries_.Get(index);
}
inline ::parser::ParseTable_Entry* ParseTable::mutable_entries(int index) {
// @@protoc_insertion_point(field_mutable:parser.ParseTable.entries)
return entries_.Mutable(index);
}
inline ::parser::ParseTable_Entry* ParseTable::add_entries() {
// @@protoc_insertion_point(field_add:parser.ParseTable.entries)
return entries_.Add();
}
inline ::google::protobuf::RepeatedPtrField< ::parser::ParseTable_Entry >*
ParseTable::mutable_entries() {
// @@protoc_insertion_point(field_mutable_list:parser.ParseTable.entries)
return &entries_;
}
inline const ::google::protobuf::RepeatedPtrField< ::parser::ParseTable_Entry >&
ParseTable::entries() const {
// @@protoc_insertion_point(field_list:parser.ParseTable.entries)
return entries_;
}
#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif // __GNUC__
// -------------------------------------------------------------------
// @@protoc_insertion_point(namespace_scope)
} // namespace parser
namespace google {
namespace protobuf {
template <> struct is_proto_enum< ::parser::ParseTable_Entry_States> : ::google::protobuf::internal::true_type {};
template <>
inline const EnumDescriptor* GetEnumDescriptor< ::parser::ParseTable_Entry_States>() {
return ::parser::ParseTable_Entry_States_descriptor();
}
} // namespace protobuf
} // namespace google
// @@protoc_insertion_point(global_scope)
#endif // PROTOBUF_parsetable_2eproto__INCLUDED
| [
"marwan.01010100@gmail.com"
] | marwan.01010100@gmail.com |
45ce31f67af80d79429432a91a380e67e3542472 | 96e7347db30d3ae35f2df119a18472cf5b251fa2 | /Classes/Native/mscorlib_System_Security_Cryptography_HMACSHA12307349023.h | c41833ecb6628cf5ce9bb7242e84dd85064f7554 | [] | no_license | Henry0285/abcwriting | 04b111887489d9255fd2697a4ea8d9971dc17d89 | ed2e4da72fbbad85d9e0e9d912e73ddd33bc91ec | refs/heads/master | 2021-01-20T14:16:48.025648 | 2017-05-08T06:00:06 | 2017-05-08T06:00:06 | 90,583,162 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 555 | h | #pragma once
#include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <stdint.h>
#include "mscorlib_System_Security_Cryptography_HMAC2137965578.h"
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Security.Cryptography.HMACSHA1
struct HMACSHA1_t2307349023 : public HMAC_t2137965578
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
| [
"phamnguyentruc@yahoo.com"
] | phamnguyentruc@yahoo.com |
f158b551cd3cc7a6faeafa8f84c286e2f4014a14 | b59120b25ce2d851f82abaf8854b5dd690b92666 | /Dungeon-DashP3/Hero.cpp | f69a1129e458f1b5d775aa443239afa48c3f0bf3 | [] | no_license | Nwyattc/DungeonDash | ecca204f630df190d4ddc6a2822df8faabbf5133 | 3797e1278d29892990b7c80beca292cbfcb52b8d | refs/heads/master | 2020-05-07T00:55:32.483695 | 2019-04-09T00:22:29 | 2019-04-09T00:22:29 | 180,250,582 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,019 | cpp | #include <iostream>
#include <cstdlib>
#include <unistd.h>
#include <stdio.h>
#include <string>
#include <fstream>
#include "Hero.h"
using namespace std;
Hero::Hero(){
health = 8;
currHealth = 8;
attack = 2;
level = 1;
name = "Hero";
//talent
}
Hero::Hero(int h, int a, int l, string n){ //add in
health = h;
attack = a;
level = l;
name = n;
//
}
void Hero::HsetHealth(int h){
health = h;
}
int Hero::HgetHealth(){
return health;
}
void Hero::HsetCurrHealth(int num){
if((currHealth + num) > health){
currHealth = health;
}
else {
currHealth = currHealth + num;
}
}
int Hero::HgetCurrHealth(){
return currHealth;
}
void Hero::HsetAttack(int a){
attack = a;
}
int Hero::HgetAttack(){
return attack;
}
void Hero::HsetLevel(int l){
level = l;
}
int Hero::HgetLevel(){
return level;
}
void Hero::HsetName(string n){
name = n;
}
string Hero::HgetName(){
return name;
}
//method associated with talent | [
"nwayttc@gmail.com"
] | nwayttc@gmail.com |
11fe2fbe1387c90c52cd004f945266b08464cdd2 | cc0b7d50a3c6e6b329aab5b0aa0a349580bddbdd | /constant/cs11/polyMesh/neighbour | 73f04f929113bad3cc5e7cc996b79891ed2afea7 | [] | 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 | 23,379 | /*--------------------------------*- 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;
note "nPoints:5202 nCells:2500 nFaces:10100 nInternalFaces:4900";
location "constant/cs11/polyMesh";
object neighbour;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
4900
(
1
50
2
51
3
52
4
53
5
54
6
55
7
56
8
57
9
58
10
59
11
60
12
61
13
62
14
63
15
64
16
65
17
66
18
67
19
68
20
69
21
70
22
71
23
72
24
73
25
74
26
75
27
76
28
77
29
78
30
79
31
80
32
81
33
82
34
83
35
84
36
85
37
86
38
87
39
88
40
89
41
90
42
91
43
92
44
93
45
94
46
95
47
96
48
97
49
98
99
51
100
52
101
53
102
54
103
55
104
56
105
57
106
58
107
59
108
60
109
61
110
62
111
63
112
64
113
65
114
66
115
67
116
68
117
69
118
70
119
71
120
72
121
73
122
74
123
75
124
76
125
77
126
78
127
79
128
80
129
81
130
82
131
83
132
84
133
85
134
86
135
87
136
88
137
89
138
90
139
91
140
92
141
93
142
94
143
95
144
96
145
97
146
98
147
99
148
149
101
150
102
151
103
152
104
153
105
154
106
155
107
156
108
157
109
158
110
159
111
160
112
161
113
162
114
163
115
164
116
165
117
166
118
167
119
168
120
169
121
170
122
171
123
172
124
173
125
174
126
175
127
176
128
177
129
178
130
179
131
180
132
181
133
182
134
183
135
184
136
185
137
186
138
187
139
188
140
189
141
190
142
191
143
192
144
193
145
194
146
195
147
196
148
197
149
198
199
151
200
152
201
153
202
154
203
155
204
156
205
157
206
158
207
159
208
160
209
161
210
162
211
163
212
164
213
165
214
166
215
167
216
168
217
169
218
170
219
171
220
172
221
173
222
174
223
175
224
176
225
177
226
178
227
179
228
180
229
181
230
182
231
183
232
184
233
185
234
186
235
187
236
188
237
189
238
190
239
191
240
192
241
193
242
194
243
195
244
196
245
197
246
198
247
199
248
249
201
250
202
251
203
252
204
253
205
254
206
255
207
256
208
257
209
258
210
259
211
260
212
261
213
262
214
263
215
264
216
265
217
266
218
267
219
268
220
269
221
270
222
271
223
272
224
273
225
274
226
275
227
276
228
277
229
278
230
279
231
280
232
281
233
282
234
283
235
284
236
285
237
286
238
287
239
288
240
289
241
290
242
291
243
292
244
293
245
294
246
295
247
296
248
297
249
298
299
251
300
252
301
253
302
254
303
255
304
256
305
257
306
258
307
259
308
260
309
261
310
262
311
263
312
264
313
265
314
266
315
267
316
268
317
269
318
270
319
271
320
272
321
273
322
274
323
275
324
276
325
277
326
278
327
279
328
280
329
281
330
282
331
283
332
284
333
285
334
286
335
287
336
288
337
289
338
290
339
291
340
292
341
293
342
294
343
295
344
296
345
297
346
298
347
299
348
349
301
350
302
351
303
352
304
353
305
354
306
355
307
356
308
357
309
358
310
359
311
360
312
361
313
362
314
363
315
364
316
365
317
366
318
367
319
368
320
369
321
370
322
371
323
372
324
373
325
374
326
375
327
376
328
377
329
378
330
379
331
380
332
381
333
382
334
383
335
384
336
385
337
386
338
387
339
388
340
389
341
390
342
391
343
392
344
393
345
394
346
395
347
396
348
397
349
398
399
351
400
352
401
353
402
354
403
355
404
356
405
357
406
358
407
359
408
360
409
361
410
362
411
363
412
364
413
365
414
366
415
367
416
368
417
369
418
370
419
371
420
372
421
373
422
374
423
375
424
376
425
377
426
378
427
379
428
380
429
381
430
382
431
383
432
384
433
385
434
386
435
387
436
388
437
389
438
390
439
391
440
392
441
393
442
394
443
395
444
396
445
397
446
398
447
399
448
449
401
450
402
451
403
452
404
453
405
454
406
455
407
456
408
457
409
458
410
459
411
460
412
461
413
462
414
463
415
464
416
465
417
466
418
467
419
468
420
469
421
470
422
471
423
472
424
473
425
474
426
475
427
476
428
477
429
478
430
479
431
480
432
481
433
482
434
483
435
484
436
485
437
486
438
487
439
488
440
489
441
490
442
491
443
492
444
493
445
494
446
495
447
496
448
497
449
498
499
451
500
452
501
453
502
454
503
455
504
456
505
457
506
458
507
459
508
460
509
461
510
462
511
463
512
464
513
465
514
466
515
467
516
468
517
469
518
470
519
471
520
472
521
473
522
474
523
475
524
476
525
477
526
478
527
479
528
480
529
481
530
482
531
483
532
484
533
485
534
486
535
487
536
488
537
489
538
490
539
491
540
492
541
493
542
494
543
495
544
496
545
497
546
498
547
499
548
549
501
550
502
551
503
552
504
553
505
554
506
555
507
556
508
557
509
558
510
559
511
560
512
561
513
562
514
563
515
564
516
565
517
566
518
567
519
568
520
569
521
570
522
571
523
572
524
573
525
574
526
575
527
576
528
577
529
578
530
579
531
580
532
581
533
582
534
583
535
584
536
585
537
586
538
587
539
588
540
589
541
590
542
591
543
592
544
593
545
594
546
595
547
596
548
597
549
598
599
551
600
552
601
553
602
554
603
555
604
556
605
557
606
558
607
559
608
560
609
561
610
562
611
563
612
564
613
565
614
566
615
567
616
568
617
569
618
570
619
571
620
572
621
573
622
574
623
575
624
576
625
577
626
578
627
579
628
580
629
581
630
582
631
583
632
584
633
585
634
586
635
587
636
588
637
589
638
590
639
591
640
592
641
593
642
594
643
595
644
596
645
597
646
598
647
599
648
649
601
650
602
651
603
652
604
653
605
654
606
655
607
656
608
657
609
658
610
659
611
660
612
661
613
662
614
663
615
664
616
665
617
666
618
667
619
668
620
669
621
670
622
671
623
672
624
673
625
674
626
675
627
676
628
677
629
678
630
679
631
680
632
681
633
682
634
683
635
684
636
685
637
686
638
687
639
688
640
689
641
690
642
691
643
692
644
693
645
694
646
695
647
696
648
697
649
698
699
651
700
652
701
653
702
654
703
655
704
656
705
657
706
658
707
659
708
660
709
661
710
662
711
663
712
664
713
665
714
666
715
667
716
668
717
669
718
670
719
671
720
672
721
673
722
674
723
675
724
676
725
677
726
678
727
679
728
680
729
681
730
682
731
683
732
684
733
685
734
686
735
687
736
688
737
689
738
690
739
691
740
692
741
693
742
694
743
695
744
696
745
697
746
698
747
699
748
749
701
750
702
751
703
752
704
753
705
754
706
755
707
756
708
757
709
758
710
759
711
760
712
761
713
762
714
763
715
764
716
765
717
766
718
767
719
768
720
769
721
770
722
771
723
772
724
773
725
774
726
775
727
776
728
777
729
778
730
779
731
780
732
781
733
782
734
783
735
784
736
785
737
786
738
787
739
788
740
789
741
790
742
791
743
792
744
793
745
794
746
795
747
796
748
797
749
798
799
751
800
752
801
753
802
754
803
755
804
756
805
757
806
758
807
759
808
760
809
761
810
762
811
763
812
764
813
765
814
766
815
767
816
768
817
769
818
770
819
771
820
772
821
773
822
774
823
775
824
776
825
777
826
778
827
779
828
780
829
781
830
782
831
783
832
784
833
785
834
786
835
787
836
788
837
789
838
790
839
791
840
792
841
793
842
794
843
795
844
796
845
797
846
798
847
799
848
849
801
850
802
851
803
852
804
853
805
854
806
855
807
856
808
857
809
858
810
859
811
860
812
861
813
862
814
863
815
864
816
865
817
866
818
867
819
868
820
869
821
870
822
871
823
872
824
873
825
874
826
875
827
876
828
877
829
878
830
879
831
880
832
881
833
882
834
883
835
884
836
885
837
886
838
887
839
888
840
889
841
890
842
891
843
892
844
893
845
894
846
895
847
896
848
897
849
898
899
851
900
852
901
853
902
854
903
855
904
856
905
857
906
858
907
859
908
860
909
861
910
862
911
863
912
864
913
865
914
866
915
867
916
868
917
869
918
870
919
871
920
872
921
873
922
874
923
875
924
876
925
877
926
878
927
879
928
880
929
881
930
882
931
883
932
884
933
885
934
886
935
887
936
888
937
889
938
890
939
891
940
892
941
893
942
894
943
895
944
896
945
897
946
898
947
899
948
949
901
950
902
951
903
952
904
953
905
954
906
955
907
956
908
957
909
958
910
959
911
960
912
961
913
962
914
963
915
964
916
965
917
966
918
967
919
968
920
969
921
970
922
971
923
972
924
973
925
974
926
975
927
976
928
977
929
978
930
979
931
980
932
981
933
982
934
983
935
984
936
985
937
986
938
987
939
988
940
989
941
990
942
991
943
992
944
993
945
994
946
995
947
996
948
997
949
998
999
951
1000
952
1001
953
1002
954
1003
955
1004
956
1005
957
1006
958
1007
959
1008
960
1009
961
1010
962
1011
963
1012
964
1013
965
1014
966
1015
967
1016
968
1017
969
1018
970
1019
971
1020
972
1021
973
1022
974
1023
975
1024
976
1025
977
1026
978
1027
979
1028
980
1029
981
1030
982
1031
983
1032
984
1033
985
1034
986
1035
987
1036
988
1037
989
1038
990
1039
991
1040
992
1041
993
1042
994
1043
995
1044
996
1045
997
1046
998
1047
999
1048
1049
1001
1050
1002
1051
1003
1052
1004
1053
1005
1054
1006
1055
1007
1056
1008
1057
1009
1058
1010
1059
1011
1060
1012
1061
1013
1062
1014
1063
1015
1064
1016
1065
1017
1066
1018
1067
1019
1068
1020
1069
1021
1070
1022
1071
1023
1072
1024
1073
1025
1074
1026
1075
1027
1076
1028
1077
1029
1078
1030
1079
1031
1080
1032
1081
1033
1082
1034
1083
1035
1084
1036
1085
1037
1086
1038
1087
1039
1088
1040
1089
1041
1090
1042
1091
1043
1092
1044
1093
1045
1094
1046
1095
1047
1096
1048
1097
1049
1098
1099
1051
1100
1052
1101
1053
1102
1054
1103
1055
1104
1056
1105
1057
1106
1058
1107
1059
1108
1060
1109
1061
1110
1062
1111
1063
1112
1064
1113
1065
1114
1066
1115
1067
1116
1068
1117
1069
1118
1070
1119
1071
1120
1072
1121
1073
1122
1074
1123
1075
1124
1076
1125
1077
1126
1078
1127
1079
1128
1080
1129
1081
1130
1082
1131
1083
1132
1084
1133
1085
1134
1086
1135
1087
1136
1088
1137
1089
1138
1090
1139
1091
1140
1092
1141
1093
1142
1094
1143
1095
1144
1096
1145
1097
1146
1098
1147
1099
1148
1149
1101
1150
1102
1151
1103
1152
1104
1153
1105
1154
1106
1155
1107
1156
1108
1157
1109
1158
1110
1159
1111
1160
1112
1161
1113
1162
1114
1163
1115
1164
1116
1165
1117
1166
1118
1167
1119
1168
1120
1169
1121
1170
1122
1171
1123
1172
1124
1173
1125
1174
1126
1175
1127
1176
1128
1177
1129
1178
1130
1179
1131
1180
1132
1181
1133
1182
1134
1183
1135
1184
1136
1185
1137
1186
1138
1187
1139
1188
1140
1189
1141
1190
1142
1191
1143
1192
1144
1193
1145
1194
1146
1195
1147
1196
1148
1197
1149
1198
1199
1151
1200
1152
1201
1153
1202
1154
1203
1155
1204
1156
1205
1157
1206
1158
1207
1159
1208
1160
1209
1161
1210
1162
1211
1163
1212
1164
1213
1165
1214
1166
1215
1167
1216
1168
1217
1169
1218
1170
1219
1171
1220
1172
1221
1173
1222
1174
1223
1175
1224
1176
1225
1177
1226
1178
1227
1179
1228
1180
1229
1181
1230
1182
1231
1183
1232
1184
1233
1185
1234
1186
1235
1187
1236
1188
1237
1189
1238
1190
1239
1191
1240
1192
1241
1193
1242
1194
1243
1195
1244
1196
1245
1197
1246
1198
1247
1199
1248
1249
1201
1250
1202
1251
1203
1252
1204
1253
1205
1254
1206
1255
1207
1256
1208
1257
1209
1258
1210
1259
1211
1260
1212
1261
1213
1262
1214
1263
1215
1264
1216
1265
1217
1266
1218
1267
1219
1268
1220
1269
1221
1270
1222
1271
1223
1272
1224
1273
1225
1274
1226
1275
1227
1276
1228
1277
1229
1278
1230
1279
1231
1280
1232
1281
1233
1282
1234
1283
1235
1284
1236
1285
1237
1286
1238
1287
1239
1288
1240
1289
1241
1290
1242
1291
1243
1292
1244
1293
1245
1294
1246
1295
1247
1296
1248
1297
1249
1298
1299
1251
1300
1252
1301
1253
1302
1254
1303
1255
1304
1256
1305
1257
1306
1258
1307
1259
1308
1260
1309
1261
1310
1262
1311
1263
1312
1264
1313
1265
1314
1266
1315
1267
1316
1268
1317
1269
1318
1270
1319
1271
1320
1272
1321
1273
1322
1274
1323
1275
1324
1276
1325
1277
1326
1278
1327
1279
1328
1280
1329
1281
1330
1282
1331
1283
1332
1284
1333
1285
1334
1286
1335
1287
1336
1288
1337
1289
1338
1290
1339
1291
1340
1292
1341
1293
1342
1294
1343
1295
1344
1296
1345
1297
1346
1298
1347
1299
1348
1349
1301
1350
1302
1351
1303
1352
1304
1353
1305
1354
1306
1355
1307
1356
1308
1357
1309
1358
1310
1359
1311
1360
1312
1361
1313
1362
1314
1363
1315
1364
1316
1365
1317
1366
1318
1367
1319
1368
1320
1369
1321
1370
1322
1371
1323
1372
1324
1373
1325
1374
1326
1375
1327
1376
1328
1377
1329
1378
1330
1379
1331
1380
1332
1381
1333
1382
1334
1383
1335
1384
1336
1385
1337
1386
1338
1387
1339
1388
1340
1389
1341
1390
1342
1391
1343
1392
1344
1393
1345
1394
1346
1395
1347
1396
1348
1397
1349
1398
1399
1351
1400
1352
1401
1353
1402
1354
1403
1355
1404
1356
1405
1357
1406
1358
1407
1359
1408
1360
1409
1361
1410
1362
1411
1363
1412
1364
1413
1365
1414
1366
1415
1367
1416
1368
1417
1369
1418
1370
1419
1371
1420
1372
1421
1373
1422
1374
1423
1375
1424
1376
1425
1377
1426
1378
1427
1379
1428
1380
1429
1381
1430
1382
1431
1383
1432
1384
1433
1385
1434
1386
1435
1387
1436
1388
1437
1389
1438
1390
1439
1391
1440
1392
1441
1393
1442
1394
1443
1395
1444
1396
1445
1397
1446
1398
1447
1399
1448
1449
1401
1450
1402
1451
1403
1452
1404
1453
1405
1454
1406
1455
1407
1456
1408
1457
1409
1458
1410
1459
1411
1460
1412
1461
1413
1462
1414
1463
1415
1464
1416
1465
1417
1466
1418
1467
1419
1468
1420
1469
1421
1470
1422
1471
1423
1472
1424
1473
1425
1474
1426
1475
1427
1476
1428
1477
1429
1478
1430
1479
1431
1480
1432
1481
1433
1482
1434
1483
1435
1484
1436
1485
1437
1486
1438
1487
1439
1488
1440
1489
1441
1490
1442
1491
1443
1492
1444
1493
1445
1494
1446
1495
1447
1496
1448
1497
1449
1498
1499
1451
1500
1452
1501
1453
1502
1454
1503
1455
1504
1456
1505
1457
1506
1458
1507
1459
1508
1460
1509
1461
1510
1462
1511
1463
1512
1464
1513
1465
1514
1466
1515
1467
1516
1468
1517
1469
1518
1470
1519
1471
1520
1472
1521
1473
1522
1474
1523
1475
1524
1476
1525
1477
1526
1478
1527
1479
1528
1480
1529
1481
1530
1482
1531
1483
1532
1484
1533
1485
1534
1486
1535
1487
1536
1488
1537
1489
1538
1490
1539
1491
1540
1492
1541
1493
1542
1494
1543
1495
1544
1496
1545
1497
1546
1498
1547
1499
1548
1549
1501
1550
1502
1551
1503
1552
1504
1553
1505
1554
1506
1555
1507
1556
1508
1557
1509
1558
1510
1559
1511
1560
1512
1561
1513
1562
1514
1563
1515
1564
1516
1565
1517
1566
1518
1567
1519
1568
1520
1569
1521
1570
1522
1571
1523
1572
1524
1573
1525
1574
1526
1575
1527
1576
1528
1577
1529
1578
1530
1579
1531
1580
1532
1581
1533
1582
1534
1583
1535
1584
1536
1585
1537
1586
1538
1587
1539
1588
1540
1589
1541
1590
1542
1591
1543
1592
1544
1593
1545
1594
1546
1595
1547
1596
1548
1597
1549
1598
1599
1551
1600
1552
1601
1553
1602
1554
1603
1555
1604
1556
1605
1557
1606
1558
1607
1559
1608
1560
1609
1561
1610
1562
1611
1563
1612
1564
1613
1565
1614
1566
1615
1567
1616
1568
1617
1569
1618
1570
1619
1571
1620
1572
1621
1573
1622
1574
1623
1575
1624
1576
1625
1577
1626
1578
1627
1579
1628
1580
1629
1581
1630
1582
1631
1583
1632
1584
1633
1585
1634
1586
1635
1587
1636
1588
1637
1589
1638
1590
1639
1591
1640
1592
1641
1593
1642
1594
1643
1595
1644
1596
1645
1597
1646
1598
1647
1599
1648
1649
1601
1650
1602
1651
1603
1652
1604
1653
1605
1654
1606
1655
1607
1656
1608
1657
1609
1658
1610
1659
1611
1660
1612
1661
1613
1662
1614
1663
1615
1664
1616
1665
1617
1666
1618
1667
1619
1668
1620
1669
1621
1670
1622
1671
1623
1672
1624
1673
1625
1674
1626
1675
1627
1676
1628
1677
1629
1678
1630
1679
1631
1680
1632
1681
1633
1682
1634
1683
1635
1684
1636
1685
1637
1686
1638
1687
1639
1688
1640
1689
1641
1690
1642
1691
1643
1692
1644
1693
1645
1694
1646
1695
1647
1696
1648
1697
1649
1698
1699
1651
1700
1652
1701
1653
1702
1654
1703
1655
1704
1656
1705
1657
1706
1658
1707
1659
1708
1660
1709
1661
1710
1662
1711
1663
1712
1664
1713
1665
1714
1666
1715
1667
1716
1668
1717
1669
1718
1670
1719
1671
1720
1672
1721
1673
1722
1674
1723
1675
1724
1676
1725
1677
1726
1678
1727
1679
1728
1680
1729
1681
1730
1682
1731
1683
1732
1684
1733
1685
1734
1686
1735
1687
1736
1688
1737
1689
1738
1690
1739
1691
1740
1692
1741
1693
1742
1694
1743
1695
1744
1696
1745
1697
1746
1698
1747
1699
1748
1749
1701
1750
1702
1751
1703
1752
1704
1753
1705
1754
1706
1755
1707
1756
1708
1757
1709
1758
1710
1759
1711
1760
1712
1761
1713
1762
1714
1763
1715
1764
1716
1765
1717
1766
1718
1767
1719
1768
1720
1769
1721
1770
1722
1771
1723
1772
1724
1773
1725
1774
1726
1775
1727
1776
1728
1777
1729
1778
1730
1779
1731
1780
1732
1781
1733
1782
1734
1783
1735
1784
1736
1785
1737
1786
1738
1787
1739
1788
1740
1789
1741
1790
1742
1791
1743
1792
1744
1793
1745
1794
1746
1795
1747
1796
1748
1797
1749
1798
1799
1751
1800
1752
1801
1753
1802
1754
1803
1755
1804
1756
1805
1757
1806
1758
1807
1759
1808
1760
1809
1761
1810
1762
1811
1763
1812
1764
1813
1765
1814
1766
1815
1767
1816
1768
1817
1769
1818
1770
1819
1771
1820
1772
1821
1773
1822
1774
1823
1775
1824
1776
1825
1777
1826
1778
1827
1779
1828
1780
1829
1781
1830
1782
1831
1783
1832
1784
1833
1785
1834
1786
1835
1787
1836
1788
1837
1789
1838
1790
1839
1791
1840
1792
1841
1793
1842
1794
1843
1795
1844
1796
1845
1797
1846
1798
1847
1799
1848
1849
1801
1850
1802
1851
1803
1852
1804
1853
1805
1854
1806
1855
1807
1856
1808
1857
1809
1858
1810
1859
1811
1860
1812
1861
1813
1862
1814
1863
1815
1864
1816
1865
1817
1866
1818
1867
1819
1868
1820
1869
1821
1870
1822
1871
1823
1872
1824
1873
1825
1874
1826
1875
1827
1876
1828
1877
1829
1878
1830
1879
1831
1880
1832
1881
1833
1882
1834
1883
1835
1884
1836
1885
1837
1886
1838
1887
1839
1888
1840
1889
1841
1890
1842
1891
1843
1892
1844
1893
1845
1894
1846
1895
1847
1896
1848
1897
1849
1898
1899
1851
1900
1852
1901
1853
1902
1854
1903
1855
1904
1856
1905
1857
1906
1858
1907
1859
1908
1860
1909
1861
1910
1862
1911
1863
1912
1864
1913
1865
1914
1866
1915
1867
1916
1868
1917
1869
1918
1870
1919
1871
1920
1872
1921
1873
1922
1874
1923
1875
1924
1876
1925
1877
1926
1878
1927
1879
1928
1880
1929
1881
1930
1882
1931
1883
1932
1884
1933
1885
1934
1886
1935
1887
1936
1888
1937
1889
1938
1890
1939
1891
1940
1892
1941
1893
1942
1894
1943
1895
1944
1896
1945
1897
1946
1898
1947
1899
1948
1949
1901
1950
1902
1951
1903
1952
1904
1953
1905
1954
1906
1955
1907
1956
1908
1957
1909
1958
1910
1959
1911
1960
1912
1961
1913
1962
1914
1963
1915
1964
1916
1965
1917
1966
1918
1967
1919
1968
1920
1969
1921
1970
1922
1971
1923
1972
1924
1973
1925
1974
1926
1975
1927
1976
1928
1977
1929
1978
1930
1979
1931
1980
1932
1981
1933
1982
1934
1983
1935
1984
1936
1985
1937
1986
1938
1987
1939
1988
1940
1989
1941
1990
1942
1991
1943
1992
1944
1993
1945
1994
1946
1995
1947
1996
1948
1997
1949
1998
1999
1951
2000
1952
2001
1953
2002
1954
2003
1955
2004
1956
2005
1957
2006
1958
2007
1959
2008
1960
2009
1961
2010
1962
2011
1963
2012
1964
2013
1965
2014
1966
2015
1967
2016
1968
2017
1969
2018
1970
2019
1971
2020
1972
2021
1973
2022
1974
2023
1975
2024
1976
2025
1977
2026
1978
2027
1979
2028
1980
2029
1981
2030
1982
2031
1983
2032
1984
2033
1985
2034
1986
2035
1987
2036
1988
2037
1989
2038
1990
2039
1991
2040
1992
2041
1993
2042
1994
2043
1995
2044
1996
2045
1997
2046
1998
2047
1999
2048
2049
2001
2050
2002
2051
2003
2052
2004
2053
2005
2054
2006
2055
2007
2056
2008
2057
2009
2058
2010
2059
2011
2060
2012
2061
2013
2062
2014
2063
2015
2064
2016
2065
2017
2066
2018
2067
2019
2068
2020
2069
2021
2070
2022
2071
2023
2072
2024
2073
2025
2074
2026
2075
2027
2076
2028
2077
2029
2078
2030
2079
2031
2080
2032
2081
2033
2082
2034
2083
2035
2084
2036
2085
2037
2086
2038
2087
2039
2088
2040
2089
2041
2090
2042
2091
2043
2092
2044
2093
2045
2094
2046
2095
2047
2096
2048
2097
2049
2098
2099
2051
2100
2052
2101
2053
2102
2054
2103
2055
2104
2056
2105
2057
2106
2058
2107
2059
2108
2060
2109
2061
2110
2062
2111
2063
2112
2064
2113
2065
2114
2066
2115
2067
2116
2068
2117
2069
2118
2070
2119
2071
2120
2072
2121
2073
2122
2074
2123
2075
2124
2076
2125
2077
2126
2078
2127
2079
2128
2080
2129
2081
2130
2082
2131
2083
2132
2084
2133
2085
2134
2086
2135
2087
2136
2088
2137
2089
2138
2090
2139
2091
2140
2092
2141
2093
2142
2094
2143
2095
2144
2096
2145
2097
2146
2098
2147
2099
2148
2149
2101
2150
2102
2151
2103
2152
2104
2153
2105
2154
2106
2155
2107
2156
2108
2157
2109
2158
2110
2159
2111
2160
2112
2161
2113
2162
2114
2163
2115
2164
2116
2165
2117
2166
2118
2167
2119
2168
2120
2169
2121
2170
2122
2171
2123
2172
2124
2173
2125
2174
2126
2175
2127
2176
2128
2177
2129
2178
2130
2179
2131
2180
2132
2181
2133
2182
2134
2183
2135
2184
2136
2185
2137
2186
2138
2187
2139
2188
2140
2189
2141
2190
2142
2191
2143
2192
2144
2193
2145
2194
2146
2195
2147
2196
2148
2197
2149
2198
2199
2151
2200
2152
2201
2153
2202
2154
2203
2155
2204
2156
2205
2157
2206
2158
2207
2159
2208
2160
2209
2161
2210
2162
2211
2163
2212
2164
2213
2165
2214
2166
2215
2167
2216
2168
2217
2169
2218
2170
2219
2171
2220
2172
2221
2173
2222
2174
2223
2175
2224
2176
2225
2177
2226
2178
2227
2179
2228
2180
2229
2181
2230
2182
2231
2183
2232
2184
2233
2185
2234
2186
2235
2187
2236
2188
2237
2189
2238
2190
2239
2191
2240
2192
2241
2193
2242
2194
2243
2195
2244
2196
2245
2197
2246
2198
2247
2199
2248
2249
2201
2250
2202
2251
2203
2252
2204
2253
2205
2254
2206
2255
2207
2256
2208
2257
2209
2258
2210
2259
2211
2260
2212
2261
2213
2262
2214
2263
2215
2264
2216
2265
2217
2266
2218
2267
2219
2268
2220
2269
2221
2270
2222
2271
2223
2272
2224
2273
2225
2274
2226
2275
2227
2276
2228
2277
2229
2278
2230
2279
2231
2280
2232
2281
2233
2282
2234
2283
2235
2284
2236
2285
2237
2286
2238
2287
2239
2288
2240
2289
2241
2290
2242
2291
2243
2292
2244
2293
2245
2294
2246
2295
2247
2296
2248
2297
2249
2298
2299
2251
2300
2252
2301
2253
2302
2254
2303
2255
2304
2256
2305
2257
2306
2258
2307
2259
2308
2260
2309
2261
2310
2262
2311
2263
2312
2264
2313
2265
2314
2266
2315
2267
2316
2268
2317
2269
2318
2270
2319
2271
2320
2272
2321
2273
2322
2274
2323
2275
2324
2276
2325
2277
2326
2278
2327
2279
2328
2280
2329
2281
2330
2282
2331
2283
2332
2284
2333
2285
2334
2286
2335
2287
2336
2288
2337
2289
2338
2290
2339
2291
2340
2292
2341
2293
2342
2294
2343
2295
2344
2296
2345
2297
2346
2298
2347
2299
2348
2349
2301
2350
2302
2351
2303
2352
2304
2353
2305
2354
2306
2355
2307
2356
2308
2357
2309
2358
2310
2359
2311
2360
2312
2361
2313
2362
2314
2363
2315
2364
2316
2365
2317
2366
2318
2367
2319
2368
2320
2369
2321
2370
2322
2371
2323
2372
2324
2373
2325
2374
2326
2375
2327
2376
2328
2377
2329
2378
2330
2379
2331
2380
2332
2381
2333
2382
2334
2383
2335
2384
2336
2385
2337
2386
2338
2387
2339
2388
2340
2389
2341
2390
2342
2391
2343
2392
2344
2393
2345
2394
2346
2395
2347
2396
2348
2397
2349
2398
2399
2351
2400
2352
2401
2353
2402
2354
2403
2355
2404
2356
2405
2357
2406
2358
2407
2359
2408
2360
2409
2361
2410
2362
2411
2363
2412
2364
2413
2365
2414
2366
2415
2367
2416
2368
2417
2369
2418
2370
2419
2371
2420
2372
2421
2373
2422
2374
2423
2375
2424
2376
2425
2377
2426
2378
2427
2379
2428
2380
2429
2381
2430
2382
2431
2383
2432
2384
2433
2385
2434
2386
2435
2387
2436
2388
2437
2389
2438
2390
2439
2391
2440
2392
2441
2393
2442
2394
2443
2395
2444
2396
2445
2397
2446
2398
2447
2399
2448
2449
2401
2450
2402
2451
2403
2452
2404
2453
2405
2454
2406
2455
2407
2456
2408
2457
2409
2458
2410
2459
2411
2460
2412
2461
2413
2462
2414
2463
2415
2464
2416
2465
2417
2466
2418
2467
2419
2468
2420
2469
2421
2470
2422
2471
2423
2472
2424
2473
2425
2474
2426
2475
2427
2476
2428
2477
2429
2478
2430
2479
2431
2480
2432
2481
2433
2482
2434
2483
2435
2484
2436
2485
2437
2486
2438
2487
2439
2488
2440
2489
2441
2490
2442
2491
2443
2492
2444
2493
2445
2494
2446
2495
2447
2496
2448
2497
2449
2498
2499
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
)
// ************************************************************************* //
| [
"andrew.lindsay@westnet.com.au"
] | andrew.lindsay@westnet.com.au | |
2fa84cf512e05602da3e023845d2a676a6334cd0 | 0a37f3dbbd1b7452b149df3999f7a7fe50045143 | /SDL_project/include/Entity.hpp | ac8a7a4a4e44d4c22f71b8c869a0848ab5ed1206 | [] | no_license | Neryss/SDL_2DProject | 6d8ce6c972f1998fad36c5b99451080d7e38de1f | 9c179a70e75d547add1fe27894ce1488c0faef92 | refs/heads/master | 2023-01-05T09:00:55.822338 | 2020-11-02T20:08:05 | 2020-11-02T20:08:05 | 282,535,451 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 462 | hpp | #pragma once
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include "Math.hpp"
class Entity
{
public:
Entity(Vector2f p_pos, SDL_Texture *p_tex);
Vector2f &getPos()
{
return(pos);
}
void playerMove();
void setPos(Vector2f newPos);
void moveEntity(Vector2f velocity);
void pollEvents(SDL_Event &event);
SDL_Texture *getTex();
SDL_Rect getCurrentFrame();
private:
Vector2f pos;
SDL_Rect currentFrame;
SDL_Texture *tex;
}; | [
"kuroysiris@gmail.com"
] | kuroysiris@gmail.com |
b3cc31df787643cba1b08977a6ad29abe294201f | 177c31547ae1ffff1fe4909a22f251d2e7a495cd | /IPOP/backup2/IPOP.h | 3f50dfeaffe453f757ceebbd7d0684d75d60c0aa | [
"MIT"
] | permissive | agalod/ipop | 43f573f8186441e460b6dff1a3b5315a9b59dfff | b14353e7d2af5fd3f80a1bc76efe59f86ab22e00 | refs/heads/master | 2022-11-07T11:05:45.684949 | 2020-06-21T10:24:00 | 2020-06-21T10:24:00 | 273,880,530 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 1,121 | h | // IPOP.h: Schnittstelle für die Klasse CIPOP.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_IPOP_H__DE93C761_5E56_4F24_BEA7_7EF3EBE7ABF0__INCLUDED_)
#define AFX_IPOP_H__DE93C761_5E56_4F24_BEA7_7EF3EBE7ABF0__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "IIPM.h"
class CIPOP: public CIIPM
{
public:
D3DVECTORLINE* GetPiercingPoints();
void Calc_PiercingPoints();
void UpdatePlane();
void Reset();
vector< D3DVECTORLINE >* GetCorrespondingPoints();
vector< D3DVECTOR >* GetPtsObj();
void Calculate_Init();
void Set_Calibration_InitTrafo(D3DMATRIX &Trafo);
void Calculate_OneStep();
CIPOP();
virtual ~CIPOP();
//D3DCAMERA m_Camera;
D3DPLANE m_Plane;
D3DVECTORLINE m_WorkpiecePoints;
//D3DPLANE m_Plane;
//D3DMATRIX m_Init_Transformation;
//vector< D3DVECTOR, D3DVECTOR& > m_Pts_Obj, m_Pts_Img;
//vector < CPoint, CPoint& > *m_pCalibration_ObjectPoints,
// *m_pCalibration_ImagePoints;
};
#endif // !defined(AFX_IPOP_H__DE93C761_5E56_4F24_BEA7_7EF3EBE7ABF0__INCLUDED_)
| [
"aroehnisch@info-tech.biz"
] | aroehnisch@info-tech.biz |
a0464518131a3403599fdaeea9fc6f30529d1971 | 2c95379f5e0fbb929647c498e02d5d359295ed50 | /MainFormatNumberTest.cpp | 292faf442788a9d93e4514078458c46824b58fa5 | [] | no_license | Fruitseller/FormatNumber | 6d3f7bb6fa0c4f547d6f6d2d3e0d1e8b4b82d80c | 40f750ca4554f3060b0bdcf8eda72ae3cdd6ed87 | refs/heads/master | 2021-01-10T20:49:33.294668 | 2014-01-23T11:17:46 | 2014-01-23T11:17:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 693 | cpp | /*
* MainFormatNumberTest.cpp
*
* Created on: 20.11.2012
* Author: bronkalla
*/
#include <cppunit/CompilerOutputter.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/ui/text/TextTestRunner.h>
int main(int argc, char* argv[])
{
/* Test-Runner erzeugen */
CppUnit::TextTestRunner runner;
/* TestSuite erzeugen */
CppUnit::Test *suite = CppUnit::TestFactoryRegistry::getRegistry().makeTest();
runner.addTest( suite );
/* Outputformatierung festlegen */
runner.setOutputter( new CppUnit::CompilerOutputter( &runner.result(), std::cerr ) );
/* Tests durchführen
** und 0 oder im Fehlerfall 1 zurückmelden */
return runner.run() ? 0 : 1;
}
| [
"bronkalla@sipgate.de"
] | bronkalla@sipgate.de |
a4680e547065e37272d1c769c0f4a142fd9c395e | 2fb6e3860be751132d26502325a0c4559a794217 | /cpac/chef/maxand18.cpp | fdb6ef43d320deaf8eab84c6faceb3665cd46ed3 | [
"MIT"
] | permissive | 00mjk/Allcodes_codeWar | 8af56bf4c74cbdef577fc34d991d6ec88d24c67f | 0dfc3367ecc1df58f502f20ff3d732c49c62f140 | refs/heads/master | 2023-04-18T11:23:41.844829 | 2021-05-09T13:32:40 | 2021-05-09T13:32:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 647 | cpp | #include<bits/stdc++.h>
using namespace std;
#define abhinav ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr);
#define endl "\n"
#define ll long long int
ll bitcount(ll n){
ll count = 0;
while (n > 0){
count += 1;
n = n & (n-1);
}
return count;
}
void solve(){
ll n,k,b=0,max=0;
cin>>n>>k;
ll a[n];
for(ll i=0;i<n;i++){
cin>>a[i];
}
sort(a,a+n);
for(ll i=a[0];i<a[n-1];i++){
if(bitcount(i)==k){
for(ll j=0;j<n;j++){
b+=i&a[j];
}
if(b>max)
max=i;
b=0;
}
}
cout<<max<<endl;
}
int main()
{
abhinav;
int t;
cin>>t;
while(t--)
{
solve();
}
return 0;
} | [
"abhinav.022000@gmail.com"
] | abhinav.022000@gmail.com |
4d9919b578496a2def00e5d6f832e7507ca52e5e | fed63676a76f3bfa8e5f1d57099cfc52024f93b2 | /core/unit_test/cilkplus/TestCilkPlus_Atomics.cpp | 7e759464b3c646e11f0a39ff48ff5c5a046bbae5 | [] | no_license | jeffmiles63/kokkos-cilk-plugin | e23e5820466f48c150ad546c24568714bf87fb57 | 3b61f6554168df505fea356e8e2631e72d72f879 | refs/heads/master | 2022-11-26T02:35:18.112140 | 2020-07-20T22:36:11 | 2020-07-20T22:36:11 | 256,516,693 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,038 | cpp | /*
//@HEADER
// ************************************************************************
//
// Kokkos v. 2.0
// Copyright (2014) Sandia Corporation
//
// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
// the U.S. Government retains certain rights in this software.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the Corporation nor the names of the
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "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 SANDIA CORPORATION OR THE
// 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.
//
// Questions? Contact H. Carter Edwards (hcedwar@sandia.gov)
//
// ************************************************************************
//@HEADER
*/
#include <cilkplus/TestCilkPlus_Category.hpp>
#include <TestAtomic.hpp>
| [
"jsmiles@apollo.sandia.gov"
] | jsmiles@apollo.sandia.gov |
4dc89a2ccf568d00bccd72acae7291e99a90c930 | dc2ecd3900a942c7495ff03091d1e06a2d1601cd | /main.cxx | 197fc77196f5c989f6cbe7bf2cf5f16d0c28eb86 | [
"BSD-2-Clause"
] | permissive | yanorei32/openvr2ctl | c1ec3cfaa440446e2c1b15d98070e0fa1c1b2a0d | c72085bbb56bbcdbbce510254faa8de3eec174a8 | refs/heads/main | 2022-12-29T09:47:10.861500 | 2020-10-21T16:05:35 | 2020-10-21T16:05:35 | 305,509,244 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,553 | cxx | #include <algorithm>
#include <chrono>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <filesystem>
#include <iostream>
#include <numbers>
#include <string>
#include <thread>
#ifdef _MSC_BUILD
#include <fcntl.h>
#include <io.h>
#endif
#ifdef __CYGWIN__
#include <windows.h>
#endif
#include "openvr.h"
struct Vector2f_t {
float x, y;
};
Vector2f_t getVector2ActionState(
vr::VRActionHandle_t action
) {
Vector2f_t v = {0};
vr::InputAnalogActionData_t actionData;
vr::VRInput()->GetAnalogActionData(
action,
&actionData,
sizeof(actionData),
vr::k_ulInvalidInputValueHandle
);
if (actionData.bActive) {
v.x = actionData.x;
v.y = actionData.y;
}
return v;
}
float getVector1ActionState(
vr::VRActionHandle_t action
) {
vr::InputAnalogActionData_t actionData;
vr::VRInput()->GetAnalogActionData(
action,
&actionData,
sizeof(actionData),
vr::k_ulInvalidInputValueHandle
);
return actionData.bActive ? actionData.x : 0.0f;
}
bool getDigitalActionState(
vr::VRActionHandle_t action
) {
vr::InputDigitalActionData_t actionData;
vr::VRInput()->GetDigitalActionData(
action,
&actionData,
sizeof(actionData),
vr::k_ulInvalidInputValueHandle
);
return actionData.bActive && actionData.bState;
}
bool getDigitalActionRisingEdge(
vr::VRActionHandle_t action
) {
vr::InputDigitalActionData_t actionData;
vr::VRInput()->GetDigitalActionData(
action,
&actionData,
sizeof(actionData),
vr::k_ulInvalidInputValueHandle
);
return actionData.bActive && actionData.bChanged && actionData.bState;
}
float rad2deg(float rad) {
return rad * 180 / std::numbers::pi;
}
int main(int, char**) {
#ifdef _MSC_BUILD
setmode(fileno(stdout), O_BINARY);
#endif
std::cerr << "VR Application Overlay initialization" << std::endl;
vr::EVRInitError error = vr::VRInitError_None;
vr::VR_Init(&error, vr::VRApplication_Overlay);
if (error != vr::VRInitError_None) {
std::cerr << __LINE__ << ": ";
std::cerr << "error " << vr::VR_GetVRInitErrorAsSymbol(error) << std::endl;
return error;
}
std::cerr << "Action set initialization" << std::endl;
vr::VRActionSetHandle_t defaultSetHandle = vr::k_ulInvalidActionSetHandle;
vr::VRActionHandle_t defaultToggleControl = vr::k_ulInvalidActionHandle;
vr::VRActionSetHandle_t controlSetHandle = vr::k_ulInvalidActionSetHandle;
vr::VRActionHandle_t controlSnapTurnLeft = vr::k_ulInvalidActionHandle;
vr::VRActionHandle_t controlSnapTurnRight = vr::k_ulInvalidActionHandle;
vr::VRActionHandle_t controlSpeedVector1 = vr::k_ulInvalidActionHandle;
vr::VRActionHandle_t controlSpeedVector2 = vr::k_ulInvalidActionHandle;
vr::VRActionHandle_t controlDirection = vr::k_ulInvalidActionHandle;
auto actionsPathCptr = (std::filesystem::current_path() / "actions.json").string().c_str();
#ifdef __CYGWIN__
char winpath[MAX_PATH];
GetModuleFileName(NULL, winpath, MAX_PATH);
std::strcpy(std::strrchr(winpath, '\\') + 1, "actions.json");
actionsPathCptr = winpath;
#endif
vr::VRInput()->SetActionManifestPath(
actionsPathCptr
);
vr::VRInput()->GetActionSetHandle(
"/actions/default",
&defaultSetHandle
);
vr::VRInput()->GetActionHandle(
"/actions/default/in/ToggleControl",
&defaultToggleControl
);
vr::VRInput()->GetActionSetHandle(
"/actions/control",
&controlSetHandle
);
vr::VRInput()->GetActionHandle(
"/actions/control/in/SnapTurnLeft",
&controlSnapTurnLeft
);
vr::VRInput()->GetActionHandle(
"/actions/control/in/SnapTurnRight",
&controlSnapTurnRight
);
vr::VRInput()->GetActionHandle(
"/actions/control/in/SpeedVector1",
&controlSpeedVector1
);
vr::VRInput()->GetActionHandle(
"/actions/control/in/SpeedVector2",
&controlSpeedVector2
);
vr::VRInput()->GetActionHandle(
"/actions/control/in/Direction",
&controlDirection
);
vr::VRActiveActionSet_t sets[2] = { 0 };
sets[0].ulActionSet = defaultSetHandle;
sets[1].ulActionSet = controlSetHandle;
sets[1].nPriority = 0x01FFFFFF;
std::cerr << "Enter to main loop" << std::endl;
bool inControl = true;
float oldSpeed = NAN, oldDirection = NAN;
while (1) {
std::this_thread::sleep_for(std::chrono::milliseconds(1000 / 100));
if (!inControl) {
vr::VRInput()->UpdateActionState(&sets[0], sizeof(sets[0]), 1);
if (getDigitalActionRisingEdge(defaultToggleControl)) {
std::cerr << "Activate State: Control" << std::endl;
inControl = true;
}
continue;
}
vr::VRInput()->UpdateActionState(&sets[0], sizeof(sets[0]), 2);
if (getDigitalActionRisingEdge(defaultToggleControl)) {
std::cerr << "Activate State: Default" << std::endl;
inControl = false;
continue;
}
auto speedVec1 = getVector1ActionState(controlSpeedVector1);
auto speedVec2Raw = getVector2ActionState(controlSpeedVector2);
auto speedVec2 = std::min(
std::hypotf(speedVec2Raw.x, speedVec2Raw.y),
1.0f
);
auto speed = std::max(speedVec1, speedVec2);
auto directionRaw = getVector2ActionState(controlDirection);
auto direction = rad2deg(
-std::atan2(-directionRaw.x, directionRaw.y)
);
#ifdef DEBUG
if (speed != oldSpeed || oldDirection != direction) {
#else
if (1) {
#endif
std::cout << "move " << speed << " " << direction << std::endl;
}
oldSpeed = speed;
oldDirection = direction;
if (speed == 0.0f && getDigitalActionRisingEdge(controlSnapTurnLeft)) {
std::cout << "snapturn left" << std::endl;
}
if (speed == 0.0f && getDigitalActionRisingEdge(controlSnapTurnRight)) {
std::cout << "snapturn right" << std::endl;
}
}
return 0;
}
| [
"yanorei@hotmail.co.jp"
] | yanorei@hotmail.co.jp |
b5b3eb3a1f6a4d0af1a4946450d3d2b63619e366 | 6b2985d7ea8b289badbeade95efe45f02409cf1b | /wlbh.cpp | 9ae7bb844d06d2ec8d1809803f676debbd1c02a5 | [] | no_license | feengg/SanTang | e92a3f7cca8766fe047739501d558bab3c326087 | 83577a464b251c96f26f75e13e7a557aa477a0ed | refs/heads/master | 2021-05-18T00:18:29.374704 | 2020-05-03T15:02:10 | 2020-05-03T15:02:10 | 251,019,653 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,710 | cpp | #include "wlbh.h"
#include "ui_wlbh.h"
#include "wlbh_sub.h"
#include "widget.h"
Wlbh::Wlbh(QWidget *parent) :
QWidget(parent),
ui(new Ui::Wlbh)
{
ui->setupUi(this);
this->setWindowFlags(Qt::FramelessWindowHint);
QPalette palette;
palette.setBrush(QPalette::Background,QBrush(QPixmap(":./images/采购申请背景图.png").scaled(this->size(),Qt::IgnoreAspectRatio)));
this->setPalette(palette);
this->setWindowTitle("物料编号");
flushTableSlot();
}
Wlbh::~Wlbh()
{
delete ui;
}
//下面三个函数实现没有边框的窗体鼠标移动功能
void Wlbh::mousePressEvent(QMouseEvent *event)
{
if(event->button() == Qt::LeftButton)
{
position = event->globalPos() - this->pos();
setCursor(Qt::ClosedHandCursor);
event->accept();
dragWindow = true;
}
}
void Wlbh::mouseReleaseEvent(QMouseEvent *)
{
dragWindow = false;
setCursor(Qt::ArrowCursor);
}
void Wlbh::mouseMoveEvent(QMouseEvent *event)
{
if(dragWindow && (event->buttons() && Qt::LeftButton))
{
this->move(event->globalPos() - position);
event->accept();
}
}
void Wlbh::on_pushButton_new_clicked()
{
Wlbh_sub * wlbh_sub = new Wlbh_sub;
connect(wlbh_sub,SIGNAL(emitFlushWlbhTableSig()),this,SLOT(flushTableSlot()));
wlbh_sub->show();
}
void Wlbh::on_pushButton_ok_clicked()
{
this->close();
}
void Wlbh::on_toolButton_clicked()
{
this->close();
}
void Wlbh::flushTableSlot()
{
ui->tableWidget->clear();
ui->tableWidget->setColumnCount(6);
QStringList header;
header << "物料编码" << "物料名称" << "规格型号/封装" << "厂家"<<"申请人"<<"申请日期";
ui->tableWidget->setHorizontalHeaderLabels(header);
ui->tableWidget->horizontalHeader()->setStretchLastSection(true);
if(!QSqlDatabase::database().isValid())
{
Widget::openMySql();
}
QSqlQuery query;
if(query.exec(tr("select * from wlbhMsg order by dealTime desc")))
{
ui->tableWidget->setRowCount(query.size());
for(int i = 0; i < query.size();i ++)
{
query.next();
QTableWidgetItem * item0 = new QTableWidgetItem(query.value(3).toString());
QTableWidgetItem * item1 = new QTableWidgetItem(query.value(4).toString());
QTableWidgetItem * item2 = new QTableWidgetItem(query.value(5).toString());
QTableWidgetItem * item3 = new QTableWidgetItem(query.value(6).toString());
QTableWidgetItem * item4 = new QTableWidgetItem(query.value(1).toString());
QTableWidgetItem * item5 = new QTableWidgetItem(query.value(0).toString());
item0->setTextAlignment(Qt::AlignCenter);
item1->setTextAlignment(Qt::AlignCenter);
item2->setTextAlignment(Qt::AlignCenter);
item3->setTextAlignment(Qt::AlignCenter);
item4->setTextAlignment(Qt::AlignCenter);
item5->setTextAlignment(Qt::AlignCenter);
ui->tableWidget->setItem(i,0,item0);
ui->tableWidget->setItem(i,1,item1);
ui->tableWidget->setItem(i,2,item2);
ui->tableWidget->setItem(i,3,item3);
ui->tableWidget->setItem(i,4,item4);
ui->tableWidget->setItem(i,5,item5);
}
}
}
//显示搜索结果到table
void Wlbh::showSearchResultToTable()
{
ui->tableWidget->clear();
ui->tableWidget->setColumnCount(6);
QStringList header;
header << "物料编码" << "物料名称" << "规格型号/封装" << "厂家"<<"申请人"<<"申请日期";
ui->tableWidget->setHorizontalHeaderLabels(header);
ui->tableWidget->horizontalHeader()->setStretchLastSection(true);
if(!QSqlDatabase::database().isValid())
{
Widget::openMySql();
}
QSqlQuery query;
if(query.exec(tr("select * from wlbhMsg where wlNum like '%%1%' and wlName like '%%2%' and wlFormat like '%%3%' order by dealTime desc")
.arg(ui->lineEdit_wlNum->text().trimmed()).arg(ui->lineEdit_wlName->text().trimmed()).arg(ui->lineEdit_format->text().trimmed())))
{
ui->tableWidget->setRowCount(query.size());
for(int i = 0; i < query.size();i ++)
{
query.next();
QTableWidgetItem * item0 = new QTableWidgetItem(query.value(3).toString());
QTableWidgetItem * item1 = new QTableWidgetItem(query.value(4).toString());
QTableWidgetItem * item2 = new QTableWidgetItem(query.value(5).toString());
QTableWidgetItem * item3 = new QTableWidgetItem(query.value(6).toString());
QTableWidgetItem * item4 = new QTableWidgetItem(query.value(1).toString());
QTableWidgetItem * item5 = new QTableWidgetItem(query.value(0).toString());
item0->setTextAlignment(Qt::AlignCenter);
item1->setTextAlignment(Qt::AlignCenter);
item2->setTextAlignment(Qt::AlignCenter);
item3->setTextAlignment(Qt::AlignCenter);
item4->setTextAlignment(Qt::AlignCenter);
item5->setTextAlignment(Qt::AlignCenter);
ui->tableWidget->setItem(i,0,item0);
ui->tableWidget->setItem(i,1,item1);
ui->tableWidget->setItem(i,2,item2);
ui->tableWidget->setItem(i,3,item3);
ui->tableWidget->setItem(i,4,item4);
ui->tableWidget->setItem(i,5,item5);
}
}
}
void Wlbh::on_lineEdit_wlNum_textChanged(const QString &arg1)
{
showSearchResultToTable();
}
void Wlbh::on_lineEdit_wlName_textChanged(const QString &arg1)
{
showSearchResultToTable();
}
void Wlbh::on_lineEdit_format_textChanged(const QString &arg1)
{
showSearchResultToTable();
}
| [
"feengg@163.com"
] | feengg@163.com |
d5b253d394cae9075c8161bf0b5732c6ad1d1834 | 8567438779e6af0754620a25d379c348e4cd5a5d | /chrome/browser/chromeos/app_mode/kiosk_app_manager.h | f057d111d0186b77814c77a4f0bc0c8e6ed735f4 | [
"BSD-3-Clause"
] | permissive | thngkaiyuan/chromium | c389ac4b50ccba28ee077cbf6115c41b547955ae | dab56a4a71f87f64ecc0044e97b4a8f247787a68 | refs/heads/master | 2022-11-10T02:50:29.326119 | 2017-04-08T12:28:57 | 2017-04-08T12:28:57 | 84,073,924 | 0 | 1 | BSD-3-Clause | 2022-10-25T19:47:15 | 2017-03-06T13:04:15 | null | UTF-8 | C++ | false | false | 13,330 | h | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_CHROMEOS_APP_MODE_KIOSK_APP_MANAGER_H_
#define CHROME_BROWSER_CHROMEOS_APP_MODE_KIOSK_APP_MANAGER_H_
#include <map>
#include <memory>
#include <string>
#include <vector>
#include "base/callback_forward.h"
#include "base/lazy_instance.h"
#include "base/macros.h"
#include "base/observer_list.h"
#include "base/time/time.h"
#include "chrome/browser/chromeos/app_mode/kiosk_app_data_delegate.h"
#include "chrome/browser/chromeos/extensions/external_cache.h"
#include "chrome/browser/chromeos/settings/cros_settings.h"
#include "chrome/browser/chromeos/settings/install_attributes.h"
#include "components/signin/core/account_id/account_id.h"
#include "ui/gfx/image/image_skia.h"
class GURL;
class PrefRegistrySimple;
class Profile;
namespace base {
class CommandLine;
}
namespace extensions {
class Extension;
class ExternalLoader;
}
namespace chromeos {
class AppSession;
class KioskAppData;
class KioskAppExternalLoader;
class KioskAppManagerObserver;
class KioskExternalUpdater;
class OwnerSettingsServiceChromeOS;
// KioskAppManager manages cached app data.
class KioskAppManager : public KioskAppDataDelegate,
public ExternalCache::Delegate {
public:
enum ConsumerKioskAutoLaunchStatus {
// Consumer kiosk mode auto-launch feature can be enabled on this machine.
CONSUMER_KIOSK_AUTO_LAUNCH_CONFIGURABLE,
// Consumer kiosk auto-launch feature is enabled on this machine.
CONSUMER_KIOSK_AUTO_LAUNCH_ENABLED,
// Consumer kiosk mode auto-launch feature is disabled and cannot any longer
// be enabled on this machine.
CONSUMER_KIOSK_AUTO_LAUNCH_DISABLED,
};
typedef base::Callback<void(bool success)> EnableKioskAutoLaunchCallback;
typedef base::Callback<void(ConsumerKioskAutoLaunchStatus status)>
GetConsumerKioskAutoLaunchStatusCallback;
// Struct to hold app info returned from GetApps() call.
struct App {
App(const KioskAppData& data,
bool is_extension_pending,
bool was_auto_launched_with_zero_delay);
App();
App(const App& other);
~App();
std::string app_id;
AccountId account_id;
std::string name;
gfx::ImageSkia icon;
std::string required_platform_version;
bool is_loading;
bool was_auto_launched_with_zero_delay;
};
typedef std::vector<App> Apps;
// Name of a dictionary that holds kiosk app info in Local State.
// Sample layout:
// "kiosk": {
// "auto_login_enabled": true //
// }
static const char kKioskDictionaryName[];
static const char kKeyApps[];
static const char kKeyAutoLoginState[];
// Sub directory under DIR_USER_DATA to store cached icon files.
static const char kIconCacheDir[];
// Sub directory under DIR_USER_DATA to store cached crx files.
static const char kCrxCacheDir[];
// Sub directory under DIR_USER_DATA to store unpacked crx file for validating
// its signature.
static const char kCrxUnpackDir[];
// Gets the KioskAppManager instance, which is lazily created on first call..
static KioskAppManager* Get();
// Prepares for shutdown and calls CleanUp() if needed.
static void Shutdown();
// Registers kiosk app entries in local state.
static void RegisterPrefs(PrefRegistrySimple* registry);
// Removes cryptohomes which could not be removed during the previous session.
static void RemoveObsoleteCryptohomes();
static bool IsConsumerKioskEnabled();
// Initiates reading of consumer kiosk mode auto-launch status.
void GetConsumerKioskAutoLaunchStatus(
const GetConsumerKioskAutoLaunchStatusCallback& callback);
// Enables consumer kiosk mode app auto-launch feature. Upon completion,
// |callback| will be invoked with outcome of this operation.
void EnableConsumerKioskAutoLaunch(
const EnableKioskAutoLaunchCallback& callback);
// Returns true if this device is consumer kiosk auto launch enabled.
bool IsConsumerKioskDeviceWithAutoLaunch();
// Returns auto launcher app id or an empty string if there is none.
std::string GetAutoLaunchApp() const;
// Sets |app_id| as the app to auto launch at start up.
void SetAutoLaunchApp(const std::string& app_id,
OwnerSettingsServiceChromeOS* service);
// Returns true if there is a pending auto-launch request.
bool IsAutoLaunchRequested() const;
// Returns true if owner/policy enabled auto launch.
bool IsAutoLaunchEnabled() const;
// Enable auto launch setter.
void SetEnableAutoLaunch(bool value);
// Returns the cached required platform version of the auto launch with
// zero delay kiosk app.
std::string GetAutoLaunchAppRequiredPlatformVersion() const;
// Adds/removes a kiosk app by id. When removed, all locally cached data
// will be removed as well.
void AddApp(const std::string& app_id, OwnerSettingsServiceChromeOS* service);
void RemoveApp(const std::string& app_id,
OwnerSettingsServiceChromeOS* service);
// Gets info of all apps that have no meta data load error.
void GetApps(Apps* apps) const;
// Gets app data for the given app id. Returns true if |app_id| is known and
// |app| is populated. Otherwise, return false.
bool GetApp(const std::string& app_id, App* app) const;
// Gets whether the bailout shortcut is disabled.
bool GetDisableBailoutShortcut() const;
// Clears locally cached app data.
void ClearAppData(const std::string& app_id);
// Updates app data from the |app| in |profile|. |app| is provided to cover
// the case of app update case where |app| is the new version and is not
// finished installing (e.g. because old version is still running). Otherwise,
// |app| could be NULL and the current installed app in |profile| will be
// used.
void UpdateAppDataFromProfile(const std::string& app_id,
Profile* profile,
const extensions::Extension* app);
void RetryFailedAppDataFetch();
// Returns true if the app is found in cache.
bool HasCachedCrx(const std::string& app_id) const;
// Gets the path and version of the cached crx with |app_id|.
// Returns true if the app is found in cache.
bool GetCachedCrx(const std::string& app_id,
base::FilePath* file_path,
std::string* version) const;
void AddObserver(KioskAppManagerObserver* observer);
void RemoveObserver(KioskAppManagerObserver* observer);
// Creates extensions::ExternalLoader for installing the primary kiosk app
// during its first time launch.
extensions::ExternalLoader* CreateExternalLoader();
// Creates extensions::ExternalLoader for installing secondary kiosk apps
// before launching the primary app for the first time.
extensions::ExternalLoader* CreateSecondaryAppExternalLoader();
// Installs kiosk app with |id| from cache.
void InstallFromCache(const std::string& id);
// Installs the secondary apps listed in |ids|.
void InstallSecondaryApps(const std::vector<std::string>& ids);
void UpdateExternalCache();
// Monitors kiosk external update from usb stick.
void MonitorKioskExternalUpdate();
// Invoked when kiosk app cache has been updated.
void OnKioskAppCacheUpdated(const std::string& app_id);
// Invoked when kiosk app updating from usb stick has been completed.
// |success| indicates if all the updates are completed successfully.
void OnKioskAppExternalUpdateComplete(bool success);
// Installs the validated external extension into cache.
void PutValidatedExternalExtension(
const std::string& app_id,
const base::FilePath& crx_path,
const std::string& version,
const ExternalCache::PutExternalExtensionCallback& callback);
// Whether the current platform is compliant with the given required
// platform version.
bool IsPlatformCompliant(const std::string& required_platform_version) const;
// Whether the platform is compliant for the given app.
bool IsPlatformCompliantWithApp(const extensions::Extension* app) const;
// Notifies the KioskAppManager that a given app was auto-launched
// automatically with no delay on startup. Certain privacy-sensitive
// kiosk-mode behavior (such as network reporting) is only enabled for
// kiosk apps that are immediately auto-launched on startup.
void SetAppWasAutoLaunchedWithZeroDelay(const std::string& app_id);
// Initialize |app_session_|.
void InitSession(Profile* profile, const std::string& app_id);
// Adds an app with the given meta data directly and skips meta data fetching
// for test.
void AddAppForTest(const std::string& app_id,
const AccountId& account_id,
const GURL& update_url,
const std::string& required_platform_version);
AppSession* app_session() { return app_session_.get(); }
bool external_loader_created() const { return external_loader_created_; }
bool secondary_app_external_loader_created() const {
return secondary_app_external_loader_created_;
}
private:
friend struct base::DefaultLazyInstanceTraits<KioskAppManager>;
friend std::default_delete<KioskAppManager>;
friend class KioskAppManagerTest;
friend class KioskTest;
friend class KioskUpdateTest;
enum AutoLoginState {
AUTOLOGIN_NONE = 0,
AUTOLOGIN_REQUESTED = 1,
AUTOLOGIN_APPROVED = 2,
AUTOLOGIN_REJECTED = 3,
};
KioskAppManager();
~KioskAppManager() override;
// Stop all data loading and remove its dependency on CrosSettings.
void CleanUp();
// Gets KioskAppData for the given app id.
const KioskAppData* GetAppData(const std::string& app_id) const;
KioskAppData* GetAppDataMutable(const std::string& app_id);
// Updates app data |apps_| based on CrosSettings.
void UpdateAppData();
// Clear cached data and crx of the removed apps.
void ClearRemovedApps(
const std::map<std::string, std::unique_ptr<KioskAppData>>& old_apps);
// Updates the prefs of |external_cache_| from |apps_|.
void UpdateExternalCachePrefs();
// KioskAppDataDelegate overrides:
void GetKioskAppIconCacheDir(base::FilePath* cache_dir) override;
void OnKioskAppDataChanged(const std::string& app_id) override;
void OnKioskAppDataLoadFailure(const std::string& app_id) override;
// ExternalCache::Delegate:
void OnExtensionListsUpdated(const base::DictionaryValue* prefs) override;
void OnExtensionLoadedInCache(const std::string& id) override;
void OnExtensionDownloadFailed(
const std::string& id,
extensions::ExtensionDownloaderDelegate::Error error) override;
// Callback for InstallAttributes::LockDevice() during
// EnableConsumerModeKiosk() call.
void OnLockDevice(const EnableKioskAutoLaunchCallback& callback,
InstallAttributes::LockResult result);
// Callback for InstallAttributes::ReadImmutableAttributes() during
// GetConsumerKioskModeStatus() call.
void OnReadImmutableAttributes(
const GetConsumerKioskAutoLaunchStatusCallback& callback);
// Callback for reading handling checks of the owner public.
void OnOwnerFileChecked(
const GetConsumerKioskAutoLaunchStatusCallback& callback,
bool* owner_present);
// Reads/writes auto login state from/to local state.
AutoLoginState GetAutoLoginState() const;
void SetAutoLoginState(AutoLoginState state);
void GetCrxCacheDir(base::FilePath* cache_dir);
void GetCrxUnpackDir(base::FilePath* unpack_dir);
// Returns the auto launch delay.
base::TimeDelta GetAutoLaunchDelay() const;
// Gets list of user switches that should be passed to Chrome in case current
// session has to be restored, e.g. in case of a crash. The switches will be
// returned as |switches| command line arguments.
// Returns whether the set of switches would have to be changed in respect to
// the current set of switches - if that is not the case |switches| might not
// get populated.
bool GetSwitchesForSessionRestore(const std::string& app_id,
base::CommandLine* switches);
// True if machine ownership is already established.
bool ownership_established_;
std::vector<std::unique_ptr<KioskAppData>> apps_;
std::string auto_launch_app_id_;
std::string currently_auto_launched_with_zero_delay_app_;
base::ObserverList<KioskAppManagerObserver, true> observers_;
std::unique_ptr<CrosSettings::ObserverSubscription>
local_accounts_subscription_;
std::unique_ptr<CrosSettings::ObserverSubscription>
local_account_auto_login_id_subscription_;
std::unique_ptr<ExternalCache> external_cache_;
std::unique_ptr<KioskExternalUpdater> usb_stick_updater_;
// The extension external loader for deploying primary app.
bool external_loader_created_;
base::WeakPtr<KioskAppExternalLoader> external_loader_;
// The extension external loader for deploying secondary apps.
bool secondary_app_external_loader_created_;
base::WeakPtr<KioskAppExternalLoader> secondary_app_external_loader_;
std::unique_ptr<AppSession> app_session_;
DISALLOW_COPY_AND_ASSIGN(KioskAppManager);
};
} // namespace chromeos
#endif // CHROME_BROWSER_CHROMEOS_APP_MODE_KIOSK_APP_MANAGER_H_
| [
"hedonist.ky@gmail.com"
] | hedonist.ky@gmail.com |
d54375baa529907ef93b90baf6b2cb405f4428ec | 9c0bcf19c1d1a4eb7ecc053006a877889c24b5b2 | /算法时空/树/leetcode-101 对称二叉树/main.cpp | dc02d881fc1c90b0001e4d95b8f10bb81ea9d188 | [
"Apache-2.0"
] | permissive | summerHearts/AlgorithmPro | 027fb8be6086fd16cd24f2552427e7220a071219 | 089ac889708e31ec89267cbe11721f6b1d6704c5 | refs/heads/master | 2021-06-15T05:12:39.230448 | 2021-04-14T15:07:49 | 2021-04-14T15:07:49 | 176,458,045 | 9 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,062 | cpp | //
// main.cpp
// leetcode-101 对称二叉树
//
// Created by 佐毅 on 2020/2/1.
// Copyright © 2020 dfjr. All rights reserved.
//
/**
### 题目描述
给定一个二叉树,检查它是否是镜像对称的。
例如,二叉树 `[1,2,2,3,4,4,3]` 是对称的。
1
/ \
2 2
/ \ / \
3 4 4 3
*/
/**
### 题目解析
用递归做比较简单:一棵树是对称的**等价**于它的左子树和右子树两棵树是对称的,问题就转变为判断两棵树是否对称。
解题思路:
若一个二叉树root是镜像对称的,则与克隆体rootcopy有:
根节点相同
root每个右子树与rootcopy左子树镜像对称
root每个左子树与rootcopy右子树镜像对称
*/
#include <iostream>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
bool isSymmetric(TreeNode* root) {
return ismirror(root,root);
}
bool ismirror(TreeNode* t1,TreeNode* t2){
if(t1==NULL&&t2==NULL)//都为空
return true;
if(t1==NULL||t2==NULL)//有一个为空
return false;
return (t1->val==t2->val)&&ismirror(t1->left,t2->right)&&ismirror(t1->right,t2->left);
}
};
int main(int argc, const char * argv[]) {
// 给定二叉树: [3,9,20,null,null,15,7],
TreeNode *headNodel = new TreeNode(3);
TreeNode *node2 = new TreeNode(9);
TreeNode *node3 = new TreeNode(20);
TreeNode *node4 = new TreeNode(15);
TreeNode *node5 = new TreeNode(7);
node2->left = nullptr;
node2->right = nullptr;
node4->left = nullptr;
node4->right = nullptr;
node5->left = nullptr;
node5->right = nullptr;
headNodel->left = node2;
headNodel->right = node3;
node3->left = node4;
node3->right = node5;
Solution solution;
cout << "该树是对成二叉树: " << endl ;
cout << solution.isSymmetric(headNodel) << endl;
return 0;
}
| [
"yaoyajie@enmonster.com"
] | yaoyajie@enmonster.com |
9eab021bd97ef4a37dc8be28473e8fe3d8e30e5d | a6993ebbb0d58312c50316065c6f86c4fd72e878 | /src/alg/CurveGenerator.cpp | e2f2169985ea0773a479a2827aabc7d5b0a5a40e | [] | no_license | SZSilence06/curve-design | dbc194c8da411e2d506334757f6b7ecea412b5c7 | 396caebf9fdfa9fb3aaa6b507b16f9e82b5ae986 | refs/heads/master | 2021-01-11T09:42:36.951541 | 2017-05-02T10:19:27 | 2017-05-02T10:19:27 | 77,582,631 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 30,771 | cpp | #include "CurveGenerator.h"
#include "GeodesicGenerator.h"
#include "../globals/geometry.h"
CurveGenerator::CurveGenerator(Mesh &mesh) : mesh(mesh)
{
auto& halfEdgeMesh = mesh.getHalfEdgeMesh();
for(auto vert = halfEdgeMesh.verts().begin(); vert != halfEdgeMesh.verts().end(); ++vert)
{
std::vector<size_t> result;
auto edge = vert->edge();
do{
result.push_back(edge->oppo()->vert()->id_);
edge = edge->next()->oppo();
}while(edge != vert->edge());
vertex_neighbours.push_back(result);
}
}
bool CurveGenerator::computeCurve(std::vector<size_t> &control_points, bool is_loop, double t,
double error_percentage, matrixr_t &outCurve)
{
this->t = t;
this->error_percentage = error_percentage;
if(initialize(control_points, is_loop) == false)
{
return false;
}
int i = 0;
while (true)
{
i++;
smooth();
if(isFinished() || i >= 100)
{
std::cout << "Finished smoothing after " << i << " iterations." << std::endl;
break;
}
handleCriticalVertices();
}
outCurve = matrixr_t(3, curve.size());
for(int i = 0; i < curve.size(); i++)
{
outCurve(colon(), i) = getCoordinate(curve[i]);
}
return true;
}
bool CurveGenerator::initialize(std::vector<size_t> &control_points, bool is_loop)
{
GeodesicGenerator generator(mesh);
std::vector<int> geodesic;
if(generator.generateGeodesic(control_points, is_loop, geodesic) == false)
{
return false;
}
curve.clear();
for(int i = 0; i < geodesic.size(); i++)
{
Point p;
p.a = geodesic[i];
p.b = -1;
p.t = 1;
for(int j = 0; j < control_points.size(); j++)
{
if(control_points[j] == p.a)
{
p.is_control_point = true;
p.control_points.push_back(control_points[j]);
}
}
curve.push_back(p);
}
desired_total_curvature = 0;
for(int i = 1; i < curve.size() - 1; i++)
{
double curvature = computeCurvature(i);
curve[i].desiredCurvature = curvature * t;
curve[i].lastCurvature = curve[i].desiredCurvature;
desired_total_curvature += curve[i].desiredCurvature;
}
return true;
}
void CurveGenerator::smooth()
{
for(current_index = 1; current_index < curve.size() - 1; current_index++)
{
handlePoint(current_index);
}
}
bool CurveGenerator::onSameEdge(const Point &a, const Point &b)
{
/*if(isVertex(a))
{
return b.a == getVertex(a) || b.b == getVertex(a);
}
if(isVertex(b))
{
return a.a == getVertex(b) || a.b == getVertex(b);
}*/
return (a.a == b.a && a.b == b.b) || (a.b == b.a && a.a == b.b);
}
void CurveGenerator::push_unique(std::vector<int> &v, int a)
{
for(int i = 0; i < v.size(); i++)
{
if(v[i] == a)
{
return;
}
}
v.push_back(a);
}
bool CurveGenerator::inSameFace(const Point& a, const Point& b, const Point& c)
{
std::vector<int> appeared_vertices;
if(isVertex(a))
{
push_unique(appeared_vertices, a.a);
}
else
{
push_unique(appeared_vertices, a.a);
push_unique(appeared_vertices, a.b);
}
if(isVertex(b))
{
push_unique(appeared_vertices, b.a);
}
else
{
push_unique(appeared_vertices, b.a);
push_unique(appeared_vertices, b.b);
}
if(isVertex(c))
{
push_unique(appeared_vertices, c.a);
}
else
{
push_unique(appeared_vertices, c.a);
push_unique(appeared_vertices, c.b);
}
if(appeared_vertices.size() > 3)
{
return false;
}
if(appeared_vertices.size() == 2)
{
return true;
}
bool exist1 = false, exist2 = false;
auto& neighbours = vertex_neighbours[appeared_vertices[0]];
for(int i = 0; i < neighbours.size(); i++)
{
if(neighbours[i] == appeared_vertices[1])
{
exist1 = true;
}
if(neighbours[i] == appeared_vertices[2])
{
exist2 = true;
}
}
if(!(exist1 && exist2))
{
return false;
}
bool exist3 = false, exist4 = false;
auto& neighbours2 = vertex_neighbours[appeared_vertices[1]];
for(int i = 0; i < neighbours2.size(); i++)
{
if(neighbours2[i] == appeared_vertices[0])
{
exist3 = true;
}
if(neighbours2[i] == appeared_vertices[2])
{
exist4 = true;
}
}
if(!(exist3 && exist4))
{
return false;
}
return true;
}
int CurveGenerator::getCommonVertex(const Point &a, const Point &b)
{
if(a.a == b.a)
{
return a.a;
}
if(a.a == b.b)
{
return a.a;
}
if(a.b == b.a)
{
return a.b;
}
if(a.b == b.b && a.b >= 0)
{
return a.b;
}
return -1;
}
void CurveGenerator::handlePoint(int point_index)
{
Point& point = curve[point_index];
if(point.is_control_point)
{
//return;
}
if(inSameFace(curve[point_index - 1], curve[point_index], curve[point_index + 1]))
{
curve[point_index - 1].is_control_point |= curve[point_index].is_control_point;
if(curve[point_index].is_control_point)
{
curve[point_index - 1].control_points = merge(curve[point_index - 1].control_points,
curve[point_index].control_points);
}
curve[point_index + 1].is_control_point |= curve[point_index].is_control_point;
if(curve[point_index].is_control_point)
{
curve[point_index + 1].control_points = merge(curve[point_index + 1].control_points,
curve[point_index].control_points);
}
auto iter = curve.begin() + point_index;
curve.erase(iter);
current_index --;
while(current_index > 0 && inSameFace(curve[current_index-1], curve[current_index],
curve[current_index+1]))
{
curve[point_index - 1].is_control_point |= curve[point_index].is_control_point;
if(curve[point_index].is_control_point)
{
curve[point_index - 1].control_points = merge(curve[point_index - 1].control_points,
curve[point_index].control_points);
}
curve[point_index + 1].is_control_point |= curve[point_index].is_control_point;
if(curve[point_index].is_control_point)
{
curve[point_index + 1].control_points = merge(curve[point_index + 1].control_points,
curve[point_index].control_points);
}
iter = curve.begin() + current_index;
curve.erase(iter);
current_index--;
}
return;
}
if(isVertex(point))
{
current_index += split(point_index);
current_index--;
}
else
{
auto& neighbours = vertex_neighbours[point.a];
matrixr_t expMap = getExpMap(point.a, neighbours);
matrixr_t polar_plus, polar_minus, polar_p2;
getPolar(curve[point_index - 1], point.a, neighbours, expMap, polar_minus);
getPolar(curve[point_index + 1], point.a, neighbours, expMap, polar_plus);
for(int i = 0; i < neighbours.size(); i++)
{
if(neighbours[i] == point.b)
{
polar_p2 = expMap(colon(), i);
}
}
relocate(polar_minus, polar_plus, polar_p2, point.b, point);
}
}
void CurveGenerator::relocate(const matrixr_t &polar_minus, const matrixr_t &polar_plus,
const matrixr_t &polar_p2, int p2, Point& p)
{
auto& vertices = mesh.getVertices();
//std::cout << "polar_plus" << std::endl << polar_plus << std::endl
// << "polar minus" << std::endl << polar_minus << std::endl
// << "polar_p2" << std::endl << polar_p2 << std::endl;
double lambda;
if(p.is_control_point == false)
{
lambda = 1;
//computeLambda(polar_plus, polar_minus, polar_p2, PI - fabs(p.desiredCurvature));
}
else
{
lambda = 0.25f;
}
double theta_plus_p_p2 = fabs(polar_plus[1] - polar_p2[1]);
if(theta_plus_p_p2 > PI)
{
theta_plus_p_p2 = 2 * PI - theta_plus_p_p2;
}
double plus_proj = polar_plus[0] * sin(theta_plus_p_p2);
double p_proj_plus = polar_plus[0] * cos(theta_plus_p_p2);
double theta_minus_p_p2 = fabs(polar_minus[1] - polar_p2[1]);
if(theta_minus_p_p2 > PI)
{
theta_minus_p_p2 = 2 * PI - theta_minus_p_p2;
}
double minus_proj = polar_minus[0] * sin(theta_minus_p_p2);
double p_proj_minus = polar_minus[0] * cos(theta_minus_p_p2);
double edge_length = norm(vertices(colon(), p.a) - vertices(colon(), p2));
double p_length = (1 - p.t) * edge_length;
double t_minus = 1 - p_proj_minus / edge_length;
double t_plus = 1 - p_proj_plus / edge_length;
double t_new;
//decide whether minus and plus are on diffrent sides of line segment pp2.
double polar_bigger = polar_minus[1] > polar_plus[1] ? polar_minus[1] : polar_plus[1];
double polar_smaller = polar_minus[1] < polar_plus[1] ? polar_minus[1] : polar_plus[1];
double polar_bigger_2 = polar_bigger + PI;
if(polar_bigger_2 > 2 * PI)
{
polar_bigger_2 -= 2 * PI;
}
double polar_smaller_2 = polar_smaller + PI;
if(polar_smaller_2 > 2 * PI)
{
polar_smaller_2 -= 2 * PI;
}
bool on_different_side = false;
bool on_different_side_1, on_different_side_2;
if(polar_bigger - polar_smaller < PI)
{
on_different_side_1 = polar_p2[1] > polar_smaller && polar_p2[1] < polar_bigger;
}
else
{
on_different_side_1 = polar_p2[1] < polar_smaller || polar_p2[1] > polar_bigger;
}
if(polar_bigger_2 - polar_smaller_2 < PI)
{
on_different_side_2 = polar_p2[1] > polar_smaller_2 && polar_p2[1] < polar_bigger_2;
}
else
{
on_different_side_2 = polar_p2[1] < polar_smaller_2 || polar_p2[1] > polar_bigger_2;
}
on_different_side = on_different_side_1 || on_different_side_2;
if(on_different_side)
{
//minus and plus are on diffrent sides of line segment pp2.
double omega_plus = minus_proj / (minus_proj + plus_proj);
double omega_minus = plus_proj / (minus_proj + plus_proj);
t_new = (1 - lambda) * p.t + lambda * (omega_minus * t_minus + omega_plus * t_plus);
}
else
{
/*double omega_plus = minus_proj / (minus_proj - plus_proj);
double omega_minus = plus_proj / (plus_proj - minus_proj);
t_new = (1 - lambda) * p.t + lambda * (omega_minus * t_minus + omega_plus * t_plus);*/
t_new = 1;
}
if(t_new < 0)
{
p.a = p.b;
p.b = -1;
t_new = 1;
}
else if(t_new >= 1)
{
t_new = 1;
p.b = -1;
}
p.t = t_new;
}
int CurveGenerator::split(int point_index)
{
Point p = curve[point_index];
Point pplus = curve[point_index + 1];
Point pminus = curve[point_index - 1];
auto& vertices = mesh.getVertices();
matrixr_t coorp = vertices(colon(), p.a);
auto& neighbours = vertex_neighbours[p.a];
matrixr_t expMap = getExpMap(p.a, neighbours);
//std::cout << "expMap" << std::endl << expMap << std::endl;
//compute polar coordinate of pplus,pminus
matrixr_t polar_plus(2,1), polar_minus(2,1);
getPolar(pplus, p.a, neighbours, expMap, polar_plus);
getPolar(pminus, p.a, neighbours, expMap, polar_minus);
std::vector<size_t> N1,N2;
selectNeighbours(expMap, neighbours, p.a, pplus, pminus, N1, N2);
auto split_result_1 = getSplitResult(expMap, neighbours, N1, p, polar_plus, polar_minus);
auto split_result_2 = getSplitResult(expMap, neighbours, N2, p, polar_plus, polar_minus);;
double length1 = computeSplitLength(pplus, pminus, split_result_1);
double length2 = computeSplitLength(pplus, pminus, split_result_2);
curve.erase(curve.begin() + point_index);
if(length1 < length2)
{
int i = 0;
for(auto iter = curve.begin() + point_index; i < split_result_1.size(); ++iter, ++i)
{
iter = curve.insert(iter, split_result_1[i]);
}
return split_result_1.size();
}
else
{
int i = 0;
for(auto iter = curve.begin() + point_index; i < split_result_2.size(); ++iter, ++i)
{
iter = curve.insert(iter, split_result_2[i]);
}
return split_result_2.size();
}
}
matrixr_t CurveGenerator::getExpMap(int vert, const std::vector<size_t>& neighbours)
{
auto& vertices = mesh.getVertices();
matrixr_t coorp = vertices(colon(), vert);
matrixr_t expMap(2, neighbours.size());
double theta = 0;
for(int i = 0; i < neighbours.size(); i++)
{
int a = i;
int b = (i+1) % neighbours.size();
matrixr_t coora = vertices(colon(), neighbours[a]);
matrixr_t coorb = vertices(colon(), neighbours[b]);
matrixr_t pa = coora - coorp;
matrixr_t pb = coorb - coorp;
double angle = acos(dot(pa, pb) / (norm(pa) * norm(pb)));
expMap(0, a) = norm(pa);
expMap(1, a) = theta;
theta += angle;
}
double ratio = 2 * PI / theta;
for(int i = 0; i < neighbours.size(); i++)
{
expMap(1, i) *= ratio;
}
return expMap;
}
void CurveGenerator::selectNeighbours(const matrixr_t &expMap, const std::vector<size_t> &neighbours,
int vert, Point plus, Point minus, std::vector<size_t> &N1,
std::vector<size_t>& N2)
{
int region = 0;
int prev_neighbour = -1;
int need_reverse_region;
int bound[2] = {0, 0};
//for test
if(isVertex(plus))
{
assert(plus.b == -1);
}
if(isVertex(minus))
{
assert(minus.b == -1);
}
N1.clear();
N2.clear();
for(int i = 0; i < neighbours.size(); i++)
{
bool equals_plus = isVertex(plus) && getVertex(plus) == neighbours[i];
bool equals_minus = (isVertex(minus) && getVertex(minus) == neighbours[i]);
if(equals_plus || equals_minus)
{
if(region == 0)
{
bound[0] = N1.size();
}
else
{
bound[1] = N2.size();
}
if(equals_minus)
{
need_reverse_region = region;
}
else
{
need_reverse_region = !region;
}
region = !region;
prev_neighbour = neighbours[i];
continue;
}
if(prev_neighbour >= 0)
{
if((plus.a == neighbours[i] && plus.b == prev_neighbour)
|| (plus.b == neighbours[i] && plus.a == prev_neighbour))
{
if(region == 0)
{
bound[0] = N1.size();
}
else
{
bound[1] = N2.size();
}
region = !region;
need_reverse_region = region;
}
if((minus.a == neighbours[i] && minus.b == prev_neighbour)
|| (minus.b == neighbours[i] && minus.a == prev_neighbour))
{
if(region == 0)
{
bound[0] = N1.size();
}
else
{
bound[1] = N2.size();
}
need_reverse_region = region;
region = !region;
}
}
prev_neighbour = neighbours[i];
if(region == 0)
{
N1.push_back(i);
}
else
{
N2.push_back(i);
}
}
normalizeNeighbours(bound[0], N1);
normalizeNeighbours(bound[1], N2);
if(need_reverse_region == 0)
{
reverse(N1);
}
else if(need_reverse_region == 1)
{
reverse(N2);
}
}
void CurveGenerator::normalizeNeighbours(int bound, std::vector<size_t> &neighbours)
{
assert(bound >=0 && bound <= neighbours.size());
std::vector<size_t> temp;
for(int i = 0; i < bound; i++)
{
temp.push_back(neighbours[i]);
}
for(int i = bound; i < neighbours.size(); i++)
{
neighbours[i - bound] = neighbours[i];
}
for(int i = 0; i < temp.size(); i++)
{
neighbours[neighbours.size() - temp.size() + i] = temp[i];
}
}
void CurveGenerator::reverse(std::vector<size_t>& neighbours)
{
for(int i = 0; i < neighbours.size() / 2; i++)
{
auto temp = neighbours[i];
neighbours[i] = neighbours[neighbours.size() - i - 1];
neighbours[neighbours.size() - i - 1] = temp;
}
}
std::vector<CurveGenerator::Point> CurveGenerator::getSplitResult(const matrixr_t &expMap, const std::vector<size_t>& neighbours,
const std::vector<size_t> &N, Point p,
const matrixr_t &polar_plus, const matrixr_t polar_minus)
{
matrixr_t polar_minus_temp = polar_minus;
std::vector<Point> result;
for(int i = 0; i < N.size(); i++)
{
Point splited_point;
splited_point.a = getVertex(p);
splited_point.b = neighbours[N[i]];
splited_point.desiredCurvature = p.desiredCurvature;
splited_point.t = 1;
splited_point.is_control_point = p.is_control_point;
splited_point.control_points = p.control_points;
relocate(polar_minus_temp, polar_plus, expMap(colon(), N[i]), splited_point.b, splited_point);
if(isVertex(splited_point))
{
if(getVertex(p) == getVertex(splited_point))
{
result.push_back(splited_point);
return result;
}
}
result.push_back(splited_point);
getPolar(splited_point, getVertex(p), neighbours, expMap, polar_minus_temp);
}
return result;
}
void CurveGenerator::getPolar(Point p, int vert, const std::vector<size_t>& neighbours, const matrixr_t& expMap,
matrixr_t &polar)
{
polar = matrixr_t(2,1);
matrixr_t a(2,1), b(2,1), c(2,1);
for(int i = 0; i < neighbours.size(); i++)
{
if(p.a == neighbours[i] && p.b == vert)
{
polar[0] = p.t * expMap(0, i);
polar[1] = expMap(1, i);
return;
}
else if(p.b == neighbours[i] && p.a == vert)
{
polar[0] = (1 - p.t) * expMap(0, i);
polar[1] = expMap(1, i);
return;
}
else
{
if(p.a == neighbours[i])
{
a[0] = expMap(0, i) * cos(expMap(1, i));
a[1] = expMap(0, i) * sin(expMap(1, i));
}
else if(p.b == neighbours[i])
{
b[0] = expMap(0, i) * cos(expMap(1, i));
b[1] = expMap(0, i) * sin(expMap(1, i));
}
}
}
c = p.t * a + (1 - p.t) * b;
polar[0] = sqrt(c[0] * c[0] + c[1] * c[1]);
polar[1] = get_2d_angle(c[0], c[1]);
}
double CurveGenerator::computeCurvature(int point_index)
{
Point point = curve[point_index];
assert(point_index > 0 && point_index < curve.size() - 1);
Point plus = curve[point_index + 1];
Point minus = curve[point_index - 1];
matrixr_t coor_plus = getCoordinate(plus);
matrixr_t coor_minus = getCoordinate(minus);
matrixr_t coor_point = getCoordinate(point);
matrixr_t a = coor_plus - coor_point;
matrixr_t b = coor_minus - coor_point;
double beta = acos(dot(a,b) / (norm(a) * norm(b)));
double theta;
if(isVertex(point))
{
theta = mesh.computeVertexAngle(point.a);
}
else
{
theta = 2 * PI;
}
return PI - (2 * PI * beta / theta);
}
double CurveGenerator::computeLambda(const matrixr_t &polar_plus, const matrixr_t &polar_minus,
const matrixr_t &polar_p2, double theta)
{
matrixr_t coor_plus(2,1);
matrixr_t coor_minus(2,1);
matrixr_t coor_p2(2,1);
coor_plus[0] = polar_plus[0] * cos(polar_plus[1]);
coor_plus[1] = polar_plus[0] * sin(polar_plus[1]);
coor_minus[0] = polar_minus[0] * cos(polar_minus[1]);
coor_minus[1] = polar_minus[0] * sin(polar_minus[1]);
coor_p2[0] = polar_p2[0] * cos(polar_p2[1]);
coor_p2[1] = polar_p2[0] * sin(polar_p2[1]);
matrixr_t minus_plus = coor_plus - coor_minus;
double u, gamma;
double theta_p_minus_plus = acos(dot(-coor_minus, minus_plus) /
(polar_minus[0] * norm(minus_plus)));
if(theta_p_minus_plus > PI / 2) //proj,minus,star,plus
{
double projp = -polar_minus[0] * cos(theta_p_minus_plus);
double theta_minus_p_proj = PI / 2 - (PI - theta_p_minus_plus);
double minus_proj = polar_minus[0] * sin(theta_minus_p_proj);
double theta_minus_p_star = fabs(polar_p2[1] - polar_minus[1]);
if(theta_minus_p_star > PI)
{
theta_minus_p_star = 2 * PI - theta_minus_p_star;
}
double theta_proj_p_star = theta_minus_p_proj + theta_minus_p_star;
double proj_star = projp * tan(theta_proj_p_star);
u = proj_star - minus_proj;
gamma = PI / 2 + theta_proj_p_star;
}
else
{
double projp = polar_minus[0] * sin(theta_p_minus_plus);
double theta_minus_p_proj = PI / 2 - theta_p_minus_plus;
double minus_proj = polar_minus[0] * sin(theta_minus_p_proj);
double theta_minus_p_star = fabs(polar_p2[1] - polar_minus[1]);
if(theta_minus_p_star > PI)
{
theta_minus_p_star = 2 * PI - theta_minus_p_star;
}
if(theta_minus_p_star > theta_minus_p_proj) //minus,proj,star,plus
{
double theta_proj_p_star = theta_minus_p_star - theta_minus_p_proj;
double proj_star = projp * tan(theta_proj_p_star);
u = minus_proj + proj_star;
gamma = PI / 2 + theta_proj_p_star;
}
else
{
double theta_proj_p_star = theta_minus_p_proj - theta_minus_p_star;
double proj_star = projp * tan(theta_proj_p_star);
u = minus_proj - proj_star;
gamma = PI / 2 - theta_proj_p_star;
}
}
double alpha = 1 + 1 / (tan(gamma) * tan(gamma));
double L = norm(minus_plus);
double T = tan(theta - PI);
double beta = L / T + (L - 2 * u) / tan(gamma);
double sqrt_value = beta * beta / (4 * alpha * alpha) + u * (L - u) / alpha;
if(fabs(sqrt_value) < 1e-3)
{
sqrt_value = 0;
}
assert(sqrt_value >= 0);
double ystar = beta / (2 * alpha) + sqrt(sqrt_value);
double theta_for_cross = acos(dot(coor_minus, minus_plus) / (norm(coor_minus) * norm(minus_plus)));
double d = fabs(norm(coor_minus) * norm(minus_plus) * sin(theta_for_cross)) / L;
assert(d != 0);
return 1 - ystar / d;
}
double CurveGenerator::computeSplitLength(Point plus, Point minus, std::vector<Point> &split_result)
{
Curve curve;
curve.push_back(minus);
for(int i = 0; i < split_result.size(); i++)
{
curve.push_back(split_result[i]);
}
curve.push_back(plus);
return computeLength(curve);
}
double CurveGenerator::computeLength(Curve curve)
{
if(curve.size() < 1)
{
return 0;
}
matrixr_t coor_prev = getCoordinate(curve[0]);
matrixr_t coor_current;
double length = 0;
for(int i = 1; i < curve.size(); i++)
{
coor_current = getCoordinate(curve[i]);
length += norm(coor_current - coor_prev);
coor_prev = coor_current;
}
return length;
}
bool CurveGenerator::isFinished()
{
bool result = true;
double total_curvature = 0;
for(int i = 1; i < curve.size() - 1; i++)
{
if(curve[i].is_control_point)
{
Point& p = curve[i];
for(int j = 0; j < p.control_points.size(); j++)
{
if(mesh.howManyRing(p.a ,p.control_points[j]) > 2 ||
(p.b >= 0 && mesh.howManyRing(p.b ,p.control_points[j]) > 2))
{
return true;
}
}
}
double curvature = computeCurvature(i);
total_curvature += curvature;
if( fabs(curvature - curve[i].lastCurvature) / curve[i].lastCurvature > error_percentage)
{
result = false;
}
curve[i].lastCurvature = curvature;
}
if(desired_total_curvature == 0)
{
return true;
}
if(fabs(total_curvature - desired_total_curvature) / desired_total_curvature < error_percentage)
{
return true;
}
return result;
}
bool CurveGenerator::isVertex(Point p)
{
return p.t == 0 || p.t == 1;
}
int CurveGenerator::getVertex(Point p)
{
if(p.t == 0)
{
return p.b;
}
return p.a;
}
int CurveGenerator::getAnotherVertex(Point p)
{
if(p.t == 0)
{
return p.a;
}
return p.b;
}
matrixr_t CurveGenerator::getCoordinate(Point p)
{
auto& vertices = mesh.getVertices();
if(isVertex(p))
{
return vertices(colon(), p.a);
}
return vertices(colon(), p.a) * p.t + vertices(colon(), p.b) * (1 - p.t);
}
void CurveGenerator::handleCriticalVertices()
{
auto critical_points = findCriticalPoints();
for(int i = 0; i < critical_points.size(); i++)
{
Curve try_curve_1, try_curve_2;
const CriticalPointInfo& info = critical_points[i];
assert(info.points[0] > 0);
try_curve_1.push_back(curve[info.points[0] - 1]);
try_curve_2.push_back(curve[info.points[0] - 1]);
for(int j = 0; j < info.points.size(); j++)
{
try_curve_1.push_back(curve[info.points[j]]);
}
assert(info.points[info.points.size() - 1] + 1 < curve.size());
try_curve_1.push_back(curve[info.points[info.points.size() - 1] + 1]);
Point p;
p.a = info.move_to_index;
p.b = -1;
p.desiredCurvature = curve[info.points[0]].desiredCurvature;
p.lastCurvature = computeMeanCurvature(info);
p.t = 1;
for(int j = 0; j < info.points.size(); j++)
{
if(curve[info.points[j]].is_control_point)
{
p.is_control_point = true;
p.control_points = merge(p.control_points, curve[info.points[j]].control_points);
}
}
try_curve_2.push_back(p);
try_curve_2.push_back(curve[info.points[info.points.size() - 1] + 1]);
double length1 = computeLength(try_curve_1);
double length2 = computeLength(try_curve_2);
if(length2 < length1)
{
for(int j = 0; j < info.points.size(); j++)
{
curve[info.points[j]].a = try_curve_2[1].a;
curve[info.points[j]].b = try_curve_2[1].b;
curve[info.points[j]].t = try_curve_2[1].t;
curve[info.points[j]].desiredCurvature = try_curve_2[1].desiredCurvature;
curve[info.points[j]].lastCurvature = try_curve_2[1].lastCurvature;
}
}
}
//merge same points
int prev_vertex = -1;
for(auto iter = curve.begin(); iter != curve.end(); ++iter)
{
if(isVertex(*iter))
{
if(getVertex(*iter) == prev_vertex)
{
if(iter->is_control_point)
{
auto iter_prior = iter - 1;
iter_prior->is_control_point = true;
iter_prior->control_points = merge(iter_prior->control_points, iter->control_points);
}
iter = curve.erase(iter);
--iter;
}
else
{
prev_vertex = getVertex(*iter);
}
}
}
}
std::vector<CurveGenerator::CriticalPointInfo> CurveGenerator::findCriticalPoints()
{
int prev_moving_to = -1;
std::vector<int> points;
std::vector<CriticalPointInfo> result;
for(int i = 1; i < curve.size(); i++)
{
if(isVertex(curve[i]))
{
if(prev_moving_to >= 0)
{
CriticalPointInfo info;
info.move_to_index = prev_moving_to;
info.points = points;
result.push_back(info);
points.clear();
prev_moving_to = -1;
}
continue;
}
if(curve[i].a == prev_moving_to || curve[i].b == prev_moving_to)
{
points.push_back(i);
}
else
{
if(prev_moving_to >= 0)
{
CriticalPointInfo info;
info.move_to_index = prev_moving_to;
info.points = points;
result.push_back(info);
}
points.clear();
if(curve[i - 1].a == curve[i].a || curve[i - 1].a == curve[i].b)
{
prev_moving_to = curve[i - 1].a;
points.push_back(i - 1);
points.push_back(i);
}
else if(curve[i - 1].b == curve[i].a || curve[i - 1].b == curve[i].b)
{
prev_moving_to = curve[i - 1].b;
points.push_back(i - 1);
points.push_back(i);
}
else
{
prev_moving_to = -1;
}
}
}
return result;
}
double CurveGenerator::computeMeanCurvature(const CriticalPointInfo &info)
{
double result = 0;
for(int i = 0; i < info.points.size();i++)
{
result += curve[info.points[i]].lastCurvature;
}
return result / info.points.size();
}
std::vector<int> CurveGenerator::merge(const std::vector<int> &a, const std::vector<int> &b)
{
std::vector<int> result = a;
for(int i = 0 ; i < b.size(); i++)
{
bool existed = false;
for(int j = 0; j < a.size(); j++)
{
if(b[i] == a[j])
{
existed = true;
break;
}
}
if(existed == false)
{
result.push_back(b[i]);
}
}
return result;
}
| [
"342631359@@qq.com"
] | 342631359@@qq.com |
1dd3ccd899459ffd90cb50e2417e466af8ac46be | fef1e13f46154e16bf566a9b289f25b4550aceb7 | /tf_opt/neural_net/ops/arithmetic_operations.h | d0f623da2f1903da263efa50d08b5a2dedb1e8f8 | [
"Apache-2.0"
] | permissive | ljmi2dle/tf-opt | 7438cfc28d88589cd8980d60f864dc78cf77b34e | d546d218e61e2933760149760187bf122e6dc178 | refs/heads/master | 2023-04-21T16:12:43.461204 | 2021-05-20T19:22:41 | 2021-05-20T19:23:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,273 | h | // Copyright 2021 The tf.opt Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef TF_OPT_SHARED_OPS_ARITHMETIC_OPERATIONS_H_
#define TF_OPT_SHARED_OPS_ARITHMETIC_OPERATIONS_H_
#include <string>
#include <utility>
#include <vector>
#include "ortools/base/logging.h"
#include "absl/status/statusor.h"
#include "tf_opt/neural_net/operation.h"
#include "tf_opt/neural_net/operation_validator.h"
#include "tf_opt/neural_net/operation_visitor.h"
#include "tf_opt/neural_net/ops/operation_types.h"
#include "tf_opt/open_source/status_macros.h"
#include "tf_opt/tensor/math.h"
#include "tf_opt/tensor/shape.h"
namespace tf_opt {
template <BinaryArithmeticOpType OpType>
class BinaryArithmeticOperation : public Operation {
public:
~BinaryArithmeticOperation() override {}
const Shape& left() const { return input_shape(0); }
const Shape& right() const { return input_shape(1); }
void Accept(OperationVisitor* visitor) const override {
visitor->Visit(*this);
}
static absl::StatusOr<BinaryArithmeticOperation<OpType>> Create(
std::string op_name, Shape left_shape, Shape right_shape);
// TODO: replace this by a variadic template function.
static MaybeForGraph<BinaryArithmeticOperation<OpType>> CreateForGraph(
std::string op_name, const Operation* left, const Operation* right);
// Expected input format:
// input_shapes: Shapes of the input tensors, input_shapes.size() == 2.
// output_shape: The shape to produce, follows broadcasting rules.
// options: Empty.
static absl::StatusOr<BinaryArithmeticOperation<OpType>> GenericCreate(
std::string op_name, std::vector<Shape> input_shapes, Shape output_shape,
const Options& options);
proto::TensorNode ToProto(
const std::vector<std::string>& inputs) const override;
private:
BinaryArithmeticOperation(std::string op_name,
std::vector<Shape> input_shapes,
Shape output_shape);
};
// Add two tensors element-wise.
using AddOperation = BinaryArithmeticOperation<BinaryArithmeticOpType::kAdd>;
// Subtract two tensors element-wise.
using SubtractOperation =
BinaryArithmeticOperation<BinaryArithmeticOpType::kSubtract>;
// Multiply two tensors element-wise.
using MultiplyOperation =
BinaryArithmeticOperation<BinaryArithmeticOpType::kMultiply>;
// Divide two tensors element-wise.
using DivideOperation =
BinaryArithmeticOperation<BinaryArithmeticOpType::kDivide>;
// ///////////////////////////// Implementation ////////////////////////////////
template <BinaryArithmeticOpType OpType>
BinaryArithmeticOperation<OpType>::BinaryArithmeticOperation(
std::string op_name, std::vector<Shape> input_shapes, Shape output_shape)
: Operation(std::move(op_name), std::move(input_shapes),
std::move(output_shape)) {}
template <BinaryArithmeticOpType OpType>
absl::StatusOr<BinaryArithmeticOperation<OpType>>
BinaryArithmeticOperation<OpType>::Create(std::string op_name, Shape left_shape,
Shape right_shape) {
TFOPT_ASSIGN_OR_RETURN(Shape output_shape,
BinaryOpOutputShape(left_shape, right_shape));
return BinaryArithmeticOperation<OpType>(
std::move(op_name), {std::move(left_shape), std::move(right_shape)},
std::move(output_shape));
}
template <BinaryArithmeticOpType OpType>
MaybeForGraph<BinaryArithmeticOperation<OpType>>
BinaryArithmeticOperation<OpType>::CreateForGraph(std::string op_name,
const Operation* left,
const Operation* right) {
return FromMaybeCreated(
BinaryArithmeticOperation<OpType>::Create(
std::move(op_name), left->output_shape(), right->output_shape()),
{left, right});
}
template <BinaryArithmeticOpType OpType>
absl::StatusOr<BinaryArithmeticOperation<OpType>>
BinaryArithmeticOperation<OpType>::GenericCreate(
std::string op_name, std::vector<Shape> input_shapes, Shape output_shape,
const Options& options) {
OperationValidator validator("BinaryArithmeticOperation", op_name);
TFOPT_RETURN_IF_ERROR(
validator.ExpectInputSizeEquals(input_shapes.size(), 2));
TFOPT_RETURN_IF_ERROR(validator.ExpectOptionsEmpty(options.size()));
TFOPT_ASSIGN_OR_RETURN(BinaryArithmeticOperation<OpType> result,
BinaryArithmeticOperation<OpType>::Create(
std::move(op_name), std::move(input_shapes[0]),
std::move(input_shapes[1])),
_ << validator.base_error_message());
TFOPT_RETURN_IF_ERROR(
validator.ExpectOutputShapeEquals(output_shape, result.output_shape()));
return std::move(result);
}
template <BinaryArithmeticOpType OpType>
proto::TensorNode BinaryArithmeticOperation<OpType>::ToProto(
const std::vector<std::string>& inputs) const {
CHECK_EQ(inputs.size(), 2);
proto::TensorNode result;
result.set_name(name());
switch (OpType) {
case BinaryArithmeticOpType::kAdd:
result.set_op_type(proto::OpType::ADD);
break;
case BinaryArithmeticOpType::kSubtract:
result.set_op_type(proto::OpType::SUBTRACT);
break;
case BinaryArithmeticOpType::kMultiply:
result.set_op_type(proto::OpType::MULTIPLY);
break;
case BinaryArithmeticOpType::kDivide:
result.set_op_type(proto::OpType::DIVIDE);
break;
}
*result.mutable_out_dimension() = output_shape().AsProto();
for (const std::string& input : inputs) {
result.add_input_names(input);
}
result.set_output_type(proto::TensorNode::FLOAT32);
return result;
}
} // namespace tf_opt
#endif // TF_OPT_SHARED_OPS_ARITHMETIC_OPERATIONS_H_
| [
"no-reply@google.com"
] | no-reply@google.com |
8bf9b76d59b7a832fe4823950228174453784bfb | 2318276621d6301eedf14031ad942792a0d953c4 | /rubiksCubeBases.hpp | 17884ac6bb25947d7ac8bcdbbab1a30f6dac4cce | [] | no_license | Matthew244Z/Rubiks-Cube-Solver-Project-Part-1 | 37eda8f897f41203b79d3a805594a3cc2f9e98be | 1fb5db8ca2bcf044a43b1bb9296f69e6c5402874 | refs/heads/main | 2023-04-12T01:16:44.005453 | 2021-05-18T05:18:00 | 2021-05-18T05:18:00 | 368,405,891 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,510 | hpp | #ifndef RUBIKS_CUBE_BASES
#define RUBIKS_CUBE_BASES
#include "rubiksCubeMovements.hpp"
const int ROW = 6;
const int COLUMN = 8;
const int FOUR_SIDES = 12;
const int ONE_SIDE = 8;
const int CENTER = 6;
const int TOP = 0;
const int FRONT = 1;
const int RIGHT = 2;
const int BEHIND = 3;
const int LEFT = 4;
const int BOTTOM = 5;
const string YELLOW_CHAR = "Y";
const string BLUE_CHAR = "B";
const string RED_CHAR = "R";
const string GREEN_CHAR = "G";
const string ORANGE_CHAR = "O";
const string WHITE_CHAR = "W";
const int EDGE_NUM = 4;
Movement moveU(0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 1, 2, 3, 4, 0, "U");
Movement moveD(4, 5, 6, 4, 5, 6, 4, 5, 6, 4, 5, 6, 1, 4, 3, 2, 5, "D");
Movement moveR(2, 3, 4, 2, 3, 4, 2, 3, 4, 6, 7, 0, 0, 1, 5, 3, 2, "R");
Movement moveL(6, 7, 0, 2, 3, 4, 6, 7, 0, 6, 7, 0, 0, 3, 5, 1, 4, "L");
Movement moveF(4, 5, 6, 2, 3, 4, 0, 1, 2, 6, 7, 0, 0, 4, 5, 2, 1, "F");
Movement moveB(0, 1, 2, 2, 3, 4, 4, 5, 6, 6, 7, 0, 0, 2, 5, 4, 3, "B");
// -------------------- Array Functions
void buildArray(ifstream & fin, string array[ROW][COLUMN]);
void printArray(string array[ROW][COLUMN]);
// -------------------- Move one layer
void moveLayer(string array[ROW][COLUMN], Movement const & moveX);
void moveSide(string array[ROW][COLUMN], Movement const & moveX);
void moveCube(string array[ROW][COLUMN], Movement const & moveX, bool print);
void moveCubeTwice(string array[ROW][COLUMN], Movement const & moveX, bool print);
void moveCubeReverse(string array[ROW][COLUMN], Movement const & moveX, bool print);
// --------------------- Move Entire Cube Y
void moveEntireCubeY(string array[ROW][COLUMN], string arrayCenter[CENTER]);
void moveEntireCubeYNormal(string array[ROW][COLUMN], string arrayCenter[CENTER], bool print);
void moveEntireCubeYReverse(string array[ROW][COLUMN], string arrayCenter[CENTER], bool print);
void moveEntireCubeYTwice(string array[ROW][COLUMN], string arrayCenter[CENTER], bool print);
// ---------------------- Move Entire Cube X
void moveEntireCubeX(string array[ROW][COLUMN], string arrayCenter[CENTER]);
void moveEntireCubeXNormal(string array[ROW][COLUMN], string arrayCenter[CENTER], bool print);
void moveEntireCubeXReverse(string array[ROW][COLUMN], string arrayCenter[CENTER], bool print);
// --------------------- Move Middle Layer
void moveMiddleNormal(string array[ROW][COLUMN], string arrayCenter[CENTER], bool print);
void moveMiddleReverse(string array[ROW][COLUMN], string arrayCenter[CENTER], bool print);
#endif
| [
"m244zhu@uwaterloo.ca"
] | m244zhu@uwaterloo.ca |
709625b8918db2b04c92b2c604621c3bf45201d3 | 984f870fd8fc3ecdbb4153eff18ff29dd43f3808 | /final introduction c++/sumofanAP.cpp | 1fbee436c30a4187d720deaa7a20d2274682237b | [] | no_license | sakshamsomani2345/c-plus-plus-practice | 7c777fbb4444cd717bdcc6e77501b74f78c06964 | aa36723642c5f740564bcf95469ebfe0893c5121 | refs/heads/main | 2023-08-06T22:38:52.811277 | 2021-09-03T04:54:31 | 2021-09-03T04:54:31 | 402,649,494 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 245 | cpp | #include <iostream>
#include <climits>
using namespace std;
int main()
{
int n;
int d;
int a;
cin>>a>>n;
cin >> d;
int sum=0;
for (int i = n; i >0; i--)
{
cout<<a<<endl;
sum=sum+a;
a=a+d;
}
cout<<sum;
} | [
"sakshamsomani2345@gmail.com"
] | sakshamsomani2345@gmail.com |
06576fa59a34deb3b7750fdf39fb785f0b971dff | f8f3d0586a90564e72e2406180ca80de39208f89 | /source/utils/http.cpp | 9eea3558a6a38da35e3506cd1a280c0a8f71c71f | [] | no_license | libertyernie/vba-wii | 3eea51a6c94a4046fb200d61d9fca0c648f04651 | bafc65ee54331c3464161a810d71f059eeecfabe | refs/heads/master | 2020-06-07T19:49:10.829506 | 2017-08-28T21:06:49 | 2017-08-28T21:06:49 | 23,288,795 | 12 | 7 | null | 2015-05-17T02:16:29 | 2014-08-24T18:19:11 | C++ | UTF-8 | C++ | false | false | 7,217 | cpp | /****************************************************************************
* Visual Boy Advance GX
*
* Tantric December 2008
*
* http.cpp
*
* HTTP operations
* Written by dhewg/bushing, modified by Tantric
***************************************************************************/
#ifdef HW_RVL
#include <malloc.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <ogcsys.h>
#include <network.h>
#include <ogc/lwp_watchdog.h>
#include <sys/types.h>
#include <sys/errno.h>
#include <fcntl.h>
#include "menu.h"
#include "http.h"
#define TCP_CONNECT_TIMEOUT 4000 // 4 secs to make a connection
#define TCP_SEND_SIZE (32 * 1024)
#define TCP_RECV_SIZE (32 * 1024)
#define TCP_BLOCK_RECV_TIMEOUT 4000 // 4 secs to receive
#define TCP_BLOCK_SEND_TIMEOUT 4000 // 4 secs to send
#define TCP_BLOCK_SIZE 1024
#define HTTP_TIMEOUT 10000 // 10 secs to get an http response
#define IOS_O_NONBLOCK 0x04
static s32 tcp_socket(void)
{
s32 s, res;
s = net_socket(PF_INET, SOCK_STREAM, IPPROTO_IP);
if (s < 0)
return s;
// Switch off Nagle with TCP_NODELAY
u32 nodelay = 1;
net_setsockopt(s,IPPROTO_TCP,TCP_NODELAY,&nodelay,sizeof(nodelay));
res = net_fcntl(s, F_GETFL, 0);
if (res < 0)
{
net_close(s);
return res;
}
res = net_fcntl(s, F_SETFL, res | IOS_O_NONBLOCK);
if (res < 0)
{
net_close(s);
return res;
}
return s;
}
static s32 tcp_connect(char *host, const u16 port)
{
struct hostent *hp;
struct sockaddr_in sa;
struct in_addr val;
s32 s, res;
u64 t1;
s = tcp_socket();
if (s < 0)
return s;
memset(&sa, 0, sizeof(struct sockaddr_in));
sa.sin_family= PF_INET;
sa.sin_len = sizeof(struct sockaddr_in);
sa.sin_port= htons(port);
if(strlen(host) < 16 && inet_aton(host, &val))
{
sa.sin_addr.s_addr = val.s_addr;
}
else
{
hp = net_gethostbyname (host);
if (!hp || !(hp->h_addrtype == PF_INET))
return errno;
memcpy((char *) &sa.sin_addr, hp->h_addr_list[0], hp->h_length);
}
t1=ticks_to_secs(gettime());
do
{
res = net_connect(s,(struct sockaddr*) &sa, sizeof (sa));
if(ticks_to_secs(gettime())-t1 > TCP_CONNECT_TIMEOUT*1000) break;
usleep(500);
}while(res != -EISCONN);
if(res != -EISCONN)
{
net_close(s);
return -1;
}
return s;
}
static int tcp_readln(const s32 s, char *buf, const u16 max_length)
{
s32 res = -1;
s32 ret;
u64 start_time = gettime();
u16 c = 0;
while (c < max_length)
{
if (ticks_to_millisecs(diff_ticks(start_time, gettime())) > HTTP_TIMEOUT)
break;
ret = net_read(s, &buf[c], 1);
if (ret == -EAGAIN)
{
usleep(20 * 1000);
continue;
}
if (ret <= 0)
break;
if (c > 0 && buf[c - 1] == '\r' && buf[c] == '\n')
{
res = 0;
buf[c-1] = 0;
break;
}
c++;
start_time = gettime();
usleep(100);
}
return res;
}
static u32 tcp_read(const s32 s, u8 *buffer, const u32 length)
{
char *p;
u32 left, block, received, step=0;
u64 t;
s32 res;
p = (char *)buffer;
left = length;
received = 0;
t = gettime();
while (left)
{
if (ticks_to_millisecs(diff_ticks(t, gettime()))
> TCP_BLOCK_RECV_TIMEOUT)
{
break;
}
block = left;
if (block > TCP_RECV_SIZE)
block = TCP_RECV_SIZE;
res = net_read(s, p, block);
if (res == -EAGAIN)
{
usleep(20 * 1000);
continue;
}
if(res<=0) break;
received += res;
left -= res;
p += res;
usleep(1000);
if ((received / TCP_BLOCK_SIZE) > step)
{
t = gettime ();
step++;
}
}
return received;
}
static u32 tcp_write(const s32 s, const u8 *buffer, const u32 length)
{
const u8 *p;
u32 left, block, sent, step=0;
s64 t;
s32 res;
p = buffer;
left = length;
sent = 0;
t = gettime();
while (left)
{
if (ticks_to_millisecs(diff_ticks(t, gettime()))
> TCP_BLOCK_SEND_TIMEOUT)
{
break;
}
block = left;
if (block > TCP_SEND_SIZE)
block = TCP_SEND_SIZE;
res = net_write(s, p, block);
if ((res == 0) || (res == -56))
{
usleep(20 * 1000);
continue;
}
if (res < 0)
break;
sent += res;
left -= res;
p += res;
usleep(100);
if ((sent / TCP_BLOCK_SIZE) > step)
{
t = gettime ();
step++;
}
}
return left == 0;
}
static bool http_split_url(char *host, char *path, const char *url)
{
const char *p;
char *c;
if (strncasecmp(url, "http://", 7))
return false;
p = url + 7;
c = strchr(p, '/');
if (c == NULL || c[0] == 0)
return false;
snprintf(host, c-p+1, "%s", p);
strcpy(path, c);
return true;
}
#define MAX_SIZE (1024*1024*15)
/****************************************************************************
* http_request
* Retrieves the specified URL, and stores it in the specified file or buffer
***************************************************************************/
int http_request(const char *url, FILE *hfile, u8 *buffer, u32 maxsize, bool silent)
{
int res = 0;
char http_host[1024];
char http_path[1024];
u16 http_port;
http_res result;
u32 http_status;
u32 sizeread = 0, content_length = 0;
int linecount;
if(maxsize > MAX_SIZE)
return 0;
if (url == NULL || (hfile == NULL && buffer == NULL))
return 0;
if (!http_split_url(http_host, http_path, url))
return 0;
http_port = 80;
http_status = 404;
int s = tcp_connect(http_host, http_port);
if (s < 0)
{
result = HTTPR_ERR_CONNECT;
return 0;
}
char request[1024];
char *r = request;
r += sprintf(r, "GET %s HTTP/1.1\r\n", http_path);
r += sprintf(r, "Host: %s\r\n", http_host);
r += sprintf(r, "Cache-Control: no-cache\r\n\r\n");
res = tcp_write(s, (u8 *) request, strlen(request));
char line[256];
for (linecount = 0; linecount < 32; linecount++)
{
if (tcp_readln(s, line, 255) != 0)
{
http_status = 404;
result = HTTPR_ERR_REQUEST;
break;
}
if (strlen(line) < 1)
break;
sscanf(line, "HTTP/1.%*u %u", &http_status);
sscanf(line, "Content-Length: %u", &content_length);
}
if (http_status != 200)
{
result = HTTPR_ERR_STATUS;
net_close(s);
return 0;
}
// length unknown - just read as much as we can
if(content_length == 0)
{
content_length = maxsize;
}
else if (content_length > maxsize)
{
result = HTTPR_ERR_TOOBIG;
net_close(s);
return 0;
}
if (buffer != NULL)
{
if(!silent)
ShowAction("Downloading...");
sizeread = tcp_read(s, buffer, content_length);
if(!silent)
CancelAction();
}
else
{
// read into file
u32 bufSize = (1024 * 32);
u32 bytesLeft = content_length;
u32 readSize;
if(!silent)
ShowProgress("Downloading...", 0, content_length);
u8 * fbuffer = (u8 *) malloc(bufSize);
if(fbuffer)
{
while (bytesLeft > 0)
{
if (bytesLeft < bufSize)
readSize = bytesLeft;
else
readSize = bufSize;
res = tcp_read(s, fbuffer, readSize);
if (!res)
break;
sizeread += res;
bytesLeft -= res;
res = fwrite(fbuffer, 1, res, hfile);
if (!res)
break;
if(!silent)
ShowProgress("Downloading...", (content_length - bytesLeft), content_length);
}
free(fbuffer);
}
if(!silent)
CancelAction();
}
net_close(s);
if (content_length < maxsize && sizeread != content_length)
{
result = HTTPR_ERR_RECEIVE;
return 0;
}
result = HTTPR_OK;
return sizeread;
}
#endif
| [
"maybeway36@gmail.com"
] | maybeway36@gmail.com |
6d345095504ec4fa7753fc8621a0603ab88a1daf | 95bf4925e2559c024aa821e57606dc75425e7f0c | /PhysicsTimestep/Model.h | 79c1a01bede2d66a9755cf97e28d3d3f83522ec3 | [] | no_license | IGME-RIT/physics-timestep-VisualStudio | dce9b719dc7fa098f416dbe8f41b68eadfe88de0 | 615ee17b12b19820fe8606dd316d82171a541d7e | refs/heads/master | 2020-06-07T07:31:57.377571 | 2019-06-20T17:34:18 | 2019-06-20T17:34:18 | 192,962,037 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 5,846 | h | /*
Title: Physics Timestep
File Name: Model.h
Copyright © 2015
Original authors: Brockton Roth
Written under the supervision of David I. Schwartz, Ph.D., and
supported by a professional development seed grant from the B. Thomas
Golisano College of Computing & Information Sciences
(https://www.rit.edu/gccis) at the Rochester Institute of Technology.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or (at
your option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Description:
Builds upon the FPS project to introduce the concept of using a physics timestep.
What this means is that every update will have a constant delta time that is set by
a variable. This allows for smooth animations and deterministic physics. This particular
project also implements an accumulator, which will take the delta time between the two
frames and add it to a variable. That variable is then compared to the physics timestep,
and we may end up calling the update function twice in a given frame. Even then, the
delta time for the update function will always equal the physics timestep.
*/
#ifndef _MODEL_H
#define _MODEL_H
#include "GLIncludes.h"
class Model
{
private:
int numVertices;
VertexFormat* vertices;
int numIndices;
GLuint* indices;
GLuint vbo;
GLuint ebo;
//GLuint shaderProgram;
//GLuint m_Buffer;
public:
Model(int numVerts = 0, VertexFormat* verts = nullptr, int numInds = 0, GLuint* inds = nullptr);
~Model();
GLuint AddVertex(VertexFormat*);
void AddIndex(GLuint);
void InitBuffer();
void UpdateBuffer();
void Draw();
// Our get variables.
int NumVertices()
{
return numVertices;
}
int NumIndices()
{
return numIndices;
}
VertexFormat* Vertices()
{
return vertices;
}
GLuint* Indices()
{
return indices;
}
/*Model(int p_nVertices = 3, float _size = 1.0f, float _originX = 0.0f, float _originY = 0.0f, float _originZ = 0.0f)
{
if (p_nVertices < 3)
p_nVertices = 3;
m_ShaderProgram = 0;
m_Buffer = 0;
m_nVertices = p_nVertices;
m_pPoint = new Point3D[p_nVertices];
SetOrigin(_originX, _originY, _originZ);
GeneratePoints(_size);
}*/
// ~Figure(void)
// {
// Release();
// }
//
// void Release(void)
// {
// m_nVertices = 0;
// if (m_pPoint != nullptr)
// {
// delete[] m_pPoint;
// m_pPoint = nullptr;
// }
// }
//
// void SetPoint(int nIndex, float x, float y, float z = 0.0f)
// {
// if (nIndex < 0 || nIndex >= m_nVertices || m_pPoint == nullptr)
// return;
//
// m_pPoint[nIndex].x = x;
// m_pPoint[nIndex].y = y;
// m_pPoint[nIndex].z = z;
// }
//
// void SetPoint(int nIndex, Point3D p_Point)
// {
// if (nIndex < 0 || nIndex >= m_nVertices || m_pPoint == nullptr)
// return;
//
// m_pPoint[nIndex] = p_Point;
// }
//
// void operator()(int nIndex, float x, float y, float z = 0.0f)
// {
// if (nIndex < 0 || nIndex >= m_nVertices || m_pPoint == nullptr)
// return;
//
// m_pPoint[nIndex].x = x;
// m_pPoint[nIndex].y = y;
// m_pPoint[nIndex].z = z;
// }
//
// void operator()(int nIndex, Point3D p_Point)
// {
// if (nIndex < 0 || nIndex >= m_nVertices || m_pPoint == nullptr)
// return;
//
// m_pPoint[nIndex] = p_Point;
// }
//
// Point3D& operator[](int nIndex)
// {
// if (nIndex < 0 || nIndex >= m_nVertices || m_pPoint == nullptr)
// assert(false);
//
// return m_pPoint[nIndex];
// }
//
// void SetOrigin(float x, float y, float z)
// {
// m_Origin.x = x;
// m_Origin.y = y;
// m_Origin.z = z;
// }
//
// void CompileFigure(void)
// {
// for (int i = 0; i < m_nVertices; i++)
// {
// m_pPoint[i].x += m_Origin.x;
// m_pPoint[i].y += m_Origin.y;
// m_pPoint[i].z += m_Origin.z;
// }
// InitBuffer();
// }
//
// friend std::ostream& operator<<(std::ostream os, Figure& other)
// {
// other.PrintContent();
// return os;
// }
//
// void Render(void)
// {
// // Use the buffer and shader for each circle.
// glUseProgram(m_ShaderProgram);
// glBindBuffer(GL_ARRAY_BUFFER, m_Buffer);
//
// // Initialize the vertex position attribute from the vertex shader.
// GLuint loc = glGetAttribLocation(m_ShaderProgram, "vPosition");
// glEnableVertexAttribArray(loc);
// glVertexAttribPointer(loc, 3, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
//
// // Draw the array of this figure
// glDrawArrays(GL_TRIANGLE_FAN, 0, m_nVertices);
// }
//
//private:
// void InitBuffer(void)
// {
// // Create a vertex array object
// GLuint vao;
// glGenVertexArrays(1, &vao);
// glBindVertexArray(vao);
//
// // Create and initialize a buffer object for each circle.
// glGenBuffers(1, &m_Buffer);
// glBindBuffer(GL_ARRAY_BUFFER, m_Buffer);
// glBufferData(GL_ARRAY_BUFFER, m_nVertices * sizeof(Point3D), m_pPoint, GL_STATIC_DRAW);
//
// // Load shaders and use the resulting shader program
// m_ShaderProgram = InitShader("Shaders\\vshader.glsl", "Shaders\\fshader.glsl");
// }
//
// void GeneratePoints(float fSize = 1.0f)
// {
// GLfloat theta = 0;
// for (int i = 0; i < m_nVertices; i++)
// {
// theta += static_cast<GLfloat>(2 * M_PI / m_nVertices);
// m_pPoint[i].x = static_cast<GLfloat>(cos(theta)) * fSize;
// m_pPoint[i].y = static_cast<GLfloat>(sin(theta)) * fSize;
// }
// CompileFigure();
// }
//
// void PrintContent(void)
// {
// std::cout << "Content:" << std::endl;
// for (int i = 0; i < m_nVertices; i++)
// {
// std::cout << m_pPoint[i] << std::endl;
// }
// }
};
#endif //_MODEL_H
| [
"njp2424@ad.rit.edu"
] | njp2424@ad.rit.edu |
c3b77cea982f7ce7aedfe35262e00891deffc629 | 711e5c8b643dd2a93fbcbada982d7ad489fb0169 | /XPSP1/NT/shell/shell32/fsdrptgt.cpp | 0997433b390ac5d1ca07fd380b92feafb37aa333 | [] | no_license | aurantst/windows-XP-SP1 | 629a7763c082fd04d3b881e0d32a1cfbd523b5ce | d521b6360fcff4294ae6c5651c539f1b9a6cbb49 | refs/heads/master | 2023-03-21T01:08:39.870106 | 2020-09-28T08:10:11 | 2020-09-28T08:10:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 116,370 | cpp | #include "shellprv.h"
#include <cowsite.h>
#include "datautil.h"
#include "ids.h"
#include "defview.h"
#include "_security.h"
#include "shitemid.h"
#include "idlcomm.h"
#include "bitbuck.h"
#include "bookmk.h"
#include "filefldr.h"
#include "brfcase.h"
#include "copy.h"
#include "filetbl.h"
#define TF_DRAGDROP 0x04000000
typedef struct
{
HWND hwnd;
DWORD dwFlags;
POINTL pt;
CHAR szUrl[INTERNET_MAX_URL_LENGTH];
} ADDTODESKTOP;
DWORD CALLBACK AddToActiveDesktopThreadProc(void *pv)
{
ADDTODESKTOP* pToAD = (ADDTODESKTOP*)pv;
CHAR szFilePath[MAX_PATH];
DWORD cchFilePath = SIZECHARS(szFilePath);
BOOL fAddComp = TRUE;
if (SUCCEEDED(PathCreateFromUrlA(pToAD->szUrl, szFilePath, &cchFilePath, 0)))
{
TCHAR szPath[MAX_PATH];
SHAnsiToTChar(szFilePath, szPath, ARRAYSIZE(szPath));
// If the Url is in the Temp directory
if (PathIsTemporary(szPath))
{
if (IDYES == ShellMessageBox(g_hinst, pToAD->hwnd, MAKEINTRESOURCE(IDS_REASONS_URLINTEMPDIR),
MAKEINTRESOURCE(IDS_AD_NAME), MB_YESNO | MB_ICONQUESTION))
{
TCHAR szFilter[64], szTitle[64];
TCHAR szFilename[MAX_PATH];
LPTSTR psz;
OPENFILENAME ofn = { 0 };
LoadString(g_hinst, IDS_ALLFILESFILTER, szFilter, ARRAYSIZE(szFilter));
LoadString(g_hinst, IDS_SAVEAS, szTitle, ARRAYSIZE(szTitle));
psz = szFilter;
//Strip out the # and make them Nulls for SaveAs Dialog
while (*psz)
{
if (*psz == (WCHAR)('#'))
*psz = (WCHAR)('\0');
psz++;
}
lstrcpy(szFilename, PathFindFileName(szPath));
ofn.lStructSize = sizeof(OPENFILENAME);
ofn.hwndOwner = pToAD->hwnd;
ofn.hInstance = g_hinst;
ofn.lpstrFilter = szFilter;
ofn.lpstrFile = szFilename;
ofn.nMaxFile = ARRAYSIZE(szFilename);
ofn.lpstrTitle = szTitle;
ofn.Flags = OFN_EXPLORER | OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT | OFN_PATHMUSTEXIST;
if (GetSaveFileName(&ofn))
{
SHFILEOPSTRUCT sfo = { 0 };
szPath[lstrlen(szPath) + 1] = 0;
ofn.lpstrFile[lstrlen(ofn.lpstrFile) + 1] = 0;
sfo.hwnd = pToAD->hwnd;
sfo.wFunc = FO_COPY;
sfo.pFrom = szPath;
sfo.pTo = ofn.lpstrFile;
cchFilePath = SIZECHARS(szPath);
if (SHFileOperation(&sfo) == 0 &&
SUCCEEDED(UrlCreateFromPath(szPath, szPath, &cchFilePath, 0)))
{
SHTCharToAnsi(szPath, pToAD->szUrl, ARRAYSIZE(pToAD->szUrl));
}
else
fAddComp = FALSE;
}
else
fAddComp = FALSE;
}
else
fAddComp = FALSE;
}
}
if (fAddComp)
CreateDesktopComponents(pToAD->szUrl, NULL, pToAD->hwnd, pToAD->dwFlags, pToAD->pt.x, pToAD->pt.y);
LocalFree((HLOCAL)pToAD);
return 0;
}
typedef struct {
DWORD dwDefEffect;
IDataObject *pdtobj;
POINTL pt;
DWORD * pdwEffect;
HKEY rghk[MAX_ASSOC_KEYS];
DWORD ck;
HMENU hmenu;
UINT idCmd;
DWORD grfKeyState;
} FSDRAGDROPMENUPARAM;
typedef struct
{
HMENU hMenu;
UINT uCopyPos;
UINT uMovePos;
UINT uLinkPos;
} FSMENUINFO;
class CFSDropTarget : CObjectWithSite, public IDropTarget
{
public:
// IUnknown
STDMETHODIMP QueryInterface(REFIID riid, void **ppv);
STDMETHODIMP_(ULONG) AddRef(void);
STDMETHODIMP_(ULONG) Release(void);
// IDropTarget
STDMETHODIMP DragEnter(IDataObject* pdtobj, DWORD grfKeyState, POINTL pt, DWORD* pdwEffect);
STDMETHODIMP DragOver(DWORD grfKeyState, POINTL pt, DWORD* pdwEffect);
STDMETHODIMP DragLeave();
STDMETHODIMP Drop(IDataObject* pdtobj, DWORD grfKeyState, POINTL pt, DWORD* pdwEffect);
CFSDropTarget(CFSFolder *pFolder, HWND hwnd);
protected:
virtual ~CFSDropTarget();
BOOL _IsBriefcaseTarget() { return IsEqualCLSID(_pFolder->_clsidBind, CLSID_BriefcaseFolder); };
BOOL _IsDesktopFolder() { return _GetIDList() && ILIsEmpty(_GetIDList()); };
HRESULT _FilterFileContents(FORMATETC* pfmte, DWORD grfKeyFlags, DWORD dwEffectsAvail,
DWORD* pdwEffects, DWORD* pdwDefaultEffect, FSMENUINFO* pfsMenuInfo);
HRESULT _FilterFileContentsOLEHack(FORMATETC* pfmte, DWORD grfKeyFlags, DWORD dwEffectsAvail,
DWORD* pdwEffects, DWORD* pdwDefaultEffect, FSMENUINFO* pfsMenuInfo);
HRESULT _FilterDeskCompHDROP(FORMATETC* pfmte, DWORD grfKeyFlags, DWORD dwEffectsAvail,
DWORD* pdwEffects, DWORD* pdwDefaultEffect, FSMENUINFO* pfsMenuInfo);
HRESULT _FilterSneakernetBriefcase(FORMATETC* pfmte, DWORD grfKeyFlags, DWORD dwEffectsAvail,
DWORD* pdwEffects, DWORD* pdwDefaultEffect, FSMENUINFO* pfsMenuInfo);
HRESULT _FilterBriefcase(FORMATETC* pfmte, DWORD grfKeyFlags, DWORD dwEffectsAvail,
DWORD* pdwEffects, DWORD* pdwDefaultEffect, FSMENUINFO* pfsMenuInfo);
HRESULT _FilterHDROP(FORMATETC* pfmte, DWORD grfKeyFlags, DWORD dwEffectsAvail,
DWORD* pdwEffects, DWORD* pdwDefaultEffect, FSMENUINFO* pfsMenuInfo);
HRESULT _FilterHIDA(FORMATETC* pfmte, DWORD grfKeyFlags, DWORD dwEffectsAvail,
DWORD* pdwEffects, DWORD* pdwDefaultEffect, FSMENUINFO* pfsMenuInfo);
HRESULT _FilterDeskImage(FORMATETC* pfmte, DWORD grfKeyFlags, DWORD dwEffectsAvail,
DWORD* pdwEffects, DWORD* pdwDefaultEffect, FSMENUINFO* pfsMenuInfo);
HRESULT _FilterDeskComp(FORMATETC* pfmte, DWORD grfKeyFlags, DWORD dwEffectsAvail,
DWORD* pdwEffects, DWORD* pdwDefaultEffect, FSMENUINFO* pfsMenuInfo);
HRESULT _FilterOlePackage(FORMATETC* pfmte, DWORD grfKeyFlags, DWORD dwEffectsAvail,
DWORD* pdwEffects, DWORD* pdwDefaultEffect, FSMENUINFO* pfsMenuInfo);
HRESULT _FilterOleObj(FORMATETC* pfmte, DWORD grfKeyFlags, DWORD dwEffectsAvail,
DWORD* pdwEffects, DWORD* pdwDefaultEffect, FSMENUINFO* pfsMenuInfo);
HRESULT _FilterOleLink(FORMATETC* pfmte, DWORD grfKeyFlags, DWORD dwEffectsAvail,
DWORD* pdwEffects, DWORD* pdwDefaultEffect, FSMENUINFO* pfsMenuInfo);
DWORD _FilesystemAdjustedDefaultEffect(DWORD dwCurEffectAvail);
HRESULT _GetPath(LPTSTR pszPath);
LPCITEMIDLIST _GetIDList();
DWORD _LimitDefaultEffect(DWORD dwDefEffect, DWORD dwEffectsAllowed);
DWORD _GetDefaultEffect(DWORD grfKeyState, DWORD dwCurEffectAvail, DWORD dwAllEffectAvail, DWORD dwOrigDefEffect);
DWORD _DetermineEffects(DWORD grfKeyState, DWORD *pdwEffectInOut, HMENU hmenu);
DWORD _EffectFromFolder();
typedef struct
{
CFSDropTarget *pThis;
IStream *pstmDataObj;
IStream *pstmFolderView;
} DROPTHREADPARAMS;
static void _FreeThreadParams(DROPTHREADPARAMS *pdtp);
static DWORD CALLBACK _DoDropThreadProc(void *pv);
void _DoDrop(IDataObject *pdtobj, IFolderView* pfv);
static void _AddVerbs(DWORD* pdwEffects, DWORD dwEffectAvail, DWORD dwDefEffect,
UINT idCopy, UINT idMove, UINT idLink,
DWORD dwForceEffect, FSMENUINFO* pfsMenuInfo);
void _FixUpDefaultItem(HMENU hmenu, DWORD dwDefEffect);
HRESULT _DragDropMenu(FSDRAGDROPMENUPARAM *pddm);
HRESULT _CreatePackage(IDataObject *pdtobj);
HRESULT _CreateURLDeskComp(IDataObject *pdtobj, POINTL pt);
HRESULT _CreateDeskCompImage(IDataObject *pdtobj, POINTL pt);
void _GetStateFromSite();
BOOL _IsFromSneakernetBriefcase();
BOOL _IsFromSameBriefcase();
void _MoveCopy(IDataObject *pdtobj, IFolderView* pfv, HDROP hDrop);
void _MoveSelectIcons(IDataObject *pdtobj, IFolderView* pfv, void *hNameMap, LPCTSTR pszFiles, BOOL fMove, HDROP hDrop);
LONG _cRef;
CFSFolder *_pFolder;
HWND _hwnd; // EVIL: used as a site and UI host
UINT _idCmd;
DWORD _grfKeyStateLast; // for previous DragOver/Enter
IDataObject *_pdtobj; // used durring Dragover() and DoDrop(), don't use on background thread
DWORD _dwEffectLastReturned; // stashed effect that's returned by base class's dragover
DWORD _dwEffect;
DWORD _dwData; // DTID_*
DWORD _dwEffectPreferred; // if dwData & DTID_PREFERREDEFFECT
DWORD _dwEffectFolder; // folder desktop.ini preferred effect
BOOL _fSameHwnd; // the drag source and target are the same folder
BOOL _fDragDrop; //
BOOL _fUseExactDropPoint; // Don't transform the drop point. The target knows exactly where it wants things.
BOOL _fBkDropTarget;
POINT _ptDrop;
IFolderView* _pfv;
typedef struct {
FORMATETC fmte;
HRESULT (CFSDropTarget::*pfnGetDragDropInfo)(
IN FORMATETC* pfmte,
IN DWORD grfKeyFlags,
IN DWORD dwEffectsAvail,
IN OUT DWORD* pdwEffectsUsed,
OUT DWORD* pdwDefaultEffect,
IN OUT FSMENUINFO* pfsMenuInfo);
CLIPFORMAT *pcfInit;
} _DATA_HANDLER;
// HACKHACK: C++ doesn't let you initialize statics inside a class
// definition, and also doesn't let you specify an empty
// size (i.e., rg_data_handlers[]) inside a class definition
// either, so we have to have this bogus NUM_DATA_HANDLERS
// symbol that must manually be kept in sync.
enum { NUM_DATA_HANDLERS = 16 };
static _DATA_HANDLER rg_data_handlers[NUM_DATA_HANDLERS];
static void _Init_rg_data_handlers();
private:
friend HRESULT CFSDropTarget_CreateInstance(CFSFolder* pFolder, HWND hwnd, IDropTarget** ppdt);
};
CFSDropTarget::CFSDropTarget(CFSFolder *pFolder, HWND hwnd) : _cRef(1), _hwnd(hwnd), _pFolder(pFolder), _dwEffectFolder(-1)
{
ASSERT(0 == _grfKeyStateLast);
ASSERT(NULL == _pdtobj);
ASSERT(0 == _dwEffectLastReturned);
ASSERT(0 == _dwData);
ASSERT(0 == _dwEffectPreferred);
_pFolder->AddRef();
}
CFSDropTarget::~CFSDropTarget()
{
AssertMsg(_pdtobj == NULL, TEXT("didn't get matching DragLeave, fix that bug"));
ATOMICRELEASE(_pdtobj);
ATOMICRELEASE(_pfv);
_pFolder->Release();
}
STDAPI CFSDropTarget_CreateInstance(CFSFolder* pFolder, HWND hwnd, IDropTarget** ppdt)
{
*ppdt = new CFSDropTarget(pFolder, hwnd);
return *ppdt ? S_OK : E_OUTOFMEMORY;
}
HRESULT CFSDropTarget::QueryInterface(REFIID riid, void** ppvObj)
{
static const QITAB qit[] = {
QITABENT(CFSDropTarget, IDropTarget),
QITABENT(CFSDropTarget, IObjectWithSite),
QITABENTMULTI2(CFSDropTarget, IID_IDropTargetWithDADSupport, IDropTarget),
{ 0 },
};
return QISearch(this, qit, riid, ppvObj);
}
STDMETHODIMP_(ULONG) CFSDropTarget::AddRef()
{
return InterlockedIncrement(&_cRef);
}
STDMETHODIMP_(ULONG) CFSDropTarget::Release()
{
if (InterlockedDecrement(&_cRef))
return _cRef;
delete this;
return 0;
}
void CFSDropTarget::_FreeThreadParams(DROPTHREADPARAMS *pdtp)
{
pdtp->pThis->Release();
ATOMICRELEASE(pdtp->pstmDataObj);
ATOMICRELEASE(pdtp->pstmFolderView);
LocalFree(pdtp);
}
// compute DTID_ bit flags from the data object to make format testing easier for
// DragOver() and Drop() code
STDAPI GetClipFormatFlags(IDataObject *pdtobj, DWORD *pdwData, DWORD *pdwEffectPreferred)
{
*pdwData = 0;
*pdwEffectPreferred = 0;
if (pdtobj)
{
IEnumFORMATETC *penum;
if (SUCCEEDED(pdtobj->EnumFormatEtc(DATADIR_GET, &penum)))
{
FORMATETC fmte;
ULONG celt;
while (S_OK == penum->Next(1, &fmte, &celt))
{
if (fmte.cfFormat == CF_HDROP && (fmte.tymed & TYMED_HGLOBAL))
*pdwData |= DTID_HDROP;
if (fmte.cfFormat == g_cfHIDA && (fmte.tymed & TYMED_HGLOBAL))
*pdwData |= DTID_HIDA;
if (fmte.cfFormat == g_cfNetResource && (fmte.tymed & TYMED_HGLOBAL))
*pdwData |= DTID_NETRES;
if (fmte.cfFormat == g_cfEmbeddedObject && (fmte.tymed & TYMED_ISTORAGE))
*pdwData |= DTID_EMBEDDEDOBJECT;
if (fmte.cfFormat == g_cfFileContents && (fmte.tymed & (TYMED_HGLOBAL | TYMED_ISTREAM | TYMED_ISTORAGE)))
*pdwData |= DTID_CONTENTS;
if (fmte.cfFormat == g_cfFileGroupDescriptorA && (fmte.tymed & TYMED_HGLOBAL))
*pdwData |= DTID_FDESCA;
if (fmte.cfFormat == g_cfFileGroupDescriptorW && (fmte.tymed & TYMED_HGLOBAL))
*pdwData |= DTID_FDESCW;
if ((fmte.cfFormat == g_cfPreferredDropEffect) &&
(fmte.tymed & TYMED_HGLOBAL) &&
(DROPEFFECT_NONE != (*pdwEffectPreferred = DataObj_GetDWORD(pdtobj, g_cfPreferredDropEffect, DROPEFFECT_NONE))))
{
*pdwData |= DTID_PREFERREDEFFECT;
}
#ifdef DEBUG
TCHAR szFormat[MAX_PATH];
if (GetClipboardFormatName(fmte.cfFormat, szFormat, ARRAYSIZE(szFormat)))
{
TraceMsg(TF_DRAGDROP, "CFSDropTarget - cf %s, tymed %d", szFormat, fmte.tymed);
}
else
{
TraceMsg(TF_DRAGDROP, "CFSDropTarget - cf %d, tymed %d", fmte.cfFormat, fmte.tymed);
}
#endif // DEBUG
SHFree(fmte.ptd);
}
penum->Release();
}
//
// HACK:
// Win95 always did the GetData below which can be quite expensive if
// the data is a directory structure on an ftp server etc.
// dont check for FD_LINKUI if the data object has a preferred effect
//
if ((*pdwData & (DTID_PREFERREDEFFECT | DTID_CONTENTS)) == DTID_CONTENTS)
{
if (*pdwData & DTID_FDESCA)
{
FORMATETC fmteRead = {g_cfFileGroupDescriptorA, NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL};
STGMEDIUM medium = {0};
if (S_OK == pdtobj->GetData(&fmteRead, &medium))
{
FILEGROUPDESCRIPTORA * pfgd = (FILEGROUPDESCRIPTORA *)GlobalLock(medium.hGlobal);
if (pfgd)
{
if (pfgd->cItems >= 1)
{
if (pfgd->fgd[0].dwFlags & FD_LINKUI)
*pdwData |= DTID_FD_LINKUI;
}
GlobalUnlock(medium.hGlobal);
}
ReleaseStgMedium(&medium);
}
}
else if (*pdwData & DTID_FDESCW)
{
FORMATETC fmteRead = {g_cfFileGroupDescriptorW, NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL};
STGMEDIUM medium = {0};
if (S_OK == pdtobj->GetData(&fmteRead, &medium))
{
FILEGROUPDESCRIPTORW * pfgd = (FILEGROUPDESCRIPTORW *)GlobalLock(medium.hGlobal);
if (pfgd)
{
if (pfgd->cItems >= 1)
{
if (pfgd->fgd[0].dwFlags & FD_LINKUI)
*pdwData |= DTID_FD_LINKUI;
}
GlobalUnlock(medium.hGlobal);
}
ReleaseStgMedium(&medium);
}
}
}
if (S_OK == OleQueryCreateFromData(pdtobj))
*pdwData |= DTID_OLEOBJ;
if (S_OK == OleQueryLinkFromData(pdtobj))
*pdwData |= DTID_OLELINK;
}
return S_OK; // for now always succeeds
}
STDMETHODIMP CFSDropTarget::DragEnter(IDataObject* pdtobj, DWORD grfKeyState, POINTL pt, DWORD* pdwEffect)
{
ASSERT(NULL == _pdtobj); // req DragDrop protocol, someone forgot to call DragLeave
// init our registerd data formats
IDLData_InitializeClipboardFormats();
_grfKeyStateLast = grfKeyState;
IUnknown_Set((IUnknown **)&_pdtobj, pdtobj);
GetClipFormatFlags(_pdtobj, &_dwData, &_dwEffectPreferred);
*pdwEffect = _dwEffectLastReturned = _DetermineEffects(grfKeyState, pdwEffect, NULL);
return S_OK;
}
STDMETHODIMP CFSDropTarget::DragOver(DWORD grfKeyState, POINTL pt, DWORD* pdwEffect)
{
if (_grfKeyStateLast != grfKeyState)
{
_grfKeyStateLast = grfKeyState;
*pdwEffect = _dwEffectLastReturned = _DetermineEffects(grfKeyState, pdwEffect, NULL);
}
else
{
*pdwEffect = _dwEffectLastReturned;
}
return S_OK;
}
STDMETHODIMP CFSDropTarget::DragLeave()
{
IUnknown_Set((IUnknown **)&_pdtobj, NULL);
return S_OK;
}
// init data from our site that we will need in processing the drop
void CFSDropTarget::_GetStateFromSite()
{
IShellFolderView* psfv;
if (SUCCEEDED(IUnknown_QueryService(_punkSite, SID_SFolderView, IID_PPV_ARG(IShellFolderView, &psfv))))
{
_fSameHwnd = S_OK == psfv->IsDropOnSource((IDropTarget*)this);
_fDragDrop = S_OK == psfv->GetDropPoint(&_ptDrop);
_fBkDropTarget = S_OK == psfv->IsBkDropTarget(NULL);
psfv->QueryInterface(IID_PPV_ARG(IFolderView, &_pfv));
psfv->Release();
}
}
STDMETHODIMP CFSDropTarget::Drop(IDataObject* pdtobj, DWORD grfKeyState, POINTL pt, DWORD* pdwEffect)
{
// OLE may give us a different data object (fully marshalled)
// from the one we've got on DragEnter (this is not the case on Win2k, this is a nop)
IUnknown_Set((IUnknown **)&_pdtobj, pdtobj);
_GetStateFromSite();
// note, that on the drop the mouse buttons are not down so the grfKeyState
// is not what we saw on the DragOver/DragEnter, thus we need to cache
// the grfKeyState to detect left vs right drag
//
// ASSERT(this->grfKeyStateLast == grfKeyState);
HMENU hmenu = SHLoadPopupMenu(HINST_THISDLL, POPUP_TEMPLATEDD);
DWORD dwDefEffect = _DetermineEffects(grfKeyState, pdwEffect, hmenu);
if (DROPEFFECT_NONE == dwDefEffect)
{
*pdwEffect = DROPEFFECT_NONE;
DAD_SetDragImage(NULL, NULL);
IUnknown_Set((IUnknown **)&_pdtobj, NULL);
return S_OK;
}
TCHAR szPath[MAX_PATH];
_GetPath(szPath);
// this doesn't actually do the menu if (grfKeyState MK_LBUTTON)
FSDRAGDROPMENUPARAM ddm;
ddm.dwDefEffect = dwDefEffect;
ddm.pdtobj = pdtobj;
ddm.pt = pt;
ddm.pdwEffect = pdwEffect;
ddm.ck = SHGetAssocKeysForIDList(_GetIDList(), ddm.rghk, ARRAYSIZE(ddm.rghk));
ddm.hmenu = hmenu;
ddm.grfKeyState = grfKeyState;
HRESULT hr = _DragDropMenu(&ddm);
SHRegCloseKeys(ddm.rghk, ddm.ck);
DestroyMenu(hmenu);
if (hr == S_FALSE)
{
// let callers know where this is about to go
// SHScrap cares because it needs to close the file so we can copy/move it
DataObj_SetDropTarget(pdtobj, &CLSID_ShellFSFolder);
switch (ddm.idCmd)
{
case DDIDM_CONTENTS_DESKCOMP:
hr = CreateDesktopComponents(NULL, pdtobj, _hwnd, 0, ddm.pt.x, ddm.pt.y);
break;
case DDIDM_CONTENTS_DESKURL:
hr = _CreateURLDeskComp(pdtobj, ddm.pt);
break;
case DDIDM_CONTENTS_DESKIMG:
hr = _CreateDeskCompImage(pdtobj, ddm.pt);
break;
case DDIDM_CONTENTS_COPY:
case DDIDM_CONTENTS_MOVE:
case DDIDM_CONTENTS_LINK:
hr = CFSFolder_AsyncCreateFileFromClip(_hwnd, szPath, pdtobj, pt, pdwEffect, _fBkDropTarget);
break;
case DDIDM_SCRAP_COPY:
case DDIDM_SCRAP_MOVE:
case DDIDM_DOCLINK:
hr = SHCreateBookMark(_hwnd, szPath, pdtobj, pt, pdwEffect);
break;
case DDIDM_OBJECT_COPY:
case DDIDM_OBJECT_MOVE:
hr = _CreatePackage(pdtobj);
if (E_UNEXPECTED == hr)
{
// _CreatePackage() can only expand certain types of packages
// back into files. For example, it doesn't handle CMDLINK files.
//
// If _CreatePackage() didn't recognize the stream format, we fall
// back to SHCreateBookMark(), which should create a scrap:
hr = SHCreateBookMark(_hwnd, szPath, pdtobj, pt, pdwEffect);
}
break;
case DDIDM_COPY:
case DDIDM_SYNCCOPY:
case DDIDM_SYNCCOPYTYPE:
case DDIDM_MOVE:
case DDIDM_LINK:
_dwEffect = *pdwEffect;
_idCmd = ddm.idCmd;
if (DataObj_CanGoAsync(pdtobj) || DataObj_GoAsyncForCompat(pdtobj))
{
// create another thread to avoid blocking the source thread.
DROPTHREADPARAMS *pdtp;
hr = SHLocalAlloc(sizeof(*pdtp), &pdtp);
if (SUCCEEDED(hr))
{
pdtp->pThis = this;
pdtp->pThis->AddRef();
CoMarshalInterThreadInterfaceInStream(IID_IDataObject, pdtobj, &pdtp->pstmDataObj);
CoMarshalInterThreadInterfaceInStream(IID_IFolderView, _pfv, &pdtp->pstmFolderView);
if (SHCreateThread(_DoDropThreadProc, pdtp, CTF_COINIT, NULL))
{
hr = S_OK;
}
else
{
_FreeThreadParams(pdtp);
hr = E_OUTOFMEMORY;
}
}
}
else
{
_DoDrop(pdtobj, _pfv); // synchronously
}
// in these CF_HDROP cases "Move" is always an optimized move, we delete the
// source. make sure we don't return DROPEFFECT_MOVE so the source does not
// try to do this too...
// even if we have not done anything yet since we may have
// kicked of a thread to do this
DataObj_SetDWORD(pdtobj, g_cfLogicalPerformedDropEffect, *pdwEffect);
if (DROPEFFECT_MOVE == *pdwEffect)
*pdwEffect = DROPEFFECT_NONE;
break;
}
}
IUnknown_Set((IUnknown **)&_pdtobj, NULL); // don't use this any more
if (FAILED(hr))
*pdwEffect = DROPEFFECT_NONE;
ASSERT(*pdwEffect==DROPEFFECT_COPY ||
*pdwEffect==DROPEFFECT_LINK ||
*pdwEffect==DROPEFFECT_MOVE ||
*pdwEffect==DROPEFFECT_NONE);
return hr;
}
void CFSDropTarget::_AddVerbs(DWORD* pdwEffects, DWORD dwEffectAvail, DWORD dwDefEffect,
UINT idCopy, UINT idMove, UINT idLink,
DWORD dwForceEffect, FSMENUINFO* pfsMenuInfo)
{
ASSERT(pdwEffects);
MENUITEMINFO mii;
TCHAR szCmd[MAX_PATH];
if (NULL != pfsMenuInfo)
{
mii.cbSize = sizeof(mii);
mii.dwTypeData = szCmd;
mii.fMask = MIIM_ID | MIIM_TYPE | MIIM_STATE | MIIM_DATA;
mii.fType = MFT_STRING;
}
if ((DROPEFFECT_COPY == (DROPEFFECT_COPY & dwEffectAvail)) &&
((0 == (*pdwEffects & DROPEFFECT_COPY)) || (dwForceEffect & DROPEFFECT_COPY)))
{
ASSERT(0 != idCopy);
if (NULL != pfsMenuInfo)
{
LoadString(HINST_THISDLL, idCopy + IDS_DD_FIRST, szCmd, ARRAYSIZE(szCmd));
mii.fState = MFS_ENABLED | ((DROPEFFECT_COPY == dwDefEffect) ? MFS_DEFAULT : 0);
mii.wID = idCopy;
mii.dwItemData = DROPEFFECT_COPY;
InsertMenuItem(pfsMenuInfo->hMenu, pfsMenuInfo->uCopyPos, TRUE, &mii);
pfsMenuInfo->uCopyPos++;
pfsMenuInfo->uMovePos++;
pfsMenuInfo->uLinkPos++;
}
}
if ((DROPEFFECT_MOVE == (DROPEFFECT_MOVE & dwEffectAvail)) &&
((0 == (*pdwEffects & DROPEFFECT_MOVE)) || (dwForceEffect & DROPEFFECT_MOVE)))
{
ASSERT(0 != idMove);
if (NULL != pfsMenuInfo)
{
LoadString(HINST_THISDLL, idMove + IDS_DD_FIRST, szCmd, ARRAYSIZE(szCmd));
mii.fState = MFS_ENABLED | ((DROPEFFECT_MOVE == dwDefEffect) ? MFS_DEFAULT : 0);
mii.wID = idMove;
mii.dwItemData = DROPEFFECT_MOVE;
InsertMenuItem(pfsMenuInfo->hMenu, pfsMenuInfo->uMovePos, TRUE, &mii);
pfsMenuInfo->uMovePos++;
pfsMenuInfo->uLinkPos++;
}
}
if ((DROPEFFECT_LINK == (DROPEFFECT_LINK & dwEffectAvail)) &&
((0 == (*pdwEffects & DROPEFFECT_LINK)) || (dwForceEffect & DROPEFFECT_LINK)))
{
ASSERT(0 != idLink);
if (NULL != pfsMenuInfo)
{
LoadString(HINST_THISDLL, idLink + IDS_DD_FIRST, szCmd, ARRAYSIZE(szCmd));
mii.fState = MFS_ENABLED | ((DROPEFFECT_LINK == dwDefEffect) ? MFS_DEFAULT : 0);
mii.wID = idLink;
mii.dwItemData = DROPEFFECT_LINK;
InsertMenuItem(pfsMenuInfo->hMenu, pfsMenuInfo->uLinkPos, TRUE, &mii);
pfsMenuInfo->uLinkPos++;
}
}
*pdwEffects |= dwEffectAvail;
}
// determine the default drop effect (move/copy/link) from the file type
//
// HKCR\.cda "DefaultDropEffect" = 4 // DROPEFFECT_LINK
DWORD EffectFromFileType(IDataObject *pdtobj)
{
DWORD dwDefEffect = DROPEFFECT_NONE; // 0
LPITEMIDLIST pidl;
if (SUCCEEDED(PidlFromDataObject(pdtobj, &pidl)))
{
IQueryAssociations *pqa;
if (SUCCEEDED(SHGetAssociations(pidl, (void **)&pqa)))
{
DWORD cb = sizeof(dwDefEffect);
pqa->GetData(0, ASSOCDATA_VALUE, L"DefaultDropEffect", &dwDefEffect, &cb);
pqa->Release();
}
ILFree(pidl);
}
return dwDefEffect;
}
// compute the default effect based on
// the allowed effects
// the keyboard state,
// the preferred effect that might be in the data object
// and previously computed default effect (if the above yields nothing)
DWORD CFSDropTarget::_GetDefaultEffect(DWORD grfKeyState, DWORD dwCurEffectAvail, DWORD dwAllEffectAvail, DWORD dwOrigDefEffect)
{
DWORD dwDefEffect = 0;
//
// keyboard, (explicit user input) gets first crack
//
switch (grfKeyState & (MK_CONTROL | MK_SHIFT | MK_ALT))
{
case MK_CONTROL:
dwDefEffect = DROPEFFECT_COPY;
break;
case MK_SHIFT:
dwDefEffect = DROPEFFECT_MOVE;
break;
case MK_SHIFT | MK_CONTROL:
case MK_ALT:
dwDefEffect = DROPEFFECT_LINK;
break;
default: // no modifier keys case
// if the data object contains a preferred drop effect, try to use it
DWORD dwPreferred = DataObj_GetDWORD(_pdtobj, g_cfPreferredDropEffect, DROPEFFECT_NONE) & dwAllEffectAvail;
if (DROPEFFECT_NONE == dwPreferred)
{
dwPreferred = EffectFromFileType(_pdtobj) & dwAllEffectAvail;
}
if (dwPreferred)
{
if (dwPreferred & DROPEFFECT_MOVE)
{
dwDefEffect = DROPEFFECT_MOVE;
}
else if (dwPreferred & DROPEFFECT_COPY)
{
dwDefEffect = DROPEFFECT_COPY;
}
else if (dwPreferred & DROPEFFECT_LINK)
{
dwDefEffect = DROPEFFECT_LINK;
}
}
else
{
dwDefEffect = dwOrigDefEffect;
}
break;
}
return dwDefEffect & dwCurEffectAvail;
}
HRESULT CFSDropTarget::_FilterDeskCompHDROP(FORMATETC* pfmte, DWORD grfKeyFlags, DWORD dwEffectsAvail,
DWORD* pdwEffects, DWORD* pdwDefaultEffect, FSMENUINFO* pfsMenuInfo)
{
ASSERT(pdwEffects);
HRESULT hr = S_FALSE;
if (!PolicyNoActiveDesktop() &&
!SHRestricted(REST_NOADDDESKCOMP) &&
_IsDesktopFolder())
{
hr = IsDeskCompHDrop(_pdtobj);
if (S_OK == hr)
{
DWORD dwDefEffect = 0;
DWORD dwEffectAdd = dwEffectsAvail & DROPEFFECT_LINK;
if (pdwDefaultEffect)
{
dwDefEffect = _GetDefaultEffect(grfKeyFlags, dwEffectAdd, dwEffectsAvail, DROPEFFECT_LINK);
*pdwDefaultEffect = dwDefEffect;
}
_AddVerbs(pdwEffects, dwEffectAdd, dwDefEffect, 0, 0, DDIDM_CONTENTS_DESKCOMP,
DROPEFFECT_LINK, // force add the DDIDM_CONTENTS_DESKCOMP verb
pfsMenuInfo);
}
}
return hr;
}
// see if a PIDL is scoped by a briefcaes
BOOL IsBriefcaseOrChild(LPCITEMIDLIST pidlIn)
{
BOOL bRet = FALSE;
LPITEMIDLIST pidl = ILClone(pidlIn);
if (pidl)
{
do
{
CLSID clsid;
if (SUCCEEDED(GetCLSIDFromIDList(pidl, &clsid)) &&
IsEqualCLSID(clsid, CLSID_Briefcase))
{
bRet = TRUE; // it is a briefcase
break;
}
} while (ILRemoveLastID(pidl));
ILFree(pidl);
}
return bRet;
}
// returns true if the data object represents items in a sneakernet briefcase
// (briefcase on removable media)
BOOL CFSDropTarget::_IsFromSneakernetBriefcase()
{
BOOL bRet = FALSE; // assume no
if (!_IsBriefcaseTarget())
{
STGMEDIUM medium = {0};
LPIDA pida = DataObj_GetHIDA(_pdtobj, &medium);
if (pida)
{
LPCITEMIDLIST pidlFolder = IDA_GetIDListPtr(pida, (UINT)-1);
TCHAR szSource[MAX_PATH];
if (SHGetPathFromIDList(pidlFolder, szSource))
{
// is source on removable device?
if (!PathIsUNC(szSource) && IsRemovableDrive(DRIVEID(szSource)))
{
TCHAR szTarget[MAX_PATH];
_GetPath(szTarget);
// is the target fixed media?
if (PathIsUNC(szTarget) || !IsRemovableDrive(DRIVEID(szTarget)))
{
bRet = IsBriefcaseOrChild(pidlFolder);
}
}
}
HIDA_ReleaseStgMedium(pida, &medium);
}
}
return bRet;
}
// TRUE if any folders are in hdrop
BOOL DroppingAnyFolders(HDROP hDrop)
{
TCHAR szPath[MAX_PATH];
for (UINT i = 0; DragQueryFile(hDrop, i, szPath, ARRAYSIZE(szPath)); i++)
{
if (PathIsDirectory(szPath))
return TRUE;
}
return FALSE;
}
// sneakernet case:
// dragging a file/folder from a briefcase on removable media. we special case this
// and use this as a chance to connect up this target folder with the content of the briefcase
HRESULT CFSDropTarget::_FilterSneakernetBriefcase(FORMATETC* pfmte, DWORD grfKeyFlags, DWORD dwEffectsAvail,
DWORD* pdwEffects, DWORD* pdwDefaultEffect, FSMENUINFO* pfsMenuInfo)
{
ASSERT(pdwEffects);
if (_IsFromSneakernetBriefcase())
{
// Yes; show the non-default briefcase cm
STGMEDIUM medium = {0};
FORMATETC fmte = {CF_HDROP, NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL};
if (SUCCEEDED(_pdtobj->GetData(&fmte, &medium)))
{
DWORD dwDefEffect = 0;
DWORD dwEffectAdd = DROPEFFECT_COPY & dwEffectsAvail;
if (pdwDefaultEffect)
{
dwDefEffect = _GetDefaultEffect(grfKeyFlags, dwEffectAdd, dwEffectsAvail, DROPEFFECT_COPY);
*pdwDefaultEffect = dwDefEffect;
}
_AddVerbs(pdwEffects, dwEffectAdd, dwDefEffect, DDIDM_SYNCCOPY, 0, 0, 0, pfsMenuInfo);
// Call _AddVerbs() again to force "Sync Copy of Type" as a 2nd DROPEFFECT_COPY verb:
if ((DROPEFFECT_COPY & dwEffectsAvail) &&
DroppingAnyFolders((HDROP)medium.hGlobal))
{
_AddVerbs(pdwEffects, DROPEFFECT_COPY, 0,
DDIDM_SYNCCOPYTYPE, 0, 0, DROPEFFECT_COPY, pfsMenuInfo);
}
ReleaseStgMedium(&medium);
}
}
return S_OK;
}
// returns true if the data object represents items from the same briefcase
// as this drop target
BOOL CFSDropTarget::_IsFromSameBriefcase()
{
BOOL bRet = FALSE;
STGMEDIUM medium;
FORMATETC fmteBrief = {g_cfBriefObj, NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL};
// Yes; are they from the same briefcase as the target?
if (SUCCEEDED(_pdtobj->GetData(&fmteBrief, &medium)))
{
BriefObj *pbo = (BriefObj *)GlobalLock(medium.hGlobal);
TCHAR szBriefPath[MAX_PATH], szPath[MAX_PATH];
lstrcpy(szBriefPath, BOBriefcasePath(pbo));
lstrcpy(szPath, BOFileList(pbo)); // first file in list
TCHAR szPathTgt[MAX_PATH];
_GetPath(szPathTgt);
int cch = PathCommonPrefix(szPath, szPathTgt, NULL);
bRet = (0 < cch) && (lstrlen(szBriefPath) <= cch);
GlobalUnlock(medium.hGlobal);
ReleaseStgMedium(&medium);
}
return bRet;
}
// briefcase drop target specific handling gets computed here
HRESULT CFSDropTarget::_FilterBriefcase(FORMATETC* pfmte, DWORD grfKeyFlags, DWORD dwEffectsAvail,
DWORD* pdwEffects, DWORD* pdwDefaultEffect, FSMENUINFO* pfsMenuInfo)
{
if (_IsBriefcaseTarget() && !_IsFromSameBriefcase())
{
STGMEDIUM medium = {0};
FORMATETC fmte = {CF_HDROP, NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL};
if (SUCCEEDED(_pdtobj->GetData(&fmte, &medium)))
{
DWORD dwDefEffect = DROPEFFECT_COPY;
DWORD dwEffectAdd = DROPEFFECT_COPY & dwEffectsAvail;
if (pdwDefaultEffect)
{
dwDefEffect = _GetDefaultEffect(grfKeyFlags, dwEffectAdd, dwEffectsAvail, DROPEFFECT_COPY);
*pdwDefaultEffect = dwDefEffect;
}
_AddVerbs(pdwEffects, dwEffectAdd, dwDefEffect, DDIDM_SYNCCOPY, 0, 0, 0, pfsMenuInfo);
// Call _AddVerbs() again to force "Sync Copy of Type" as a 2nd DROPEFFECT_COPY verb:
if ((DROPEFFECT_COPY & dwEffectsAvail) &&
DroppingAnyFolders((HDROP)medium.hGlobal))
{
_AddVerbs(pdwEffects, DROPEFFECT_COPY, 0,
DDIDM_SYNCCOPYTYPE, 0, 0, DROPEFFECT_COPY, pfsMenuInfo);
}
ReleaseStgMedium(&medium);
}
}
return S_OK;
}
HRESULT CFSDropTarget::_FilterHDROP(FORMATETC* pfmte, DWORD grfKeyFlags, DWORD dwEffectsAvail,
DWORD* pdwEffects, DWORD* pdwDefaultEffect, FSMENUINFO* pfsMenuInfo)
{
ASSERT(pdwEffects);
DWORD dwDefEffect = 0;
DWORD dwEffectAdd = dwEffectsAvail & (DROPEFFECT_COPY | DROPEFFECT_MOVE);
if (pdwDefaultEffect)
{
dwDefEffect = _GetDefaultEffect(grfKeyFlags, dwEffectAdd, dwEffectsAvail, _FilesystemAdjustedDefaultEffect(dwEffectAdd));
*pdwDefaultEffect = dwDefEffect;
}
_AddVerbs(pdwEffects, dwEffectAdd, dwDefEffect, DDIDM_COPY, DDIDM_MOVE, 0, 0, pfsMenuInfo);
return S_OK;
}
HRESULT CFSDropTarget::_FilterFileContents(FORMATETC* pfmte, DWORD grfKeyFlags, DWORD dwEffectsAvail,
DWORD* pdwEffects, DWORD* pdwDefaultEffect, FSMENUINFO* pfsMenuInfo)
{
ASSERT(pdwEffects);
if ((_dwData & (DTID_CONTENTS | DTID_FDESCA)) == (DTID_CONTENTS | DTID_FDESCA) ||
(_dwData & (DTID_CONTENTS | DTID_FDESCW)) == (DTID_CONTENTS | DTID_FDESCW))
{
DWORD dwEffectAdd, dwSuggestedEffect;
//
// HACK: if there is a preferred drop effect and no HIDA
// then just take the preferred effect as the available effects
// this is because we didn't actually check the FD_LINKUI bit
// back when we assembled dwData! (performance)
//
if ((_dwData & (DTID_PREFERREDEFFECT | DTID_HIDA)) == DTID_PREFERREDEFFECT)
{
dwEffectAdd = _dwEffectPreferred;
dwSuggestedEffect = _dwEffectPreferred;
}
else if (_dwData & DTID_FD_LINKUI)
{
dwEffectAdd = DROPEFFECT_LINK;
dwSuggestedEffect = DROPEFFECT_LINK;
}
else
{
dwEffectAdd = DROPEFFECT_COPY | DROPEFFECT_MOVE;
dwSuggestedEffect = DROPEFFECT_COPY;
}
dwEffectAdd &= dwEffectsAvail;
DWORD dwDefEffect = 0;
if (pdwDefaultEffect)
{
dwDefEffect = _GetDefaultEffect(grfKeyFlags, dwEffectAdd, dwEffectsAvail, dwSuggestedEffect);
*pdwDefaultEffect = dwDefEffect;
}
_AddVerbs(pdwEffects, dwEffectAdd, dwDefEffect,
DDIDM_CONTENTS_COPY, DDIDM_CONTENTS_MOVE, DDIDM_CONTENTS_LINK,
0, pfsMenuInfo);
}
return S_OK;
}
//
// Old versions of OLE have a bug where if two FORMATETCs use the same
// CLIPFORMAT, then only the first one makes it to the IEnumFORMATETC,
// even if the other parameters (such as DVASPECT) are different.
//
// This causes us problems because those other DVASPECTs might be useful.
// So if we see a FileContents with the wrong DVASPECT, sniff at the
// object to see if maybe it also contains a copy with the correct DVASPECT.
//
// This bug was fixed in 1996 on the NT side, but the Win9x side was
// not fixed. The Win9x OLE team was disbanded before the fix could
// be propagated. So we get to work around this OLE bug forever.
//
HRESULT CFSDropTarget::_FilterFileContentsOLEHack(FORMATETC* pfmte, DWORD grfKeyFlags, DWORD dwEffectsAvail,
DWORD* pdwEffects, DWORD* pdwDefaultEffect, FSMENUINFO* pfsMenuInfo)
{
FORMATETC fmte = *pfmte;
fmte.dwAspect = DVASPECT_CONTENT;
//
// Whoa, this test is so (intentionally) backwards it isn't funny.
//
// We want to see whether there is a DVASPECT_CONTENT available in
// the real object. So we first ask the object if it has a
// DVASPECT_CONTENT format already. If the answer is yes, then we
// **skip** this FORMATETC, because it will be found (or has already
// been found) by our big EnumFORMATETC loop.
//
// If the answer is NO, then maybe we're hitting an OLE bug.
// (They cache the list of available formats, but the bug is that
// their cache is broken.) Bypass the cache by actually getting the
// data. If it works, then run with it. Otherwise, I guess OLE wasn't
// kidding.
//
// Note that we do not GetData() unconditionally -- bad for perf.
// Only call GetData() after all the easy tests have failed.
//
HRESULT hr = _pdtobj->QueryGetData(&fmte);
if (hr == DV_E_FORMATETC)
{
// Maybe we are hitting the OLE bug. Try harder.
STGMEDIUM stgm = {0};
if (SUCCEEDED(_pdtobj->GetData(&fmte, &stgm)))
{
// Yup. OLE lied to us.
ReleaseStgMedium(&stgm);
hr = _FilterFileContents(&fmte, grfKeyFlags, dwEffectsAvail,
pdwEffects, pdwDefaultEffect, pfsMenuInfo);
}
else
{
// Whaddya know, OLE was telling the truth. Do nothing with this
// format.
hr = S_OK;
}
}
else
{
// Either QueryGetData() failed in some bizarre way
// (in which case we ignore the problem) or the QueryGetData
// succeeded, in which case we ignore this FORMATETC since
// the big enumeration will find (or has already found) the
// DVASPECT_CONTENT.
hr = S_OK;
}
return hr;
}
HRESULT CFSDropTarget::_FilterHIDA(FORMATETC* pfmte, DWORD grfKeyFlags, DWORD dwEffectsAvail,
DWORD* pdwEffects, DWORD* pdwDefaultEffect, FSMENUINFO* pfsMenuInfo)
{
ASSERT(pdwEffects);
DWORD dwDefEffect = 0;
DWORD dwEffectAdd = DROPEFFECT_LINK & dwEffectsAvail;
// NOTE: we only add a HIDA default effect if HDROP isn't going to add a default
// effect. This preserves shell behavior with file system data objects without
// requiring us to change the enumerator order in CIDLDataObj. When we do change
// the enumerator order, we can remove this special case:
if (pdwDefaultEffect &&
((0 == (_dwData & DTID_HDROP)) ||
(0 == _GetDefaultEffect(grfKeyFlags,
dwEffectsAvail & (DROPEFFECT_COPY | DROPEFFECT_MOVE),
dwEffectsAvail,
_FilesystemAdjustedDefaultEffect(dwEffectsAvail & (DROPEFFECT_COPY | DROPEFFECT_MOVE))))))
{
dwDefEffect = _GetDefaultEffect(grfKeyFlags, dwEffectAdd, dwEffectsAvail, DROPEFFECT_LINK);
*pdwDefaultEffect = dwDefEffect;
}
_AddVerbs(pdwEffects, dwEffectAdd, dwDefEffect, 0, 0, DDIDM_LINK, 0, pfsMenuInfo);
return S_OK;
}
// {F20DA720-C02F-11CE-927B-0800095AE340}
const GUID CLSID_CPackage = {0xF20DA720L, 0xC02F, 0x11CE, 0x92, 0x7B, 0x08, 0x00, 0x09, 0x5A, 0xE3, 0x40};
// old packager guid...
// {0003000C-0000-0000-C000-000000000046}
const GUID CLSID_OldPackage = {0x0003000CL, 0x0000, 0x0000, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46};
HRESULT CFSDropTarget::_FilterOlePackage(FORMATETC* pfmte, DWORD grfKeyFlags, DWORD dwEffectsAvail,
DWORD* pdwEffects, DWORD* pdwDefaultEffect, FSMENUINFO* pfsMenuInfo)
{
ASSERT(pdwEffects);
HRESULT hr = S_FALSE;
if (pdwDefaultEffect)
{
*pdwDefaultEffect = 0;
}
FORMATETC fmte = {g_cfObjectDescriptor, NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL};
STGMEDIUM medium = {0};
if (SUCCEEDED(_pdtobj->GetData(&fmte, &medium)))
{
// we've got an object descriptor
OBJECTDESCRIPTOR* pOD = (OBJECTDESCRIPTOR*) GlobalLock(medium.hGlobal);
if (pOD)
{
if (IsEqualCLSID(CLSID_OldPackage, pOD->clsid) ||
IsEqualCLSID(CLSID_CPackage, pOD->clsid))
{
// This is a package - proceed
DWORD dwDefEffect = 0;
DWORD dwEffectAdd = (DROPEFFECT_COPY | DROPEFFECT_MOVE) & dwEffectsAvail;
if (pdwDefaultEffect)
{
dwDefEffect = _GetDefaultEffect(grfKeyFlags, dwEffectAdd, dwEffectsAvail, DROPEFFECT_COPY);
*pdwDefaultEffect = dwDefEffect;
}
_AddVerbs(pdwEffects, dwEffectAdd, dwDefEffect,
DDIDM_OBJECT_COPY, DDIDM_OBJECT_MOVE, 0,
0, pfsMenuInfo);
hr = S_OK;
}
GlobalUnlock(medium.hGlobal);
}
ReleaseStgMedium(&medium);
}
return hr;
}
// REARCHITECT:
// This code has lots of problems. We need to fix this the text time we touch this code
// outside of ship mode. TO FIX:
// 1. Use SHAnsiToUnicode(CP_UTF8, ) to convert pszHTML to unicode. This will allow international
// paths to work.
// 2. Obey the selected range.
// 3. Use MSHTML to get the image. You can have trident parse the HTML via IHTMLTxtRange::pasteHTML.
// MS HTML has a special collection of images. Ask for the first image in that collection, or
// the first image in that collection within the selected range. (#1 isn't needed with this)
BOOL ExtractImageURLFromCFHTML(IN LPSTR pszHTML, IN SIZE_T cbHTMLSize, OUT LPSTR szImg, IN DWORD dwSize)
{
BOOL fSucceeded = FALSE;
// To avoid going nuts, only look at the first 64K of the HTML.
// (Important on Win64 because StrCpyNA doesn't support more than 4GB.)
if (cbHTMLSize > 0xFFFF)
cbHTMLSize = 0xFFFF;
// NT #391669: pszHTML isn't terminated, so terminate it now.
LPSTR pszCopiedHTML = (LPSTR) LocalAlloc(LPTR, cbHTMLSize + 1);
if (pszCopiedHTML)
{
LPSTR szTemp;
DWORD dwLen = dwSize;
BOOL bRet = TRUE;
StrCpyNA(pszCopiedHTML, pszHTML, (int)(cbHTMLSize + 1));
//DANGER WILL ROBINSON:
// HTML is comming in as UFT-8 encoded. Neither Unicode or Ansi,
// We've got to do something.... I'm going to party on it as if it were
// Ansi. This code will choke on escape sequences.....
//Find the base URL
//Locate <!--StartFragment-->
//Read the <IMG SRC="
//From there to the "> should be the Image URL
//Determine if it's an absolute or relative URL
//If relative, append to BASE url. You may need to lop off from the
// last delimiter to the end of the string.
//Pull out the SourceURL
LPSTR szBase = StrStrIA(pszCopiedHTML,"SourceURL:"); // Point to the char after :
if (szBase)
{
szBase += sizeof("SourceURL:")-1;
//Since each line can be terminated by a CR, CR/LF or LF check each case...
szTemp = StrChrA(szBase,'\n');
if (!szTemp)
szTemp = StrChrA(szBase,'\r');
if (szTemp)
*szTemp = '\0';
szTemp++;
}
else
szTemp = pszCopiedHTML;
//Pull out the Img Src
LPSTR pszImgSrc = StrStrIA(szTemp,"IMG");
if (pszImgSrc != NULL)
{
pszImgSrc = StrStrIA(pszImgSrc,"SRC");
if (pszImgSrc != NULL)
{
LPSTR pszImgSrcOrig = pszImgSrc;
pszImgSrc = StrChrA(pszImgSrc,'\"');
if (pszImgSrc)
{
pszImgSrc++; // Skip over the quote at the beginning of the src path.
szTemp = StrChrA(pszImgSrc,'\"'); // Find the end of the path.
}
else
{
LPSTR pszTemp1;
LPSTR pszTemp2;
pszImgSrc = StrChrA(pszImgSrcOrig,'=');
pszImgSrc++; // Skip past the equals to the first char in the path.
// Someday we may need to handle spaces between '=' and the path.
pszTemp1 = StrChrA(pszImgSrc,' '); // Since the path doesn't have quotes around it, assume a space will terminate it.
pszTemp2 = StrChrA(pszImgSrc,'>'); // Since the path doesn't have quotes around it, assume a space will terminate it.
szTemp = pszTemp1; // Assume quote terminates path.
if (!pszTemp1)
szTemp = pszTemp2; // Use '>' if quote not found.
if (pszTemp1 && pszTemp2 && (pszTemp2 < pszTemp1))
szTemp = pszTemp2; // Change to having '>' terminate path if both exist and it comes first.
}
*szTemp = '\0'; // Terminate path.
//At this point, I've reduced the 2 important strings. Now see if I need to
//Join them.
//If this fails, then we don't have a full URL, Only a relative.
if (!UrlIsA(pszImgSrc,URLIS_URL) && szBase)
{
if (SUCCEEDED(UrlCombineA(szBase, pszImgSrc, szImg, &dwLen,0)))
fSucceeded = TRUE;
}
else
{
if (lstrlenA(pszImgSrc) <= (int)dwSize)
lstrcpyA(szImg, pszImgSrc);
fSucceeded = TRUE;
}
}
}
LocalFree(pszCopiedHTML);
}
return fSucceeded;
}
HRESULT CFSDropTarget::_FilterDeskImage(FORMATETC* pfmte, DWORD grfKeyFlags, DWORD dwEffectsAvail,
DWORD* pdwEffects, DWORD* pdwDefaultEffect, FSMENUINFO* pfsMenuInfo)
{
ASSERT(pdwEffects);
HRESULT hr = S_FALSE;
if (pdwDefaultEffect)
{
*pdwDefaultEffect = 0;
}
if (!PolicyNoActiveDesktop() &&
!SHRestricted(REST_NOADDDESKCOMP) &&
_IsDesktopFolder())
{
FORMATETC fmte = {g_cfHTML, NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL};
STGMEDIUM medium = {0};
if (SUCCEEDED(_pdtobj->GetData(&fmte, &medium)))
{
//DANGER WILL ROBINSON:
//HTML is UTF-8, a mostly ANSI cross of ANSI and Unicode. Play with
// it as is it were ANSI. Find a way to escape the sequences...
CHAR *pszData = (CHAR*) GlobalLock(medium.hGlobal);
if (pszData)
{
CHAR szUrl[MAX_URL_STRING];
if (ExtractImageURLFromCFHTML(pszData, GlobalSize(medium.hGlobal), szUrl, ARRAYSIZE(szUrl)))
{
// The HTML contains an image tag - carry on...
DWORD dwDefEffect = 0;
DWORD dwEffectAdd = DROPEFFECT_LINK; // NOTE: ignoring dwEffectsAvail!
if (pdwDefaultEffect)
{
dwDefEffect = _GetDefaultEffect(grfKeyFlags, dwEffectAdd,
dwEffectsAvail | DROPEFFECT_LINK, DROPEFFECT_LINK);
*pdwDefaultEffect = dwDefEffect;
}
_AddVerbs(pdwEffects, dwEffectAdd, dwDefEffect,
0, 0, DDIDM_CONTENTS_DESKIMG,
0, pfsMenuInfo);
hr = S_OK;
}
GlobalUnlock(medium.hGlobal);
}
ReleaseStgMedium(&medium);
}
}
return hr;
}
HRESULT CFSDropTarget::_FilterDeskComp(FORMATETC* pfmte, DWORD grfKeyFlags, DWORD dwEffectsAvail,
DWORD* pdwEffects, DWORD* pdwDefaultEffect, FSMENUINFO* pfsMenuInfo)
{
ASSERT(pdwEffects);
HRESULT hr = S_FALSE;
if (pdwDefaultEffect)
{
*pdwDefaultEffect = 0;
}
if (!PolicyNoActiveDesktop() &&
!SHRestricted(REST_NOADDDESKCOMP) &&
_IsDesktopFolder())
{
FORMATETC fmte = {g_cfShellURL, NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL};
STGMEDIUM medium = {0};
if (SUCCEEDED(_pdtobj->GetData(&fmte, &medium)))
{
// DANGER WILL ROBINSON:
// HTML is UTF-8, a mostly ANSI cross of ANSI and Unicode. Play with
// it as is it were ANSI. Find a way to escape the sequences...
CHAR *pszData = (CHAR*) GlobalLock(medium.hGlobal);
if (pszData)
{
int nScheme = GetUrlSchemeA(pszData);
if ((nScheme != URL_SCHEME_INVALID) && (nScheme != URL_SCHEME_FTP))
{
// This is an internet scheme - carry on...
DWORD dwDefEffect = 0;
DWORD dwEffectAdd = DROPEFFECT_LINK & dwEffectsAvail;
if (pdwDefaultEffect)
{
dwDefEffect = _GetDefaultEffect(grfKeyFlags, dwEffectAdd, dwEffectsAvail, DROPEFFECT_LINK);
*pdwDefaultEffect = dwDefEffect;
}
_AddVerbs(pdwEffects, dwEffectAdd, dwDefEffect,
0, 0, DDIDM_CONTENTS_DESKURL,
DROPEFFECT_LINK, // force add this verb
pfsMenuInfo);
hr = S_OK;
}
GlobalUnlock(medium.hGlobal);
}
ReleaseStgMedium(&medium);
}
}
return hr;
}
HRESULT CFSDropTarget::_FilterOleObj(FORMATETC* pfmte, DWORD grfKeyFlags, DWORD dwEffectsAvail,
DWORD* pdwEffects, DWORD* pdwDefaultEffect, FSMENUINFO* pfsMenuInfo)
{
ASSERT(pdwEffects);
HRESULT hr = S_FALSE;
if (_dwData & DTID_OLEOBJ)
{
DWORD dwDefEffect = 0;
DWORD dwEffectAdd = (DROPEFFECT_COPY | DROPEFFECT_MOVE) & dwEffectsAvail;
if (pdwDefaultEffect)
{
dwDefEffect = _GetDefaultEffect(grfKeyFlags, dwEffectAdd, dwEffectsAvail, DROPEFFECT_COPY);
*pdwDefaultEffect = dwDefEffect;
}
_AddVerbs(pdwEffects, dwEffectAdd, dwDefEffect, DDIDM_SCRAP_COPY, DDIDM_SCRAP_MOVE, 0, 0, pfsMenuInfo);
hr = S_OK;
}
return hr;
}
HRESULT CFSDropTarget::_FilterOleLink(FORMATETC* pfmte, DWORD grfKeyFlags, DWORD dwEffectsAvail,
DWORD* pdwEffects, DWORD* pdwDefaultEffect, FSMENUINFO* pfsMenuInfo)
{
ASSERT(pdwEffects);
HRESULT hr = S_FALSE;
if (_dwData & DTID_OLELINK)
{
DWORD dwDefEffect = 0;
DWORD dwEffectAdd = DROPEFFECT_LINK & dwEffectsAvail;
if (pdwDefaultEffect)
{
dwDefEffect = _GetDefaultEffect(grfKeyFlags, dwEffectAdd, dwEffectsAvail, DROPEFFECT_LINK);
*pdwDefaultEffect = dwDefEffect;
}
_AddVerbs(pdwEffects, dwEffectAdd, dwDefEffect, 0, 0, DDIDM_DOCLINK, 0, pfsMenuInfo);
hr = S_OK;
}
return hr;
}
HRESULT CFSDropTarget::_CreateURLDeskComp(IDataObject *pdtobj, POINTL pt)
{
// This code should only be entered if DDIDM_CONTENTS_DESKURL was added to the menu,
// and it has these checks:
ASSERT(!PolicyNoActiveDesktop() &&
!SHRestricted(REST_NOADDDESKCOMP) &&
_IsDesktopFolder());
STGMEDIUM medium = {0};
FORMATETC fmte = {g_cfShellURL, NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL};
HRESULT hr = pdtobj->GetData(&fmte, &medium);
if (SUCCEEDED(hr))
{
//DANGER WILL ROBINSON:
//HTML is UTF-8, a mostly ANSI cross of ANSI and Unicode. Play with
// it as is it were ANSI. Find a way to escape the sequences...
CHAR *pszData = (CHAR*) GlobalLock(medium.hGlobal);
if (pszData)
{
int nScheme = GetUrlSchemeA(pszData);
if ((nScheme != URL_SCHEME_INVALID) && (nScheme != URL_SCHEME_FTP))
{
// This is an internet scheme - URL
hr = CreateDesktopComponents(pszData, NULL, _hwnd, DESKCOMP_URL, pt.x, pt.y);
}
GlobalUnlock(medium.hGlobal);
}
else
{
hr = E_FAIL;
}
ReleaseStgMedium(&medium);
}
return hr;
}
HRESULT CFSDropTarget::_CreateDeskCompImage(IDataObject *pdtobj, POINTL pt)
{
ASSERT(!PolicyNoActiveDesktop() &&
!SHRestricted(REST_NOADDDESKCOMP) &&
_IsDesktopFolder());
FORMATETC fmte = {g_cfHTML, NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL};
STGMEDIUM medium = {0};
HRESULT hr = pdtobj->GetData(&fmte, &medium);
if (SUCCEEDED(hr))
{
//DANGER WILL ROBINSON:
//HTML is UTF-8, a mostly ANSI cross of ANSI and Unicode. Play with
// it as is it were ANSI. Find a way to escape the sequences...
CHAR *pszData = (CHAR*) GlobalLock(medium.hGlobal);
if (pszData)
{
CHAR szUrl[MAX_URL_STRING];
if (ExtractImageURLFromCFHTML(pszData, GlobalSize(medium.hGlobal), szUrl, ARRAYSIZE(szUrl)))
{
// The HTML contains an image tag - carry on...
ADDTODESKTOP *pToAD;
hr = SHLocalAlloc(sizeof(*pToAD), &pToAD);
if (SUCCEEDED(hr))
{
pToAD->hwnd = _hwnd;
lstrcpyA(pToAD->szUrl, szUrl);
pToAD->dwFlags = DESKCOMP_IMAGE;
pToAD->pt = pt;
if (SHCreateThread(AddToActiveDesktopThreadProc, pToAD, CTF_COINIT, NULL))
{
hr = S_OK;
}
else
{
LocalFree(pToAD);
hr = E_OUTOFMEMORY;
}
}
}
else
{
hr = E_FAIL;
}
GlobalUnlock(medium.hGlobal);
}
else
hr = E_FAIL;
ReleaseStgMedium(&medium);
}
return hr;
}
//
// read byte by byte until we hit the null terminating char
// return: the number of bytes read
//
HRESULT StringReadFromStream(IStream* pstm, LPSTR pszBuf, UINT cchBuf)
{
UINT cch = 0;
do {
pstm->Read(pszBuf, sizeof(CHAR), NULL);
cch++;
} while (*pszBuf++ && cch <= cchBuf);
return cch;
}
HRESULT CopyStreamToFile(IStream* pstmSrc, LPCTSTR pszFile, ULONGLONG ullFileSize)
{
IStream *pstmFile;
HRESULT hr = SHCreateStreamOnFile(pszFile, STGM_CREATE | STGM_WRITE | STGM_SHARE_DENY_WRITE, &pstmFile);
if (SUCCEEDED(hr))
{
hr = CopyStreamUI(pstmSrc, pstmFile, NULL, ullFileSize);
pstmFile->Release();
}
return hr;
}
HRESULT CFSDropTarget::_CreatePackage(IDataObject *pdtobj)
{
ILockBytes* pLockBytes;
HRESULT hr = CreateILockBytesOnHGlobal(NULL, TRUE, &pLockBytes);
if (SUCCEEDED(hr))
{
STGMEDIUM medium;
medium.tymed = TYMED_ISTORAGE;
hr = StgCreateDocfileOnILockBytes(pLockBytes,
STGM_DIRECT | STGM_READWRITE | STGM_CREATE |
STGM_SHARE_EXCLUSIVE, 0, &medium.pstg);
if (SUCCEEDED(hr))
{
FORMATETC fmte = {g_cfEmbeddedObject, NULL, DVASPECT_CONTENT, -1, TYMED_ISTORAGE};
hr = pdtobj->GetDataHere(&fmte, &medium);
if (SUCCEEDED(hr))
{
IStream* pstm;
#ifdef DEBUG
STATSTG stat;
if (SUCCEEDED(medium.pstg->Stat(&stat, STATFLAG_NONAME)))
{
ASSERT(IsEqualCLSID(CLSID_OldPackage, stat.clsid) ||
IsEqualCLSID(CLSID_CPackage, stat.clsid));
}
#endif // DEBUG
#define PACKAGER_ICON 2
#define PACKAGER_CONTENTS L"\001Ole10Native"
#define PACKAGER_EMBED_TYPE 3
hr = medium.pstg->OpenStream(PACKAGER_CONTENTS, 0,
STGM_DIRECT | STGM_READWRITE | STGM_SHARE_EXCLUSIVE,
0, &pstm);
if (SUCCEEDED(hr))
{
DWORD dw;
WORD w;
CHAR szName[MAX_PATH];
CHAR szTemp[MAX_PATH];
if (SUCCEEDED(pstm->Read(&dw, sizeof(dw), NULL)) && // pkg size
SUCCEEDED(pstm->Read(&w, sizeof(w), NULL)) && // pkg appearance
(PACKAGER_ICON == w) &&
SUCCEEDED(StringReadFromStream(pstm, szName, ARRAYSIZE(szName))) &&
SUCCEEDED(StringReadFromStream(pstm, szTemp, ARRAYSIZE(szTemp))) && // icon path
SUCCEEDED(pstm->Read(&w, sizeof(w), NULL)) && // icon index
SUCCEEDED(pstm->Read(&w, sizeof(w), NULL)) && // panetype
(PACKAGER_EMBED_TYPE == w) &&
SUCCEEDED(pstm->Read(&dw, sizeof(dw), NULL)) && // filename size
SUCCEEDED(pstm->Read(szTemp, dw, NULL)) && // filename
SUCCEEDED(pstm->Read(&dw, sizeof(dw), NULL))) // get file size
{
// The rest of the stream is the file contents
TCHAR szPath[MAX_PATH], szBase[MAX_PATH], szDest[MAX_PATH];
_GetPath(szPath);
SHAnsiToTChar(szName, szBase, ARRAYSIZE(szBase));
PathAppend(szPath, szBase);
PathYetAnotherMakeUniqueName(szDest, szPath, NULL, szBase);
TraceMsg(TF_GENERAL, "CFSIDLDropTarget pkg: %s", szDest);
hr = CopyStreamToFile(pstm, szDest, dw);
if (SUCCEEDED(hr))
{
SHChangeNotify(SHCNE_CREATE, SHCNF_PATH, szDest, NULL);
if (_fBkDropTarget && _hwnd)
{
PositionFileFromDrop(_hwnd, szDest, NULL);
}
}
}
else
{
hr = E_UNEXPECTED;
}
pstm->Release();
}
}
medium.pstg->Release();
}
pLockBytes->Release();
}
return hr;
}
HRESULT CFSDropTarget::_GetPath(LPTSTR pszPath)
{
return _pFolder->_GetPath(pszPath);
}
LPCITEMIDLIST CFSDropTarget::_GetIDList()
{
return _pFolder->_GetIDList();
}
DWORD CFSDropTarget::_EffectFromFolder()
{
if (-1 == _dwEffectFolder)
{
_dwEffectFolder = DROPEFFECT_NONE; // re-set to nothing (0)
TCHAR szPath[MAX_PATH];
// add a simple pathisroot check here to prevent it from hitting the disk (mostly floppy)
// when we want the dropeffect probe to be fast (sendto, hovering over drives in view).
// its not likely that we'll want to modify the root's drop effect, and this still allows
// dropeffect modification on floppy subfolders.
if (SUCCEEDED(_GetPath(szPath)) && !PathIsRoot(szPath) && PathAppend(szPath, TEXT("desktop.ini")))
{
_dwEffectFolder = GetPrivateProfileInt(STRINI_CLASSINFO, TEXT("DefaultDropEffect"), 0, szPath);
}
}
return _dwEffectFolder;
}
BOOL AllRegisteredPrograms(HDROP hDrop)
{
TCHAR szPath[MAX_PATH];
for (UINT i = 0; DragQueryFile(hDrop, i, szPath, ARRAYSIZE(szPath)); i++)
{
if (!PathIsRegisteredProgram(szPath))
return FALSE;
}
return TRUE;
}
BOOL IsBriefcaseRoot(IDataObject *pdtobj)
{
BOOL bRet = FALSE;
STGMEDIUM medium;
LPIDA pida = DataObj_GetHIDA(pdtobj, &medium);
if (pida)
{
// Is there a briefcase root in this pdtobj?
IShellFolder2 *psf;
if (SUCCEEDED(SHBindToObject(NULL, IID_X_PPV_ARG(IShellFolder2, IDA_GetIDListPtr(pida, (UINT)-1), &psf))))
{
for (UINT i = 0; i < pida->cidl; i++)
{
CLSID clsid;
bRet = SUCCEEDED(GetItemCLSID(psf, IDA_GetIDListPtr(pida, i), &clsid)) &&
IsEqualCLSID(clsid, CLSID_Briefcase);
if (bRet)
break;
}
psf->Release();
}
HIDA_ReleaseStgMedium(pida, &medium);
}
return bRet;
}
//
// the "default effect" defines what will be choosen out of the allowed effects
//
// If the data object does NOT contain HDROP -> "none"
// else if the source data object has a default drop effect folder list (maybe based on sub folderness)
// else if the source is root or registered progam -> "link"
// else if this is within a volume -> "move"
// else if this is a briefcase -> "move"
// else -> "copy"
//
DWORD CFSDropTarget::_FilesystemAdjustedDefaultEffect(DWORD dwCurEffectAvail)
{
DWORD dwDefEffect = DROPEFFECT_NONE;
FORMATETC fmte = {CF_HDROP, NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL};
STGMEDIUM medium = {0};
if (SUCCEEDED(_pdtobj->GetData(&fmte, &medium)))
{
TCHAR szPath[MAX_PATH];
DragQueryFile((HDROP) medium.hGlobal, 0, szPath, ARRAYSIZE(szPath)); // focused item
// DROPEFFECTFOLDERLIST allows the source of the data
// to specify the desired drop effect for items under
// certain parts of the name space.
//
// cd-burning does this to avoid the default move/copy computation
// that would kick in for cross volume CD burning/staging area transfers
FORMATETC fmteDropFolders = {g_cfDropEffectFolderList, NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL};
STGMEDIUM mediumDropFolders = {0};
if (SUCCEEDED(_pdtobj->GetData(&fmteDropFolders, &mediumDropFolders)))
{
DROPEFFECTFOLDERLIST *pdefl = (DROPEFFECTFOLDERLIST*)GlobalLock(mediumDropFolders.hGlobal);
if (pdefl)
{
// get the default effect from the list -- in the staging area case this is DROPEFFECT_COPY
// so its a copy even if the staging area and source are on the same volume.
dwDefEffect = pdefl->dwDefaultDropEffect;
for (INT i = 0; i < pdefl->cFolders; i++)
{
// some folders are excluded, for example if you move a file from one part of the staging
// area to another we override (to DROPEFFECT_MOVE in this case).
if (PathIsEqualOrSubFolder(pdefl->aFolders[i].wszPath, szPath))
{
dwDefEffect = pdefl->aFolders[i].dwDropEffect;
break;
}
}
GlobalUnlock(pdefl);
}
ReleaseStgMedium(&mediumDropFolders);
}
if (DROPEFFECT_NONE == dwDefEffect)
{
dwDefEffect = _EffectFromFolder();
}
// If we didn't get a drop effect (==0) then lets fall back to the old checks
if (DROPEFFECT_NONE == dwDefEffect)
{
TCHAR szFolder[MAX_PATH];
_GetPath(szFolder);
// drive/UNC roots and installed programs get link
if (PathIsRoot(szPath) || AllRegisteredPrograms((HDROP)medium.hGlobal))
{
dwDefEffect = DROPEFFECT_LINK;
}
else if (PathIsSameRoot(szPath, szFolder))
{
dwDefEffect = DROPEFFECT_MOVE;
}
else if (IsBriefcaseRoot(_pdtobj))
{
// briefcase default to move even accross volumes
dwDefEffect = DROPEFFECT_MOVE;
}
else
{
dwDefEffect = DROPEFFECT_COPY;
}
}
ReleaseStgMedium(&medium);
}
else if (SUCCEEDED(_pdtobj->QueryGetData(&fmte)))
{
// but QueryGetData() succeeds!
// this means this data object has HDROP but can't
// provide it until it is dropped. Let's assume we are copying.
dwDefEffect = DROPEFFECT_COPY;
}
// Switch default verb if the dwCurEffectAvail hint suggests that we picked an
// unavailable effect (this code applies to MOVE and COPY only):
dwCurEffectAvail &= (DROPEFFECT_MOVE | DROPEFFECT_COPY);
if ((DROPEFFECT_MOVE == dwDefEffect) && (DROPEFFECT_COPY == dwCurEffectAvail))
{
// If we were going to return MOVE, and only COPY is available, return COPY:
dwDefEffect = DROPEFFECT_COPY;
}
else if ((DROPEFFECT_COPY == dwDefEffect) && (DROPEFFECT_MOVE == dwCurEffectAvail))
{
// If we were going to return COPY, and only MOVE is available, return MOVE:
dwDefEffect = DROPEFFECT_MOVE;
}
return dwDefEffect;
}
//
// make sure that the default effect is among the allowed effects
//
DWORD CFSDropTarget::_LimitDefaultEffect(DWORD dwDefEffect, DWORD dwEffectsAllowed)
{
if (dwDefEffect & dwEffectsAllowed)
return dwDefEffect;
if (dwEffectsAllowed & DROPEFFECT_COPY)
return DROPEFFECT_COPY;
if (dwEffectsAllowed & DROPEFFECT_MOVE)
return DROPEFFECT_MOVE;
if (dwEffectsAllowed & DROPEFFECT_LINK)
return DROPEFFECT_LINK;
return DROPEFFECT_NONE;
}
// Handy abbreviation
#define TYMED_ALLCONTENT (TYMED_HGLOBAL | TYMED_ISTREAM | TYMED_ISTORAGE)
// Use FSDH for registered clipboard formats (anything of the form g_cf*)
// Use _FSDH for predefined clipboard formats (like CF_HDROP or 0)
// Generate the _DATA_HANDLER array
#define FSDH(pfn, cf, dva, tymed) { { 0, NULL, dva, -1, tymed }, pfn, &cf }
#define _FSDH(pfn, cf, dva, tymed) { { (CLIPFORMAT)cf, NULL, dva, -1, tymed }, pfn, NULL }
// NOTE: the order is important (particularly for multiple entries with the same FORMATETC)
CFSDropTarget::_DATA_HANDLER
CFSDropTarget::rg_data_handlers[NUM_DATA_HANDLERS] = {
FSDH(_FilterFileContents, g_cfFileGroupDescriptorW, DVASPECT_CONTENT, TYMED_HGLOBAL),
FSDH(_FilterFileContentsOLEHack, g_cfFileGroupDescriptorW, DVASPECT_LINK, TYMED_HGLOBAL),
FSDH(_FilterFileContents, g_cfFileGroupDescriptorA, DVASPECT_CONTENT, TYMED_HGLOBAL),
FSDH(_FilterFileContentsOLEHack, g_cfFileGroupDescriptorA, DVASPECT_LINK, TYMED_HGLOBAL),
FSDH(_FilterFileContents, g_cfFileContents, DVASPECT_CONTENT, TYMED_ALLCONTENT),
FSDH(_FilterFileContentsOLEHack, g_cfFileContents, DVASPECT_LINK, TYMED_ALLCONTENT),
_FSDH(_FilterBriefcase, CF_HDROP, DVASPECT_CONTENT, TYMED_HGLOBAL),
_FSDH(_FilterSneakernetBriefcase, CF_HDROP, DVASPECT_CONTENT, TYMED_HGLOBAL),
_FSDH(_FilterHDROP, CF_HDROP, DVASPECT_CONTENT, TYMED_HGLOBAL),
_FSDH(_FilterDeskCompHDROP, CF_HDROP, DVASPECT_CONTENT, TYMED_HGLOBAL),
FSDH(_FilterHIDA, g_cfHIDA, DVASPECT_CONTENT, TYMED_HGLOBAL),
FSDH(_FilterOlePackage, g_cfEmbeddedObject, DVASPECT_CONTENT, TYMED_ISTORAGE),
FSDH(_FilterDeskImage, g_cfHTML, DVASPECT_CONTENT, TYMED_HGLOBAL),
FSDH(_FilterDeskComp, g_cfShellURL, DVASPECT_CONTENT, TYMED_HGLOBAL),
_FSDH(_FilterOleObj, 0, DVASPECT_CONTENT, TYMED_HGLOBAL),
_FSDH(_FilterOleLink, 0, DVASPECT_CONTENT, TYMED_HGLOBAL),
};
// Note that it's safe to race with another thread in this code
// since the function is idemponent. (Call it as many times as you
// like -- only the first time through actually does anything.)
void CFSDropTarget::_Init_rg_data_handlers()
{
for (int i = 0; i < ARRAYSIZE(rg_data_handlers); i++)
{
// If this assertion fires, then you have to change the value of
// NUM_DATA_HANDLERS to match the number of entries in the array
// definition.
ASSERT(rg_data_handlers[i].fmte.tymed);
if (rg_data_handlers[i].pcfInit)
{
rg_data_handlers[i].fmte.cfFormat = *rg_data_handlers[i].pcfInit;
}
}
}
//
// returns the default effect.
// also modifies *pdwEffectInOut to indicate "available" operations.
//
DWORD CFSDropTarget::_DetermineEffects(DWORD grfKeyState, DWORD *pdwEffectInOut, HMENU hmenu)
{
DWORD dwDefaultEffect = DROPEFFECT_NONE;
DWORD dwEffectsUsed = DROPEFFECT_NONE;
_Init_rg_data_handlers();
// Loop through formats, factoring in both the order of the enumerator and
// the order of our rg_data_handlers to determine the default effect
// (and possibly, to create the drop context menu)
FSMENUINFO fsmi = { hmenu, 0, 0, 0 };
IEnumFORMATETC *penum;
AssertMsg((NULL != _pdtobj), TEXT("CFSDropTarget::_DetermineEffects() _pdtobj is NULL but we need it. this=%#08lx"), this);
if (_pdtobj && SUCCEEDED(_pdtobj->EnumFormatEtc(DATADIR_GET, &penum)))
{
FORMATETC fmte;
ULONG celt;
while (penum->Next(1, &fmte, &celt) == S_OK)
{
for (int i = 0; i < ARRAYSIZE(rg_data_handlers); i++)
{
if (rg_data_handlers[i].fmte.cfFormat == fmte.cfFormat &&
rg_data_handlers[i].fmte.dwAspect == fmte.dwAspect &&
(rg_data_handlers[i].fmte.tymed & fmte.tymed))
{
// keep passing dwDefaultEffect until someone computes one, this
// lets the first guy that figures out the default be the default
(this->*(rg_data_handlers[i].pfnGetDragDropInfo))(
&fmte, grfKeyState, *pdwEffectInOut, &dwEffectsUsed,
(DROPEFFECT_NONE == dwDefaultEffect) ? &dwDefaultEffect : NULL,
hmenu ? &fsmi : NULL);
}
}
SHFree(fmte.ptd);
}
penum->Release();
}
// Loop through the rg_data_handlers that don't have an associated clipboard format last
for (int i = 0; i < ARRAYSIZE(rg_data_handlers); i++)
{
if (0 == rg_data_handlers[i].fmte.cfFormat)
{
// if default effect is still not computed continue to pass that
(this->*(rg_data_handlers[i].pfnGetDragDropInfo))(
NULL, grfKeyState, *pdwEffectInOut, &dwEffectsUsed,
(DROPEFFECT_NONE == dwDefaultEffect) ? &dwDefaultEffect : NULL,
hmenu ? &fsmi : NULL);
}
}
*pdwEffectInOut &= dwEffectsUsed;
dwDefaultEffect = _LimitDefaultEffect(dwDefaultEffect, *pdwEffectInOut);
DebugMsg(TF_FSTREE, TEXT("CFSDT::GetDefaultEffect dwDef=%x, dwEffUsed=%x, *pdw=%x"),
dwDefaultEffect, dwEffectsUsed, *pdwEffectInOut);
return dwDefaultEffect; // this is what we want to do
}
// This is used to map command id's back to dropeffect's:
const struct {
UINT uID;
DWORD dwEffect;
} c_IDFSEffects[] = {
DDIDM_COPY, DROPEFFECT_COPY,
DDIDM_MOVE, DROPEFFECT_MOVE,
DDIDM_CONTENTS_DESKCOMP, DROPEFFECT_LINK,
DDIDM_LINK, DROPEFFECT_LINK,
DDIDM_SCRAP_COPY, DROPEFFECT_COPY,
DDIDM_SCRAP_MOVE, DROPEFFECT_MOVE,
DDIDM_DOCLINK, DROPEFFECT_LINK,
DDIDM_CONTENTS_COPY, DROPEFFECT_COPY,
DDIDM_CONTENTS_MOVE, DROPEFFECT_MOVE,
DDIDM_CONTENTS_LINK, DROPEFFECT_LINK,
DDIDM_CONTENTS_DESKIMG, DROPEFFECT_LINK,
DDIDM_SYNCCOPYTYPE, DROPEFFECT_COPY, // (order is important)
DDIDM_SYNCCOPY, DROPEFFECT_COPY,
DDIDM_OBJECT_COPY, DROPEFFECT_COPY,
DDIDM_OBJECT_MOVE, DROPEFFECT_MOVE,
DDIDM_CONTENTS_DESKURL, DROPEFFECT_LINK,
};
void CFSDropTarget::_FixUpDefaultItem(HMENU hmenu, DWORD dwDefEffect)
{
// only do stuff if there is no default item already and we have a default effect
if ((GetMenuDefaultItem(hmenu, MF_BYPOSITION, 0) == -1) && dwDefEffect)
{
for (int i = 0; i < GetMenuItemCount(hmenu); i++)
{
// for menu item matching default effect, make it the default.
MENUITEMINFO mii = { 0 };
mii.cbSize = sizeof(mii);
mii.fMask = MIIM_DATA | MIIM_STATE;
if (GetMenuItemInfo(hmenu, i, MF_BYPOSITION, &mii) && (mii.dwItemData == dwDefEffect))
{
mii.fState |= MFS_DEFAULT;
SetMenuItemInfo(hmenu, i, MF_BYPOSITION, &mii);
break;
}
}
}
}
HRESULT CFSDropTarget::_DragDropMenu(FSDRAGDROPMENUPARAM *pddm)
{
HRESULT hr = E_OUTOFMEMORY; // assume error
DWORD dwEffectOut = 0; // assume no-ope.
if (pddm->hmenu)
{
UINT idCmd;
UINT idCmdFirst = DDIDM_EXTFIRST;
HDXA hdxa = HDXA_Create();
HDCA hdca = DCA_Create();
if (hdxa && hdca)
{
// Enumerate the DD handlers and let them append menu items.
for (DWORD i = 0; i < pddm->ck; i++)
{
DCA_AddItemsFromKey(hdca, pddm->rghk[i], STRREG_SHEX_DDHANDLER);
}
idCmdFirst = HDXA_AppendMenuItems(hdxa, pddm->pdtobj, pddm->ck,
pddm->rghk, _GetIDList(), pddm->hmenu, 0,
DDIDM_EXTFIRST, DDIDM_EXTLAST, 0, hdca);
}
// modifier keys held down to force operations that are not permitted (for example
// alt to force a shortcut from the start menu, which does not have SFGAO_CANLINK)
// can result in no default items on the context menu. however in displaying the
// cursor overlay in this case we fall back to DROPEFFECT_COPY. a left drag then
// tries to invoke the default menu item (user thinks its copy) but theres no default.
// this function selects a default menu item to match the default effect if there
// is no default item already.
_FixUpDefaultItem(pddm->hmenu, pddm->dwDefEffect);
// If this dragging is caused by the left button, simply choose
// the default one, otherwise, pop up the context menu. If there
// is no key state info and the original effect is the same as the
// current effect, choose the default one, otherwise pop up the
// context menu.
if ((_grfKeyStateLast & MK_LBUTTON) ||
(!_grfKeyStateLast && (*(pddm->pdwEffect) == pddm->dwDefEffect)))
{
idCmd = GetMenuDefaultItem(pddm->hmenu, MF_BYCOMMAND, 0);
// This one MUST be called here. Please read its comment block.
DAD_DragLeave();
if (_hwnd)
SetForegroundWindow(_hwnd);
}
else
{
// Note that SHTrackPopupMenu calls DAD_DragLeave().
idCmd = SHTrackPopupMenu(pddm->hmenu, TPM_RETURNCMD | TPM_RIGHTBUTTON | TPM_LEFTALIGN,
pddm->pt.x, pddm->pt.y, 0, _hwnd, NULL);
}
//
// We also need to call this here to release the dragged image.
//
DAD_SetDragImage(NULL, NULL);
//
// Check if the user selected one of add-in menu items.
//
if (idCmd == 0)
{
hr = S_OK; // Canceled by the user, return S_OK
}
else if (InRange(idCmd, DDIDM_EXTFIRST, DDIDM_EXTLAST))
{
//
// Yes. Let the context menu handler process it.
//
CMINVOKECOMMANDINFOEX ici = {
sizeof(CMINVOKECOMMANDINFOEX),
0L,
_hwnd,
(LPSTR)MAKEINTRESOURCE(idCmd - DDIDM_EXTFIRST),
NULL, NULL,
SW_NORMAL,
};
// record if the shift/control keys were down at the time of the drop
if (_grfKeyStateLast & MK_SHIFT)
{
ici.fMask |= CMIC_MASK_SHIFT_DOWN;
}
if (_grfKeyStateLast & MK_CONTROL)
{
ici.fMask |= CMIC_MASK_CONTROL_DOWN;
}
// We may not want to ignore the error code. (Can happen when you use the context menu
// to create new folders, but I don't know if that can happen here.).
HDXA_LetHandlerProcessCommandEx(hdxa, &ici, NULL);
hr = S_OK;
}
else
{
for (int nItem = 0; nItem < ARRAYSIZE(c_IDFSEffects); ++nItem)
{
if (idCmd == c_IDFSEffects[nItem].uID)
{
dwEffectOut = c_IDFSEffects[nItem].dwEffect;
break;
}
}
hr = S_FALSE;
}
if (hdca)
DCA_Destroy(hdca);
if (hdxa)
HDXA_Destroy(hdxa);
pddm->idCmd = idCmd;
}
*pddm->pdwEffect = dwEffectOut;
return hr;
}
void _MapName(void *hNameMap, LPTSTR pszPath)
{
if (hNameMap)
{
SHNAMEMAPPING *pNameMapping;
for (int i = 0; (pNameMapping = SHGetNameMappingPtr((HDSA)hNameMap, i)) != NULL; i++)
{
if (lstrcmpi(pszPath, pNameMapping->pszOldPath) == 0)
{
lstrcpy(pszPath, pNameMapping->pszNewPath);
break;
}
}
}
}
// convert double null list of files to array of pidls
int FileListToIDArray(LPCTSTR pszFiles, void *hNameMap, LPITEMIDLIST **pppidl)
{
int i = 0;
int nItems = CountFiles(pszFiles);
LPITEMIDLIST *ppidl = (LPITEMIDLIST *)LocalAlloc(LPTR, nItems * sizeof(*ppidl));
if (ppidl)
{
*pppidl = ppidl;
while (*pszFiles)
{
TCHAR szPath[MAX_PATH];
lstrcpy(szPath, pszFiles);
_MapName(hNameMap, szPath);
ppidl[i] = SHSimpleIDListFromPath(szPath);
pszFiles += lstrlen(pszFiles) + 1;
i++;
}
}
return i;
}
// move items to the new drop location
void CFSDropTarget::_MoveSelectIcons(IDataObject *pdtobj, IFolderView* pfv, void *hNameMap, LPCTSTR pszFiles, BOOL fMove, HDROP hDrop)
{
LPITEMIDLIST *ppidl = NULL;
int cidl;
if (pszFiles)
{
cidl = FileListToIDArray(pszFiles, hNameMap, &ppidl);
}
else
{
cidl = CreateMoveCopyList(hDrop, hNameMap, &ppidl);
}
if (ppidl)
{
if (pfv)
PositionItems(pfv, (LPCITEMIDLIST*)ppidl, cidl, pdtobj, fMove ? &_ptDrop : NULL);
FreeIDListArray(ppidl, cidl);
}
}
// this is the ILIsParent which matches up the desktop with the desktop directory.
BOOL AliasILIsParent(LPCITEMIDLIST pidl1, LPCITEMIDLIST pidl2)
{
LPITEMIDLIST pidlUse1 = SHLogILFromFSIL(pidl1);
if (pidlUse1)
pidl1 = pidlUse1;
LPITEMIDLIST pidlUse2 = SHLogILFromFSIL(pidl2);
if (pidlUse2)
pidl2 = pidlUse2;
BOOL fSame = ILIsParent(pidl1, pidl2, TRUE);
ILFree(pidlUse1); // NULL is OK here
ILFree(pidlUse2);
return fSame;
}
// in:
// pszDestDir destination dir for new file names
// pszDestSpecs double null list of destination specs
//
// returns:
// double null list of fully qualified destination file names to be freed
// with LocalFree()
//
LPTSTR RemapDestNamesW(LPCTSTR pszDestDir, LPCWSTR pszDestSpecs)
{
UINT cbDestSpec = lstrlen(pszDestDir) * sizeof(TCHAR) + sizeof(TCHAR);
LPCWSTR pszTemp;
UINT cbAlloc = sizeof(TCHAR); // for double NULL teriminaion of entire string
// compute length of buffer to aloc
for (pszTemp = pszDestSpecs; *pszTemp; pszTemp += lstrlenW(pszTemp) + 1)
{
// +1 for null teriminator
cbAlloc += cbDestSpec + lstrlenW(pszTemp) * sizeof(TCHAR) + sizeof(TCHAR);
}
LPTSTR pszRet = (LPTSTR)LocalAlloc(LPTR, cbAlloc);
if (pszRet)
{
LPTSTR pszDest = pszRet;
for (pszTemp = pszDestSpecs; *pszTemp; pszTemp += lstrlenW(pszTemp) + 1)
{
// PathCombine requires dest buffer of MAX_PATH size or it'll rip in call
// to PathCanonicalize (IsBadWritePtr)
TCHAR szTempDest[MAX_PATH];
PathCombine(szTempDest, pszDestDir, pszTemp);
lstrcpy(pszDest, szTempDest);
pszDest += lstrlen(pszDest) + 1;
ASSERT((UINT)((BYTE *)pszDest - (BYTE *)pszRet) < cbAlloc);
ASSERT(*pszDest == 0); // zero init alloc
}
ASSERT((LPTSTR)((BYTE *)pszRet + cbAlloc - sizeof(TCHAR)) >= pszDest);
ASSERT(*pszDest == 0); // zero init alloc
}
return pszRet;
}
LPTSTR RemapDestNamesA(LPCTSTR pszDestDir, LPCSTR pszDestSpecs)
{
UINT cbDestSpec = lstrlen(pszDestDir) * sizeof(TCHAR) + sizeof(TCHAR);
LPCSTR pszTemp;
LPTSTR pszRet;
UINT cbAlloc = sizeof(TCHAR); // for double NULL teriminaion of entire string
// compute length of buffer to aloc
for (pszTemp = pszDestSpecs; *pszTemp; pszTemp += lstrlenA(pszTemp) + 1)
{
// +1 for null teriminator
cbAlloc += cbDestSpec + lstrlenA(pszTemp) * sizeof(TCHAR) + sizeof(TCHAR);
}
pszRet = (LPTSTR)LocalAlloc(LPTR, cbAlloc);
if (pszRet)
{
LPTSTR pszDest = pszRet;
for (pszTemp = pszDestSpecs; *pszTemp; pszTemp += lstrlenA(pszTemp) + 1)
{
// PathCombine requires dest buffer of MAX_PATH size or it'll rip in call
// to PathCanonicalize (IsBadWritePtr)
TCHAR szTempDest[MAX_PATH];
WCHAR wszTemp[MAX_PATH];
SHAnsiToUnicode(pszTemp, wszTemp, ARRAYSIZE(wszTemp));
PathCombine(szTempDest, pszDestDir, wszTemp);
lstrcpy(pszDest, szTempDest);
pszDest += lstrlen(pszDest) + 1;
ASSERT((UINT)((BYTE *)pszDest - (BYTE *)pszRet) < cbAlloc);
ASSERT(*pszDest == 0); // zero init alloc
}
ASSERT((LPTSTR)((BYTE *)pszRet + cbAlloc - sizeof(TCHAR)) >= pszDest);
ASSERT(*pszDest == 0); // zero init alloc
}
return pszRet;
}
LPTSTR _GetDestNames(IDataObject *pdtobj, LPCTSTR pszPath)
{
LPTSTR pszDestNames = NULL;
STGMEDIUM medium;
FORMATETC fmte = {g_cfFileNameMapW, NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL};
if (S_OK == pdtobj->GetData(&fmte, &medium))
{
pszDestNames = RemapDestNamesW(pszPath, (LPWSTR)GlobalLock(medium.hGlobal));
ReleaseStgMediumHGLOBAL(medium.hGlobal, &medium);
}
else
{
fmte.cfFormat = g_cfFileNameMapA;
if (S_OK == pdtobj->GetData(&fmte, &medium))
{
pszDestNames = RemapDestNamesA(pszPath, (LPSTR)GlobalLock(medium.hGlobal));
ReleaseStgMediumHGLOBAL(medium.hGlobal, &medium);
}
}
return pszDestNames;
}
BOOL _IsInSameFolder(LPCITEMIDLIST pidlFolder, IDataObject *pdtobj)
{
BOOL bRet = FALSE;
STGMEDIUM medium = {0};
LPIDA pida = DataObj_GetHIDA(pdtobj, &medium);
if (pida)
{
for (UINT i = 0; i < pida->cidl; i++)
{
LPITEMIDLIST pidl = IDA_FullIDList(pida, i);
if (pidl)
{
// if we're doing keyboard cut/copy/paste
// to and from the same directories
// This is needed for common desktop support - BobDay/EricFlo
if (AliasILIsParent(pidlFolder, pidl))
{
bRet = TRUE;
}
ILFree(pidl);
}
}
HIDA_ReleaseStgMedium(pida, &medium);
}
return bRet;
}
LPCTSTR _RootSpecialCase(LPCTSTR pszFiles, LPTSTR pszSrc, LPTSTR pszDest)
{
if ((1 == CountFiles(pszFiles)) &&
PathIsRoot(pszFiles))
{
SHFILEINFO sfi;
// NOTE: don't use SHGFI_USEFILEATTRIBUTES because the simple IDList
// support for \\server\share produces the wrong name
if (SHGetFileInfo(pszFiles, 0, &sfi, sizeof(sfi), SHGFI_DISPLAYNAME))
{
if (!(PCS_FATAL & PathCleanupSpec(pszDest, sfi.szDisplayName)))
{
PathAppend(pszDest, sfi.szDisplayName); // sub dir name based on source root path
PathCombine(pszSrc, pszFiles, TEXT("*.*")); // all files on source
pszFiles = pszSrc;
}
}
}
return pszFiles;
}
void CFSDropTarget::_MoveCopy(IDataObject *pdtobj, IFolderView* pfv, HDROP hDrop)
{
#ifdef DEBUG
if (_hwnd == NULL)
{
TraceMsg(TF_GENERAL, "_MoveCopy() without an hwnd which will prevent displaying insert disk UI");
}
#endif // DEBUG
DRAGINFO di = { sizeof(di) };
if (DragQueryInfo(hDrop, &di))
{
TCHAR szDest[MAX_PATH] = {0}; // zero init for dbl null termination
_GetPath(szDest);
switch (_idCmd)
{
case DDIDM_MOVE:
if (_fSameHwnd)
{
_MoveSelectIcons(pdtobj, pfv, NULL, NULL, TRUE, hDrop);
break;
}
// fall through...
case DDIDM_COPY:
{
TCHAR szAltSource[MAX_PATH] = {0}; // zero init for dbl null termination
LPCTSTR pszSource = _RootSpecialCase(di.lpFileList, szAltSource, szDest);
SHFILEOPSTRUCT fo =
{
_hwnd,
(DDIDM_COPY == _idCmd) ? FO_COPY : FO_MOVE,
pszSource,
szDest,
FOF_WANTMAPPINGHANDLE | FOF_ALLOWUNDO | FOF_NOCONFIRMMKDIR
};
if (fo.wFunc == FO_MOVE && IsFolderSecurityModeOn())
{
fo.fFlags |= FOF_NOCOPYSECURITYATTRIBS;
}
// if they are in the same hwnd or to and from
// the same directory, turn on the automatic rename on collision flag
if (_fSameHwnd ||
((DDIDM_COPY == _idCmd) && _IsInSameFolder(_GetIDList(), pdtobj)))
{
// do rename on collision for copy;
fo.fFlags |= FOF_RENAMEONCOLLISION;
}
// see if there is a rename mapping from recycle bin (or someone else)
LPTSTR pszDestNames = _GetDestNames(pdtobj, szDest);
if (pszDestNames)
{
fo.pTo = pszDestNames;
fo.fFlags |= FOF_MULTIDESTFILES;
fo.fFlags &= ~FOF_ALLOWUNDO; // HACK, this came from the recycle bin, don't allow undo
}
{
static UINT s_cfFileOpFlags = 0;
if (0 == s_cfFileOpFlags)
s_cfFileOpFlags = RegisterClipboardFormat(TEXT("FileOpFlags"));
fo.fFlags = (FILEOP_FLAGS)DataObj_GetDWORD(pdtobj, s_cfFileOpFlags, fo.fFlags);
}
// Check if there were any errors
if (SHFileOperation(&fo) == 0 && !fo.fAnyOperationsAborted)
{
if (_fBkDropTarget)
ShellFolderView_SetRedraw(_hwnd, 0);
SHChangeNotifyHandleEvents(); // force update now
if (_fBkDropTarget)
{
_MoveSelectIcons(pdtobj, pfv, fo.hNameMappings, pszDestNames, _fDragDrop, hDrop);
ShellFolderView_SetRedraw(_hwnd, TRUE);
}
}
if (fo.hNameMappings)
SHFreeNameMappings(fo.hNameMappings);
if (pszDestNames)
{
LocalFree((HLOCAL)pszDestNames);
// HACK, this usually comes from the bitbucket
// but in our shell, we don't handle the moves from the source
if (DDIDM_MOVE == _idCmd)
BBCheckRestoredFiles(pszSource);
}
}
break;
}
SHFree(di.lpFileList);
}
}
const UINT c_rgFolderShortcutTargets[] = {
CSIDL_STARTMENU,
CSIDL_COMMON_STARTMENU,
CSIDL_PROGRAMS,
CSIDL_COMMON_PROGRAMS,
CSIDL_NETHOOD,
};
BOOL _ShouldCreateFolderShortcut(LPCTSTR pszFolder)
{
return PathIsEqualOrSubFolderOf(pszFolder, c_rgFolderShortcutTargets, ARRAYSIZE(c_rgFolderShortcutTargets));
}
void CFSDropTarget::_DoDrop(IDataObject *pdtobj, IFolderView* pfv)
{
HRESULT hr = E_FAIL;
// Sleep(10 * 1000); // to debug async case
TCHAR szPath[MAX_PATH];
_GetPath(szPath);
SHCreateDirectory(NULL, szPath); // if this fails we catch it later
switch (_idCmd)
{
case DDIDM_SYNCCOPY:
case DDIDM_SYNCCOPYTYPE:
if (_IsBriefcaseTarget())
{
IBriefcaseStg *pbrfstg;
if (SUCCEEDED(CreateBrfStgFromPath(szPath, _hwnd, &pbrfstg)))
{
hr = pbrfstg->AddObject(pdtobj, NULL,
(DDIDM_SYNCCOPYTYPE == _idCmd) ? AOF_FILTERPROMPT : AOF_DEFAULT,
_hwnd);
pbrfstg->Release();
}
}
else
{
// Perform a sneakernet addition to the briefcase
STGMEDIUM medium;
LPIDA pida = DataObj_GetHIDA(pdtobj, &medium);
if (pida)
{
// Is there a briefcase root in this pdtobj?
IBriefcaseStg *pbrfstg;
if (SUCCEEDED(CreateBrfStgFromIDList(IDA_GetIDListPtr(pida, (UINT)-1), _hwnd, &pbrfstg)))
{
hr = pbrfstg->AddObject(pdtobj, szPath,
(DDIDM_SYNCCOPYTYPE == _idCmd) ? AOF_FILTERPROMPT : AOF_DEFAULT,
_hwnd);
pbrfstg->Release();
}
HIDA_ReleaseStgMedium(pida, &medium);
}
}
break;
case DDIDM_COPY:
case DDIDM_MOVE:
{
STGMEDIUM medium;
FORMATETC fmte = {CF_HDROP, NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL};
hr = pdtobj->GetData(&fmte, &medium);
if (SUCCEEDED(hr))
{
_MoveCopy(pdtobj, pfv, (HDROP)medium.hGlobal);
ReleaseStgMedium(&medium);
}
}
break;
case DDIDM_LINK:
{
int i = 0;
LPITEMIDLIST *ppidl = NULL;
if (_fBkDropTarget)
{
i = DataObj_GetHIDACount(pdtobj);
ppidl = (LPITEMIDLIST *)LocalAlloc(LPTR, sizeof(*ppidl) * i);
}
// _grfKeyStateLast of 0 means this was a simulated drop
UINT uCreateFlags = _grfKeyStateLast && !(_dwEffectFolder & DROPEFFECT_LINK) ? SHCL_USETEMPLATE : 0;
if (_ShouldCreateFolderShortcut(szPath))
uCreateFlags |= SHCL_MAKEFOLDERSHORTCUT;
ShellFolderView_SetRedraw(_hwnd, FALSE);
// passing ppidl == NULL is correct in failure case
hr = SHCreateLinks(_hwnd, szPath, pdtobj, uCreateFlags, ppidl);
if (ppidl)
{
if (pfv)
PositionItems(pfv, (LPCITEMIDLIST*)ppidl, i, pdtobj, &_ptDrop);
FreeIDListArray(ppidl, i);
}
ShellFolderView_SetRedraw(_hwnd, TRUE);
}
break;
}
if (SUCCEEDED(hr) && _dwEffect)
{
DataObj_SetDWORD(pdtobj, g_cfLogicalPerformedDropEffect, _dwEffect);
DataObj_SetDWORD(pdtobj, g_cfPerformedDropEffect, _dwEffect);
}
SHChangeNotifyHandleEvents(); // force update now
}
DWORD CALLBACK CFSDropTarget::_DoDropThreadProc(void *pv)
{
DROPTHREADPARAMS *pdtp = (DROPTHREADPARAMS *)pv;
IDataObject *pdtobj;
if (SUCCEEDED(CoGetInterfaceAndReleaseStream(pdtp->pstmDataObj, IID_PPV_ARG(IDataObject, &pdtobj))))
{
IFolderView* pfv;
if (FAILED(CoGetInterfaceAndReleaseStream(pdtp->pstmFolderView, IID_PPV_ARG(IFolderView, &pfv))))
pfv = NULL;
pdtp->pThis->_DoDrop(pdtobj, pfv);
if (pfv)
pfv->Release();
pdtp->pstmFolderView = NULL; // stream now invalid; CoGetInterfaceAndReleaseStream already released it
pdtobj->Release();
}
pdtp->pstmDataObj = NULL; // stream now invalid; CoGetInterfaceAndReleaseStream already released it
_FreeThreadParams(pdtp);
CoFreeUnusedLibraries();
return 0;
}
// REARCHITECT: view and drop related helpers, these use the ugly old private defview messages
// we should replace the usage of this stuff with IShellFolderView programming
// create the pidl array that contains the destination file names. this is
// done by taking the source file names, and translating them through the
// name mapping returned by the copy engine.
//
//
// in:
// hDrop HDROP containing files recently moved/copied
// hNameMap used to translate names
//
// out:
// *pppidl id array of length return value
// # of items in pppida
//
// WARNING! You must use the provided HDROP. Do not attempt to ask the
// data object for a HDROP or HIDA or WS_FTP will break! They don't like
// it if you ask them for HDROP/HIDA, move the files to a new location
// (via the copy engine), and then ask them for HDROP/HIDA a second time.
// They notice that "Hey, those files I downloaded last time are gone!"
// and then get confused.
//
STDAPI_(int) CreateMoveCopyList(HDROP hDrop, void *hNameMap, LPITEMIDLIST **pppidl)
{
int nItems = 0;
if (hDrop)
{
nItems = DragQueryFile(hDrop, (UINT)-1, NULL, 0);
*pppidl = (LPITEMIDLIST *)LocalAlloc(LPTR, nItems * sizeof(*pppidl));
if (*pppidl)
{
for (int i = nItems - 1; i >= 0; i--)
{
TCHAR szPath[MAX_PATH];
DragQueryFile(hDrop, i, szPath, ARRAYSIZE(szPath));
_MapName(hNameMap, szPath);
(*pppidl)[i] = SHSimpleIDListFromPath(szPath);
}
}
}
return nItems;
}
// this is really not related to CFSFolder. it is generic over any view
// REARCHITECT: convert view hwnd programming to site pointer
STDAPI_(void) PositionFileFromDrop(HWND hwnd, LPCTSTR pszFile, DROPHISTORY *pdh)
{
LPITEMIDLIST pidl = SHSimpleIDListFromPath(pszFile);
if (pidl)
{
LPITEMIDLIST pidlNew = ILFindLastID(pidl);
HWND hwndView = ShellFolderViewWindow(hwnd);
SFM_SAP sap;
SHChangeNotifyHandleEvents();
// Fill in some easy SAP fields first.
sap.uSelectFlags = SVSI_SELECT;
sap.fMove = TRUE;
sap.pidl = pidlNew;
// Now compute the x,y coordinates.
// If we have a drop history, use it to determine the
// next point.
if (pdh)
{
// fill in the anchor point first...
if (!pdh->fInitialized)
{
ITEMSPACING is;
ShellFolderView_GetDropPoint(hwnd, &pdh->ptOrigin);
pdh->pt = pdh->ptOrigin; // Compute the first point.
// Compute the point deltas.
if (ShellFolderView_GetItemSpacing(hwnd, &is))
{
pdh->cxItem = is.cxSmall;
pdh->cyItem = is.cySmall;
pdh->xDiv = is.cxLarge;
pdh->yDiv = is.cyLarge;
pdh->xMul = is.cxSmall;
pdh->yMul = is.cySmall;
}
else
{
pdh->cxItem = g_cxIcon;
pdh->cyItem = g_cyIcon;
pdh->xDiv = pdh->yDiv = pdh->xMul = pdh->yMul = 1;
}
// First point gets special flags.
sap.uSelectFlags |= SVSI_ENSUREVISIBLE | SVSI_DESELECTOTHERS | SVSI_FOCUSED;
pdh->fInitialized = TRUE; // We be initialized.
}
// if we have no list of offsets, then just inc by icon size..
else if ( !pdh->pptOffset )
{
// Simple computation of the next point.
pdh->pt.x += pdh->cxItem;
pdh->pt.y += pdh->cyItem;
}
// do this after the above stuff so that we always get our position relative to the anchor
// point, if we use the anchor point as the first one things get screwy...
if (pdh->pptOffset)
{
// Transform the old offset to our coordinates.
pdh->pt.x = ((pdh->pptOffset[pdh->iItem].x * pdh->xMul) / pdh->xDiv) + pdh->ptOrigin.x;
pdh->pt.y = ((pdh->pptOffset[pdh->iItem].y * pdh->yMul) / pdh->yDiv) + pdh->ptOrigin.y;
}
sap.pt = pdh->pt; // Copy the next point from the drop history.
}
else
{
// Preinitialize this puppy in case the folder view doesn't
// know what the drop point is (e.g., if it didn't come from
// a drag/drop but rather from a paste or a ChangeNotify.)
sap.pt.x = 0x7FFFFFFF; // "don't know"
sap.pt.y = 0x7FFFFFFF;
// Get the drop point, conveniently already in
// defview's screen coordinates.
//
// pdv->bDropAnchor should be TRUE at this point,
// see DefView's GetDropPoint() for details.
ShellFolderView_GetDropPoint(hwnd, &sap.pt);
// Only point gets special flags.
sap.uSelectFlags |= SVSI_ENSUREVISIBLE | SVSI_DESELECTOTHERS | SVSI_FOCUSED;
}
SendMessage(hwndView, SVM_SELECTANDPOSITIONITEM, 1, (LPARAM)&sap);
ILFree(pidl);
}
}
//
// Class used to scale and position items for drag and drops. Handles
// scaling between different sized views.
//
//
// Bug 165413 (edwardp 8/16/00) Convert IShellFolderView usage in CItemPositioning to IFolderView
//
class CItemPositioning
{
// Methods
public:
CItemPositioning(IFolderView* pifv, LPCITEMIDLIST* apidl, UINT cidl, IDataObject* pdtobj, POINT* ppt);
void DragSetPoints(void);
void DropPositionItems(void);
private:
typedef enum
{
DPIWP_AUTOARRANGE,
DPIWP_DATAOBJ,
} DPIWP;
BOOL _DragShouldPositionItems(void);
BOOL _DragGetPoints(POINT* apts);
void _DragPositionPoints(POINT* apts);
void _DragScalePoints(POINT* apts);
POINT* _DropGetPoints(DPIWP dpiwp, STGMEDIUM* pMediam);
void _DropFreePoints(DPIWP dpiwp, POINT* apts, STGMEDIUM* pmedium);
void _DropPositionPoints(POINT* apts);
void _DropScalePoints(POINT* apts);
void _DropPositionItemsWithPoints(DPIWP dpiwp);
void _DropPositionItems(POINT* apts);
void _ScalePoints(POINT* apts, POINT ptFrom, POINT ptTo);
POINT* _SkipAnchorPoint(POINT* apts);
// Data
private:
IFolderView* _pfv;
LPCITEMIDLIST* _apidl;
UINT _cidl;
IDataObject* _pdtobj;
POINT* _ppt;
};
CItemPositioning::CItemPositioning(IFolderView* pifv, LPCITEMIDLIST* apidl, UINT cidl, IDataObject* pdtobj, POINT* ppt)
{
ASSERT(pifv);
ASSERT(apidl);
ASSERT(cidl);
ASSERT(pdtobj);
_pfv = pifv; // No need to addref as long as CPostionItems is only used locally.
_apidl = apidl;
_cidl = cidl;
_pdtobj = pdtobj; // No need to addref as long as CPostionItems is only used locally.
_ppt = ppt;
}
void CItemPositioning::DragSetPoints(void)
{
if (_DragShouldPositionItems())
{
POINT* apts = (POINT*) GlobalAlloc(GPTR, sizeof(POINT) * (_cidl + 1));
if (apts)
{
if (_DragGetPoints(apts))
{
_DragPositionPoints(_SkipAnchorPoint(apts));
_DragScalePoints(_SkipAnchorPoint(apts));
if (FAILED(DataObj_SetGlobal(_pdtobj, g_cfOFFSETS, apts)))
GlobalFree((HGLOBAL)apts);
}
else
{
GlobalFree((HGLOBAL)apts);
}
}
}
}
BOOL CItemPositioning::_DragShouldPositionItems()
{
// Don't position multiple items if they come from a view that doesn't allow
// positioning. The position information is not likely to be usefull in this
// case.
// Always position single items so they show up at the drop point.
// Don't bother with position data for 100 or more items.
return ((S_OK == _pfv->GetSpacing(NULL)) || 1 == _cidl) && _cidl < 100;
}
BOOL CItemPositioning::_DragGetPoints(POINT* apts)
{
BOOL fRet = TRUE;
// The first point is the anchor.
apts[0] = *_ppt;
for (UINT i = 0; i < _cidl; i++)
{
if (FAILED(_pfv->GetItemPosition(_apidl[i], &apts[i + 1])))
{
if (1 == _cidl)
{
apts[i + 1].x = _ppt->x;
apts[i + 1].y = _ppt->y;
}
else
{
fRet = FALSE;
}
}
}
return fRet;
}
void CItemPositioning::_DragPositionPoints(POINT* apts)
{
for (UINT i = 0; i < _cidl; i++)
{
apts[i].x -= _ppt->x;
apts[i].y -= _ppt->y;
}
}
void CItemPositioning::_DragScalePoints(POINT* apts)
{
POINT ptFrom;
POINT ptTo;
_pfv->GetSpacing(&ptFrom);
_pfv->GetDefaultSpacing(&ptTo);
if (ptFrom.x != ptTo.x || ptFrom.y != ptTo.y)
_ScalePoints(apts, ptFrom, ptTo);
}
void CItemPositioning::DropPositionItems(void)
{
if (S_OK == _pfv->GetAutoArrange())
{
_DropPositionItemsWithPoints(DPIWP_AUTOARRANGE);
}
else if (S_OK == _pfv->GetSpacing(NULL) && _ppt)
{
_DropPositionItemsWithPoints(DPIWP_DATAOBJ);
}
else
{
_DropPositionItems(NULL);
}
}
void CItemPositioning::_DropPositionItemsWithPoints(DPIWP dpiwp)
{
STGMEDIUM medium;
POINT* apts = _DropGetPoints(dpiwp, &medium);
if (apts)
{
if (DPIWP_DATAOBJ == dpiwp)
{
_DropScalePoints(_SkipAnchorPoint(apts));
_DropPositionPoints(_SkipAnchorPoint(apts));
}
_DropPositionItems(_SkipAnchorPoint(apts));
_DropFreePoints(dpiwp, apts, &medium);
}
else if (_ppt)
{
POINT *ppts;
ppts = (POINT *)LocalAlloc(LPTR, _cidl * sizeof(POINT));
if (ppts)
{
POINT pt;
_pfv->GetDefaultSpacing(&pt);
for (UINT i = 0; i < _cidl; i++)
{
ppts[i].x = (-g_cxIcon / 2) + (i * pt.x);
ppts[i].y = (-g_cyIcon / 2) + (i * pt.y);
}
_DropScalePoints(ppts);
_DropPositionPoints(ppts);
_DropPositionItems(ppts);
LocalFree(ppts);
}
else
{
_DropPositionItems(NULL);
}
}
else
{
_DropPositionItems(NULL);
}
}
void CItemPositioning::_DropPositionItems(POINT* apts)
{
// Drop the first item with special selection flags.
LPCITEMIDLIST pidl = ILFindLastID(_apidl[0]);
_pfv->SelectAndPositionItems(1, &pidl, apts, SVSI_SELECT | SVSI_ENSUREVISIBLE | SVSI_DESELECTOTHERS | SVSI_FOCUSED);
// Drop the rest of the items.
if (_cidl > 1)
{
LPCITEMIDLIST* apidl = (LPCITEMIDLIST*)LocalAlloc(GPTR, sizeof(LPCITEMIDLIST) * (_cidl - 1));
if (apidl)
{
for (UINT i = 1; i < _cidl; i++)
apidl[i - 1] = ILFindLastID(_apidl[i]);
_pfv->SelectAndPositionItems(_cidl - 1, apidl, (apts) ? &apts[1] : NULL, SVSI_SELECT);
LocalFree(apidl);
}
}
}
POINT* CItemPositioning::_DropGetPoints(DPIWP dpiwp, STGMEDIUM* pmedium)
{
POINT* pptRet = NULL;
if (DPIWP_DATAOBJ == dpiwp)
{
FORMATETC fmte = {g_cfOFFSETS, NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL};
if (SUCCEEDED(_pdtobj->GetData(&fmte, pmedium)))
{
if (pmedium->hGlobal)
{
POINT *pptSrc;
pptSrc = (POINT *)GlobalLock(pmedium->hGlobal);
if (pptSrc)
{
pptRet = (POINT*)LocalAlloc(GPTR, (_cidl + 1) * sizeof(POINT));
if (pptRet)
{
for (UINT i = 0; i <= _cidl; i++)
{
pptRet[i] = pptSrc[i];
}
}
GlobalUnlock(pptSrc);
}
}
ReleaseStgMedium(pmedium);
}
}
else if (DPIWP_AUTOARRANGE == dpiwp)
{
if (_ppt)
{
pptRet = (POINT*)LocalAlloc(GPTR, (_cidl + 1) * sizeof(POINT));
if (pptRet)
{
// skip first point to simulate data object use of first point
for (UINT i = 1; i <= _cidl; i++)
{
pptRet[i] = *_ppt;
}
}
}
}
return pptRet;
}
void CItemPositioning::_DropFreePoints(DPIWP dpiwp, POINT* apts, STGMEDIUM* pmedium)
{
LocalFree(apts);
}
void CItemPositioning::_DropScalePoints(POINT* apts)
{
POINT ptFrom;
POINT ptTo;
_pfv->GetDefaultSpacing(&ptFrom);
_pfv->GetSpacing(&ptTo);
if (ptFrom.x != ptTo.x || ptFrom.y != ptTo.y)
_ScalePoints(apts, ptFrom, ptTo);
}
void CItemPositioning::_DropPositionPoints(POINT* apts)
{
for (UINT i = 0; i < _cidl; i++)
{
apts[i].x += _ppt->x;
apts[i].y += _ppt->y;
}
}
void CItemPositioning::_ScalePoints(POINT* apts, POINT ptFrom, POINT ptTo)
{
for (UINT i = 0; i < _cidl; i++)
{
apts[i].x = MulDiv(apts[i].x, ptTo.x, ptFrom.x);
apts[i].y = MulDiv(apts[i].y, ptTo.y, ptFrom.y);
}
}
POINT* CItemPositioning::_SkipAnchorPoint(POINT* apts)
{
return &apts[1];
}
STDAPI_(void) SetPositionItemsPoints(IFolderView* pifv, LPCITEMIDLIST* apidl, UINT cidl, IDataObject* pdtobj, POINT* ptDrag)
{
CItemPositioning cpi(pifv, apidl, cidl, pdtobj, ptDrag);
cpi.DragSetPoints();
}
STDAPI_(void) PositionItems(IFolderView* pifv, LPCITEMIDLIST* apidl, UINT cidl, IDataObject* pdtobj, POINT* ptDrop)
{
CItemPositioning cip(pifv, apidl, cidl, pdtobj, ptDrop);
cip.DropPositionItems();
}
//
// Don't use PositionItems_DontUse. Instead convert to PositionItems.
// PositionItems_DontUse will be removed.
//
// Bug#163533 (edwardp 8/15/00) Remove this code.
STDAPI_(void) PositionItems_DontUse(HWND hwndOwner, UINT cidl, const LPITEMIDLIST *ppidl, IDataObject *pdtobj, POINT *pptOrigin, BOOL fMove, BOOL fUseExactOrigin)
{
if (!ppidl || !IsWindow(hwndOwner))
return;
SFM_SAP *psap = (SFM_SAP *)GlobalAlloc(GPTR, sizeof(SFM_SAP) * cidl);
if (psap)
{
UINT i, cxItem, cyItem;
int xMul, yMul, xDiv, yDiv;
STGMEDIUM medium;
POINT *pptItems = NULL;
POINT pt;
ITEMSPACING is;
// select those objects;
// this had better not fail
HWND hwnd = ShellFolderViewWindow(hwndOwner);
if (fMove)
{
FORMATETC fmte = {g_cfOFFSETS, NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL};
if (SUCCEEDED(pdtobj->GetData(&fmte, &medium)) &&
medium.hGlobal)
{
pptItems = (POINT *)GlobalLock(medium.hGlobal);
pptItems++; // The first point is the anchor
}
else
{
// By default, drop at (-g_cxIcon/2, -g_cyIcon/2), and increase
// x and y by icon dimension for each icon
pt.x = ((-3 * g_cxIcon) / 2) + pptOrigin->x;
pt.y = ((-3 * g_cyIcon) / 2) + pptOrigin->y;
medium.hGlobal = NULL;
}
if (ShellFolderView_GetItemSpacing(hwndOwner, &is))
{
xDiv = is.cxLarge;
yDiv = is.cyLarge;
xMul = is.cxSmall;
yMul = is.cySmall;
cxItem = is.cxSmall;
cyItem = is.cySmall;
}
else
{
xDiv = yDiv = xMul = yMul = 1;
cxItem = g_cxIcon;
cyItem = g_cyIcon;
}
}
for (i = 0; i < cidl; i++)
{
if (ppidl[i])
{
psap[i].pidl = ILFindLastID(ppidl[i]);
psap[i].fMove = fMove;
if (fMove)
{
if (fUseExactOrigin)
{
psap[i].pt = *pptOrigin;
}
else
{
if (pptItems)
{
psap[i].pt.x = ((pptItems[i].x * xMul) / xDiv) + pptOrigin->x;
psap[i].pt.y = ((pptItems[i].y * yMul) / yDiv) + pptOrigin->y;
}
else
{
pt.x += cxItem;
pt.y += cyItem;
psap[i].pt = pt;
}
}
}
// do regular selection from all of the rest of the items
psap[i].uSelectFlags = SVSI_SELECT;
}
}
// do this special one for the first only
psap[0].uSelectFlags = SVSI_SELECT | SVSI_ENSUREVISIBLE | SVSI_DESELECTOTHERS | SVSI_FOCUSED;
SendMessage(hwnd, SVM_SELECTANDPOSITIONITEM, cidl, (LPARAM)psap);
if (fMove && medium.hGlobal)
ReleaseStgMediumHGLOBAL(NULL, &medium);
GlobalFree(psap);
}
}
| [
"112426112@qq.com"
] | 112426112@qq.com |
6b7443e5eb67204049269ca0682c04c3f74badc4 | a3ad139a71406fdae41f7385fc9c869e64cf05da | /TimeConversion/TimeConversion/invalidHr.h | fb387be1694c1720907699f7746fb6a3c5774227 | [] | no_license | JessicaAlexander/Students_Projects6 | 68008f9f5c98701e479f6bb25fde5d2f12a18149 | ad6e92648fdf74fd2b4517875ecaaa1f115b9edf | refs/heads/master | 2020-07-06T05:45:06.410788 | 2019-08-17T18:04:47 | 2019-08-17T18:04:47 | 202,910,914 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 196 | h | #pragma once
#include "pch.h"
#include <iostream>
#include <string>
using namespace std;
class invalidHr
{
public:
invalidHr();
void showException();
private:
string message;
}; | [
"noreply@github.com"
] | noreply@github.com |
6c6db13d1a207dca9e415e1141b68731a48e32a3 | ebe145152e1dd816d17b788004470faa5c6f269b | /Lista 2/coordponto.cpp | 4a90894ee6edc15af94ed7f40211660e456f1b8e | [] | no_license | i-ramoss/Introducao-a-Logica-de-Programacao---MATA37 | 6676b305569d67214bc6773a4acbf1af2b8945eb | 5bd0410a70a0057bf6cef07aa1610a29431cb769 | refs/heads/master | 2020-08-01T12:30:09.910989 | 2019-12-03T15:27:43 | 2019-12-03T15:27:43 | 210,997,416 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 449 | cpp | #include <iostream>
#include <iomanip>
using namespace std;
int main () {
float x,y;
cin >> x >> y;
if (x==0 && y==0)
cout << "Origem\n";
else if((x>0 && y==0) || x<0 && y==0)
cout << "Eixo X\n";
else if((x==0 && y>0) || x==0 && y<0)
cout << "Eixo Y\n";
else if (x>0 && y>0)
cout << "Q1\n";
else if (x<0 && y>0)
cout << "Q2\n";
else if (x<0 && y<0)
cout << "Q3\n";
else
cout << "Q4\n";
return 0;
}
| [
"ianramossantos@hotmail.com"
] | ianramossantos@hotmail.com |
e5d3bf12d4969cd7d28d7269700f039b7e6123c0 | c8b39acfd4a857dc15ed3375e0d93e75fa3f1f64 | /Engine/Source/ThirdParty/CryptoPP/5.6.2/include/validat3.cpp | 035b556337203b29d3e5c6179dd3cd9a43ca18f2 | [
"MIT",
"LicenseRef-scancode-proprietary-license",
"BSL-1.0",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | windystrife/UnrealEngine_NVIDIAGameWorks | c3c7863083653caf1bc67d3ef104fb4b9f302e2a | b50e6338a7c5b26374d66306ebc7807541ff815e | refs/heads/4.18-GameWorks | 2023-03-11T02:50:08.471040 | 2022-01-13T20:50:29 | 2022-01-13T20:50:29 | 124,100,479 | 262 | 179 | MIT | 2022-12-16T05:36:38 | 2018-03-06T15:44:09 | C++ | UTF-8 | C++ | false | false | 27,724 | cpp | // validat3.cpp - written and placed in the public domain by Wei Dai
#include "pch.h"
#include "validate.h"
#define CRYPTOPP_ENABLE_NAMESPACE_WEAK 1
#include "smartptr.h"
#include "crc.h"
#include "adler32.h"
#include "md2.h"
#include "md4.h"
#include "md5.h"
#include "sha.h"
#include "tiger.h"
#include "ripemd.h"
#include "hmac.h"
#include "ttmac.h"
#include "integer.h"
#include "pwdbased.h"
#include "filters.h"
#include "hex.h"
#include "files.h"
#include <iostream>
#include <iomanip>
USING_NAMESPACE(CryptoPP)
USING_NAMESPACE(std)
struct HashTestTuple
{
HashTestTuple(const char *input, const char *output, unsigned int repeatTimes=1)
: input((byte *)input), output((byte *)output), inputLen(strlen(input)), repeatTimes(repeatTimes) {}
HashTestTuple(const char *input, unsigned int inputLen, const char *output, unsigned int repeatTimes)
: input((byte *)input), output((byte *)output), inputLen(inputLen), repeatTimes(repeatTimes) {}
const byte *input, *output;
size_t inputLen;
unsigned int repeatTimes;
};
bool HashModuleTest(HashTransformation &md, const HashTestTuple *testSet, unsigned int testSetSize)
{
bool pass=true, fail;
SecByteBlock digest(md.DigestSize());
for (unsigned int i=0; i<testSetSize; i++)
{
unsigned j;
for (j=0; j<testSet[i].repeatTimes; j++)
md.Update(testSet[i].input, testSet[i].inputLen);
md.Final(digest);
fail = memcmp(digest, testSet[i].output, md.DigestSize()) != 0;
pass = pass && !fail;
cout << (fail ? "FAILED " : "passed ");
for (j=0; j<md.DigestSize(); j++)
cout << setw(2) << setfill('0') << hex << (int)digest[j];
cout << " \"" << (char *)testSet[i].input << '\"';
if (testSet[i].repeatTimes != 1)
cout << " repeated " << dec << testSet[i].repeatTimes << " times";
cout << endl;
}
return pass;
}
bool ValidateCRC32()
{
HashTestTuple testSet[] =
{
HashTestTuple("", "\x00\x00\x00\x00"),
HashTestTuple("a", "\x43\xbe\xb7\xe8"),
HashTestTuple("abc", "\xc2\x41\x24\x35"),
HashTestTuple("message digest", "\x7f\x9d\x15\x20"),
HashTestTuple("abcdefghijklmnopqrstuvwxyz", "\xbd\x50\x27\x4c"),
HashTestTuple("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", "\xd2\xe6\xc2\x1f"),
HashTestTuple("12345678901234567890123456789012345678901234567890123456789012345678901234567890", "\x72\x4a\xa9\x7c"),
HashTestTuple("123456789", "\x26\x39\xf4\xcb")
};
CRC32 crc;
cout << "\nCRC-32 validation suite running...\n\n";
return HashModuleTest(crc, testSet, sizeof(testSet)/sizeof(testSet[0]));
}
bool ValidateAdler32()
{
HashTestTuple testSet[] =
{
HashTestTuple("", "\x00\x00\x00\x01"),
HashTestTuple("a", "\x00\x62\x00\x62"),
HashTestTuple("abc", "\x02\x4d\x01\x27"),
HashTestTuple("message digest", "\x29\x75\x05\x86"),
HashTestTuple("abcdefghijklmnopqrstuvwxyz", "\x90\x86\x0b\x20"),
HashTestTuple("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", "\x8a\xdb\x15\x0c"),
HashTestTuple("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "\x15\xd8\x70\xf9", 15625)
};
Adler32 md;
cout << "\nAdler-32 validation suite running...\n\n";
return HashModuleTest(md, testSet, sizeof(testSet)/sizeof(testSet[0]));
}
bool ValidateMD2()
{
HashTestTuple testSet[] =
{
HashTestTuple("", "\x83\x50\xe5\xa3\xe2\x4c\x15\x3d\xf2\x27\x5c\x9f\x80\x69\x27\x73"),
HashTestTuple("a", "\x32\xec\x01\xec\x4a\x6d\xac\x72\xc0\xab\x96\xfb\x34\xc0\xb5\xd1"),
HashTestTuple("abc", "\xda\x85\x3b\x0d\x3f\x88\xd9\x9b\x30\x28\x3a\x69\xe6\xde\xd6\xbb"),
HashTestTuple("message digest", "\xab\x4f\x49\x6b\xfb\x2a\x53\x0b\x21\x9f\xf3\x30\x31\xfe\x06\xb0"),
HashTestTuple("abcdefghijklmnopqrstuvwxyz", "\x4e\x8d\xdf\xf3\x65\x02\x92\xab\x5a\x41\x08\xc3\xaa\x47\x94\x0b"),
HashTestTuple("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", "\xda\x33\xde\xf2\xa4\x2d\xf1\x39\x75\x35\x28\x46\xc3\x03\x38\xcd"),
HashTestTuple("12345678901234567890123456789012345678901234567890123456789012345678901234567890", "\xd5\x97\x6f\x79\xd8\x3d\x3a\x0d\xc9\x80\x6c\x3c\x66\xf3\xef\xd8")
};
Weak::MD2 md2;
cout << "\nMD2 validation suite running...\n\n";
return HashModuleTest(md2, testSet, sizeof(testSet)/sizeof(testSet[0]));
}
bool ValidateMD4()
{
HashTestTuple testSet[] =
{
HashTestTuple("", "\x31\xd6\xcf\xe0\xd1\x6a\xe9\x31\xb7\x3c\x59\xd7\xe0\xc0\x89\xc0"),
HashTestTuple("a", "\xbd\xe5\x2c\xb3\x1d\xe3\x3e\x46\x24\x5e\x05\xfb\xdb\xd6\xfb\x24"),
HashTestTuple("abc", "\xa4\x48\x01\x7a\xaf\x21\xd8\x52\x5f\xc1\x0a\xe8\x7a\xa6\x72\x9d"),
HashTestTuple("message digest", "\xd9\x13\x0a\x81\x64\x54\x9f\xe8\x18\x87\x48\x06\xe1\xc7\x01\x4b"),
HashTestTuple("abcdefghijklmnopqrstuvwxyz", "\xd7\x9e\x1c\x30\x8a\xa5\xbb\xcd\xee\xa8\xed\x63\xdf\x41\x2d\xa9"),
HashTestTuple("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", "\x04\x3f\x85\x82\xf2\x41\xdb\x35\x1c\xe6\x27\xe1\x53\xe7\xf0\xe4"),
HashTestTuple("12345678901234567890123456789012345678901234567890123456789012345678901234567890", "\xe3\x3b\x4d\xdc\x9c\x38\xf2\x19\x9c\x3e\x7b\x16\x4f\xcc\x05\x36")
};
Weak::MD4 md4;
cout << "\nMD4 validation suite running...\n\n";
return HashModuleTest(md4, testSet, sizeof(testSet)/sizeof(testSet[0]));
}
bool ValidateMD5()
{
HashTestTuple testSet[] =
{
HashTestTuple("", "\xd4\x1d\x8c\xd9\x8f\x00\xb2\x04\xe9\x80\x09\x98\xec\xf8\x42\x7e"),
HashTestTuple("a", "\x0c\xc1\x75\xb9\xc0\xf1\xb6\xa8\x31\xc3\x99\xe2\x69\x77\x26\x61"),
HashTestTuple("abc", "\x90\x01\x50\x98\x3c\xd2\x4f\xb0\xd6\x96\x3f\x7d\x28\xe1\x7f\x72"),
HashTestTuple("message digest", "\xf9\x6b\x69\x7d\x7c\xb7\x93\x8d\x52\x5a\x2f\x31\xaa\xf1\x61\xd0"),
HashTestTuple("abcdefghijklmnopqrstuvwxyz", "\xc3\xfc\xd3\xd7\x61\x92\xe4\x00\x7d\xfb\x49\x6c\xca\x67\xe1\x3b"),
HashTestTuple("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", "\xd1\x74\xab\x98\xd2\x77\xd9\xf5\xa5\x61\x1c\x2c\x9f\x41\x9d\x9f"),
HashTestTuple("12345678901234567890123456789012345678901234567890123456789012345678901234567890", "\x57\xed\xf4\xa2\x2b\xe3\xc9\x55\xac\x49\xda\x2e\x21\x07\xb6\x7a")
};
Weak::MD5 md5;
cout << "\nMD5 validation suite running...\n\n";
return HashModuleTest(md5, testSet, sizeof(testSet)/sizeof(testSet[0]));
}
bool ValidateSHA()
{
cout << "\nSHA validation suite running...\n\n";
return RunTestDataFile("TestVectors/sha.txt");
}
bool ValidateSHA2()
{
cout << "\nSHA validation suite running...\n\n";
return RunTestDataFile("TestVectors/sha.txt");
}
bool ValidateTiger()
{
cout << "\nTiger validation suite running...\n\n";
HashTestTuple testSet[] =
{
HashTestTuple("", "\x32\x93\xac\x63\x0c\x13\xf0\x24\x5f\x92\xbb\xb1\x76\x6e\x16\x16\x7a\x4e\x58\x49\x2d\xde\x73\xf3"),
HashTestTuple("abc", "\x2a\xab\x14\x84\xe8\xc1\x58\xf2\xbf\xb8\xc5\xff\x41\xb5\x7a\x52\x51\x29\x13\x1c\x95\x7b\x5f\x93"),
HashTestTuple("Tiger", "\xdd\x00\x23\x07\x99\xf5\x00\x9f\xec\x6d\xeb\xc8\x38\xbb\x6a\x27\xdf\x2b\x9d\x6f\x11\x0c\x79\x37"),
HashTestTuple("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-", "\xf7\x1c\x85\x83\x90\x2a\xfb\x87\x9e\xdf\xe6\x10\xf8\x2c\x0d\x47\x86\xa3\xa5\x34\x50\x44\x86\xb5"),
HashTestTuple("ABCDEFGHIJKLMNOPQRSTUVWXYZ=abcdefghijklmnopqrstuvwxyz+0123456789", "\x48\xce\xeb\x63\x08\xb8\x7d\x46\xe9\x5d\x65\x61\x12\xcd\xf1\x8d\x97\x91\x5f\x97\x65\x65\x89\x57"),
HashTestTuple("Tiger - A Fast New Hash Function, by Ross Anderson and Eli Biham", "\x8a\x86\x68\x29\x04\x0a\x41\x0c\x72\x9a\xd2\x3f\x5a\xda\x71\x16\x03\xb3\xcd\xd3\x57\xe4\xc1\x5e"),
HashTestTuple("Tiger - A Fast New Hash Function, by Ross Anderson and Eli Biham, proceedings of Fast Software Encryption 3, Cambridge.", "\xce\x55\xa6\xaf\xd5\x91\xf5\xeb\xac\x54\x7f\xf8\x4f\x89\x22\x7f\x93\x31\xda\xb0\xb6\x11\xc8\x89"),
HashTestTuple("Tiger - A Fast New Hash Function, by Ross Anderson and Eli Biham, proceedings of Fast Software Encryption 3, Cambridge, 1996.", "\x63\x1a\xbd\xd1\x03\xeb\x9a\x3d\x24\x5b\x6d\xfd\x4d\x77\xb2\x57\xfc\x74\x39\x50\x1d\x15\x68\xdd"),
HashTestTuple("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-", "\xc5\x40\x34\xe5\xb4\x3e\xb8\x00\x58\x48\xa7\xe0\xae\x6a\xac\x76\xe4\xff\x59\x0a\xe7\x15\xfd\x25")
};
Tiger tiger;
return HashModuleTest(tiger, testSet, sizeof(testSet)/sizeof(testSet[0]));
}
bool ValidateRIPEMD()
{
HashTestTuple testSet128[] =
{
HashTestTuple("", "\xcd\xf2\x62\x13\xa1\x50\xdc\x3e\xcb\x61\x0f\x18\xf6\xb3\x8b\x46"),
HashTestTuple("a", "\x86\xbe\x7a\xfa\x33\x9d\x0f\xc7\xcf\xc7\x85\xe7\x2f\x57\x8d\x33"),
HashTestTuple("abc", "\xc1\x4a\x12\x19\x9c\x66\xe4\xba\x84\x63\x6b\x0f\x69\x14\x4c\x77"),
HashTestTuple("message digest", "\x9e\x32\x7b\x3d\x6e\x52\x30\x62\xaf\xc1\x13\x2d\x7d\xf9\xd1\xb8"),
HashTestTuple("abcdefghijklmnopqrstuvwxyz", "\xfd\x2a\xa6\x07\xf7\x1d\xc8\xf5\x10\x71\x49\x22\xb3\x71\x83\x4e"),
HashTestTuple("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", "\xa1\xaa\x06\x89\xd0\xfa\xfa\x2d\xdc\x22\xe8\x8b\x49\x13\x3a\x06"),
HashTestTuple("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", "\xd1\xe9\x59\xeb\x17\x9c\x91\x1f\xae\xa4\x62\x4c\x60\xc5\xc7\x02"),
HashTestTuple("12345678901234567890123456789012345678901234567890123456789012345678901234567890", "\x3f\x45\xef\x19\x47\x32\xc2\xdb\xb2\xc4\xa2\xc7\x69\x79\x5f\xa3"),
HashTestTuple("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "\x4a\x7f\x57\x23\xf9\x54\xeb\xa1\x21\x6c\x9d\x8f\x63\x20\x43\x1f", 15625)
};
HashTestTuple testSet160[] =
{
HashTestTuple("", "\x9c\x11\x85\xa5\xc5\xe9\xfc\x54\x61\x28\x08\x97\x7e\xe8\xf5\x48\xb2\x25\x8d\x31"),
HashTestTuple("a", "\x0b\xdc\x9d\x2d\x25\x6b\x3e\xe9\xda\xae\x34\x7b\xe6\xf4\xdc\x83\x5a\x46\x7f\xfe"),
HashTestTuple("abc", "\x8e\xb2\x08\xf7\xe0\x5d\x98\x7a\x9b\x04\x4a\x8e\x98\xc6\xb0\x87\xf1\x5a\x0b\xfc"),
HashTestTuple("message digest", "\x5d\x06\x89\xef\x49\xd2\xfa\xe5\x72\xb8\x81\xb1\x23\xa8\x5f\xfa\x21\x59\x5f\x36"),
HashTestTuple("abcdefghijklmnopqrstuvwxyz", "\xf7\x1c\x27\x10\x9c\x69\x2c\x1b\x56\xbb\xdc\xeb\x5b\x9d\x28\x65\xb3\x70\x8d\xbc"),
HashTestTuple("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", "\x12\xa0\x53\x38\x4a\x9c\x0c\x88\xe4\x05\xa0\x6c\x27\xdc\xf4\x9a\xda\x62\xeb\x2b"),
HashTestTuple("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", "\xb0\xe2\x0b\x6e\x31\x16\x64\x02\x86\xed\x3a\x87\xa5\x71\x30\x79\xb2\x1f\x51\x89"),
HashTestTuple("12345678901234567890123456789012345678901234567890123456789012345678901234567890", "\x9b\x75\x2e\x45\x57\x3d\x4b\x39\xf4\xdb\xd3\x32\x3c\xab\x82\xbf\x63\x32\x6b\xfb"),
HashTestTuple("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "\x52\x78\x32\x43\xc1\x69\x7b\xdb\xe1\x6d\x37\xf9\x7f\x68\xf0\x83\x25\xdc\x15\x28", 15625)
};
HashTestTuple testSet256[] =
{
HashTestTuple("", "\x02\xba\x4c\x4e\x5f\x8e\xcd\x18\x77\xfc\x52\xd6\x4d\x30\xe3\x7a\x2d\x97\x74\xfb\x1e\x5d\x02\x63\x80\xae\x01\x68\xe3\xc5\x52\x2d"),
HashTestTuple("a", "\xf9\x33\x3e\x45\xd8\x57\xf5\xd9\x0a\x91\xba\xb7\x0a\x1e\xba\x0c\xfb\x1b\xe4\xb0\x78\x3c\x9a\xcf\xcd\x88\x3a\x91\x34\x69\x29\x25"),
HashTestTuple("abc", "\xaf\xbd\x6e\x22\x8b\x9d\x8c\xbb\xce\xf5\xca\x2d\x03\xe6\xdb\xa1\x0a\xc0\xbc\x7d\xcb\xe4\x68\x0e\x1e\x42\xd2\xe9\x75\x45\x9b\x65"),
HashTestTuple("message digest", "\x87\xe9\x71\x75\x9a\x1c\xe4\x7a\x51\x4d\x5c\x91\x4c\x39\x2c\x90\x18\xc7\xc4\x6b\xc1\x44\x65\x55\x4a\xfc\xdf\x54\xa5\x07\x0c\x0e"),
HashTestTuple("abcdefghijklmnopqrstuvwxyz", "\x64\x9d\x30\x34\x75\x1e\xa2\x16\x77\x6b\xf9\xa1\x8a\xcc\x81\xbc\x78\x96\x11\x8a\x51\x97\x96\x87\x82\xdd\x1f\xd9\x7d\x8d\x51\x33"),
HashTestTuple("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", "\x38\x43\x04\x55\x83\xaa\xc6\xc8\xc8\xd9\x12\x85\x73\xe7\xa9\x80\x9a\xfb\x2a\x0f\x34\xcc\xc3\x6e\xa9\xe7\x2f\x16\xf6\x36\x8e\x3f"),
HashTestTuple("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", "\x57\x40\xa4\x08\xac\x16\xb7\x20\xb8\x44\x24\xae\x93\x1c\xbb\x1f\xe3\x63\xd1\xd0\xbf\x40\x17\xf1\xa8\x9f\x7e\xa6\xde\x77\xa0\xb8"),
HashTestTuple("12345678901234567890123456789012345678901234567890123456789012345678901234567890", "\x06\xfd\xcc\x7a\x40\x95\x48\xaa\xf9\x13\x68\xc0\x6a\x62\x75\xb5\x53\xe3\xf0\x99\xbf\x0e\xa4\xed\xfd\x67\x78\xdf\x89\xa8\x90\xdd"),
HashTestTuple("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "\xac\x95\x37\x44\xe1\x0e\x31\x51\x4c\x15\x0d\x4d\x8d\x7b\x67\x73\x42\xe3\x33\x99\x78\x82\x96\xe4\x3a\xe4\x85\x0c\xe4\xf9\x79\x78", 15625)
};
HashTestTuple testSet320[] =
{
HashTestTuple("", "\x22\xd6\x5d\x56\x61\x53\x6c\xdc\x75\xc1\xfd\xf5\xc6\xde\x7b\x41\xb9\xf2\x73\x25\xeb\xc6\x1e\x85\x57\x17\x7d\x70\x5a\x0e\xc8\x80\x15\x1c\x3a\x32\xa0\x08\x99\xb8"),
HashTestTuple("a", "\xce\x78\x85\x06\x38\xf9\x26\x58\xa5\xa5\x85\x09\x75\x79\x92\x6d\xda\x66\x7a\x57\x16\x56\x2c\xfc\xf6\xfb\xe7\x7f\x63\x54\x2f\x99\xb0\x47\x05\xd6\x97\x0d\xff\x5d"),
HashTestTuple("abc", "\xde\x4c\x01\xb3\x05\x4f\x89\x30\xa7\x9d\x09\xae\x73\x8e\x92\x30\x1e\x5a\x17\x08\x5b\xef\xfd\xc1\xb8\xd1\x16\x71\x3e\x74\xf8\x2f\xa9\x42\xd6\x4c\xdb\xc4\x68\x2d"),
HashTestTuple("message digest", "\x3a\x8e\x28\x50\x2e\xd4\x5d\x42\x2f\x68\x84\x4f\x9d\xd3\x16\xe7\xb9\x85\x33\xfa\x3f\x2a\x91\xd2\x9f\x84\xd4\x25\xc8\x8d\x6b\x4e\xff\x72\x7d\xf6\x6a\x7c\x01\x97"),
HashTestTuple("abcdefghijklmnopqrstuvwxyz", "\xca\xbd\xb1\x81\x0b\x92\x47\x0a\x20\x93\xaa\x6b\xce\x05\x95\x2c\x28\x34\x8c\xf4\x3f\xf6\x08\x41\x97\x51\x66\xbb\x40\xed\x23\x40\x04\xb8\x82\x44\x63\xe6\xb0\x09"),
HashTestTuple("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", "\xd0\x34\xa7\x95\x0c\xf7\x22\x02\x1b\xa4\xb8\x4d\xf7\x69\xa5\xde\x20\x60\xe2\x59\xdf\x4c\x9b\xb4\xa4\x26\x8c\x0e\x93\x5b\xbc\x74\x70\xa9\x69\xc9\xd0\x72\xa1\xac"),
HashTestTuple("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", "\xed\x54\x49\x40\xc8\x6d\x67\xf2\x50\xd2\x32\xc3\x0b\x7b\x3e\x57\x70\xe0\xc6\x0c\x8c\xb9\xa4\xca\xfe\x3b\x11\x38\x8a\xf9\x92\x0e\x1b\x99\x23\x0b\x84\x3c\x86\xa4"),
HashTestTuple("12345678901234567890123456789012345678901234567890123456789012345678901234567890", "\x55\x78\x88\xaf\x5f\x6d\x8e\xd6\x2a\xb6\x69\x45\xc6\xd2\xa0\xa4\x7e\xcd\x53\x41\xe9\x15\xeb\x8f\xea\x1d\x05\x24\x95\x5f\x82\x5d\xc7\x17\xe4\xa0\x08\xab\x2d\x42"),
HashTestTuple("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "\xbd\xee\x37\xf4\x37\x1e\x20\x64\x6b\x8b\x0d\x86\x2d\xda\x16\x29\x2a\xe3\x6f\x40\x96\x5e\x8c\x85\x09\xe6\x3d\x1d\xbd\xde\xcc\x50\x3e\x2b\x63\xeb\x92\x45\xbb\x66", 15625)
};
bool pass = true;
cout << "\nRIPEMD-128 validation suite running...\n\n";
RIPEMD128 md128;
pass = HashModuleTest(md128, testSet128, sizeof(testSet128)/sizeof(testSet128[0])) && pass;
cout << "\nRIPEMD-160 validation suite running...\n\n";
RIPEMD160 md160;
pass = HashModuleTest(md160, testSet160, sizeof(testSet160)/sizeof(testSet160[0])) && pass;
cout << "\nRIPEMD-256 validation suite running...\n\n";
RIPEMD256 md256;
pass = HashModuleTest(md256, testSet256, sizeof(testSet256)/sizeof(testSet256[0])) && pass;
cout << "\nRIPEMD-320 validation suite running...\n\n";
RIPEMD320 md320;
pass = HashModuleTest(md320, testSet320, sizeof(testSet320)/sizeof(testSet320[0])) && pass;
return pass;
}
#ifdef CRYPTOPP_REMOVED
bool ValidateHAVAL()
{
HashTestTuple testSet[] =
{
HashTestTuple("", "\xC6\x8F\x39\x91\x3F\x90\x1F\x3D\xDF\x44\xC7\x07\x35\x7A\x7D\x70"),
HashTestTuple("a", "\x4D\xA0\x8F\x51\x4A\x72\x75\xDB\xC4\xCE\xCE\x4A\x34\x73\x85\x98\x39\x83\xA8\x30"),
HashTestTuple("HAVAL", "\x0C\x13\x96\xD7\x77\x26\x89\xC4\x67\x73\xF3\xDA\xAC\xA4\xEF\xA9\x82\xAD\xBF\xB2\xF1\x46\x7E\xEA"),
HashTestTuple("0123456789", "\xBE\xBD\x78\x16\xF0\x9B\xAE\xEC\xF8\x90\x3B\x1B\x9B\xC6\x72\xD9\xFA\x42\x8E\x46\x2B\xA6\x99\xF8\x14\x84\x15\x29"),
HashTestTuple("abcdefghijklmnopqrstuvwxyz", "\xC9\xC7\xD8\xAF\xA1\x59\xFD\x9E\x96\x5C\xB8\x3F\xF5\xEE\x6F\x58\xAE\xDA\x35\x2C\x0E\xFF\x00\x55\x48\x15\x3A\x61\x55\x1C\x38\xEE"),
HashTestTuple("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", "\xB4\x5C\xB6\xE6\x2F\x2B\x13\x20\xE4\xF8\xF1\xB0\xB2\x73\xD4\x5A\xDD\x47\xC3\x21\xFD\x23\x99\x9D\xCF\x40\x3A\xC3\x76\x36\xD9\x63")
};
bool pass=true;
cout << "\nHAVAL validation suite running...\n\n";
{
HAVAL3 md(16);
pass = HashModuleTest(md, testSet+0, 1) && pass;
}
{
HAVAL3 md(20);
pass = HashModuleTest(md, testSet+1, 1) && pass;
}
{
HAVAL4 md(24);
pass = HashModuleTest(md, testSet+2, 1) && pass;
}
{
HAVAL4 md(28);
pass = HashModuleTest(md, testSet+3, 1) && pass;
}
{
HAVAL5 md(32);
pass = HashModuleTest(md, testSet+4, 1) && pass;
}
{
HAVAL5 md(32);
pass = HashModuleTest(md, testSet+5, 1) && pass;
}
return pass;
}
#endif
bool ValidatePanama()
{
return RunTestDataFile("TestVectors/panama.txt");
}
bool ValidateWhirlpool()
{
return RunTestDataFile("TestVectors/whrlpool.txt");
}
#ifdef CRYPTOPP_REMOVED
bool ValidateMD5MAC()
{
const byte keys[2][MD5MAC::KEYLENGTH]={
{0x00,0x11,0x22,0x33,0x44,0x55,0x66,0x77,0x88,0x99,0xaa,0xbb,0xcc,0xdd,0xee,0xff},
{0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef,0xfe,0xdc,0xba,0x98,0x76,0x54,0x32,0x10}};
const char *TestVals[7]={
"",
"a",
"abc",
"message digest",
"abcdefghijklmnopqrstuvwxyz",
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
"12345678901234567890123456789012345678901234567890123456789012345678901234567890"};
const byte output[2][7][MD5MAC::DIGESTSIZE]={
{{0x1f,0x1e,0xf2,0x37,0x5c,0xc0,0xe0,0x84,0x4f,0x98,0xe7,0xe8,0x11,0xa3,0x4d,0xa8},
{0x7a,0x76,0xee,0x64,0xca,0x71,0xef,0x23,0x7e,0x26,0x29,0xed,0x94,0x52,0x73,0x65},
{0xe8,0x01,0x3c,0x11,0xf7,0x20,0x9d,0x13,0x28,0xc0,0xca,0xa0,0x4f,0xd0,0x12,0xa6},
{0xc8,0x95,0x53,0x4f,0x22,0xa1,0x74,0xbc,0x3e,0x6a,0x25,0xa2,0xb2,0xef,0xd6,0x30},
{0x91,0x72,0x86,0x7e,0xb6,0x00,0x17,0x88,0x4c,0x6f,0xa8,0xcc,0x88,0xeb,0xe7,0xc9},
{0x3b,0xd0,0xe1,0x1d,0x5e,0x09,0x4c,0xb7,0x1e,0x35,0x44,0xac,0xa9,0xb8,0xbf,0xa2},
{0x93,0x37,0x16,0x64,0x44,0xcc,0x95,0x35,0xb7,0xd5,0xb8,0x0f,0x91,0xe5,0x29,0xcb}},
{{0x2f,0x6e,0x73,0x13,0xbf,0xbb,0xbf,0xcc,0x3a,0x2d,0xde,0x26,0x8b,0x59,0xcc,0x4d},
{0x69,0xf6,0xca,0xff,0x40,0x25,0x36,0xd1,0x7a,0xe1,0x38,0x03,0x2c,0x0c,0x5f,0xfd},
{0x56,0xd3,0x2b,0x6c,0x34,0x76,0x65,0xd9,0x74,0xd6,0xf7,0x5c,0x3f,0xc6,0xf0,0x40},
{0xb8,0x02,0xb2,0x15,0x4e,0x59,0x8b,0x6f,0x87,0x60,0x56,0xc7,0x85,0x46,0x2c,0x0b},
{0x5a,0xde,0xf4,0xbf,0xf8,0x04,0xbe,0x08,0x58,0x7e,0x94,0x41,0xcf,0x6d,0xbd,0x57},
{0x18,0xe3,0x49,0xa5,0x24,0x44,0xb3,0x0e,0x5e,0xba,0x5a,0xdd,0xdc,0xd9,0xf1,0x8d},
{0xf2,0xb9,0x06,0xa5,0xb8,0x4b,0x9b,0x4b,0xbe,0x95,0xed,0x32,0x56,0x4e,0xe7,0xeb}}};
byte digest[MD5MAC::DIGESTSIZE];
bool pass=true, fail;
cout << "\nMD5MAC validation suite running...\n";
for (int k=0; k<2; k++)
{
MD5MAC mac(keys[k]);
cout << "\nKEY: ";
for (int j=0;j<MD5MAC::KEYLENGTH;j++)
cout << setw(2) << setfill('0') << hex << (int)keys[k][j];
cout << endl << endl;
for (int i=0;i<7;i++)
{
mac.Update((byte *)TestVals[i], strlen(TestVals[i]));
mac.Final(digest);
fail = memcmp(digest, output[k][i], MD5MAC::DIGESTSIZE)
|| !mac.VerifyDigest(output[k][i], (byte *)TestVals[i], strlen(TestVals[i]));
pass = pass && !fail;
cout << (fail ? "FAILED " : "passed ");
for (int j=0;j<MD5MAC::DIGESTSIZE;j++)
cout << setw(2) << setfill('0') << hex << (int)digest[j];
cout << " \"" << TestVals[i] << '\"' << endl;
}
}
return pass;
}
#endif
bool ValidateHMAC()
{
return RunTestDataFile("TestVectors/hmac.txt");
}
#ifdef CRYPTOPP_REMOVED
bool ValidateXMACC()
{
typedef XMACC<MD5> XMACC_MD5;
const byte keys[2][XMACC_MD5::KEYLENGTH]={
{0x00,0x11,0x22,0x33,0x44,0x55,0x66,0x77,0x88,0x99,0xaa,0xbb},
{0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef,0xfe,0xdc,0xba,0x98}};
const word32 counters[2]={0xccddeeff, 0x76543210};
const char *TestVals[7]={
"",
"a",
"abc",
"message digest",
"abcdefghijklmnopqrstuvwxyz",
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
"12345678901234567890123456789012345678901234567890123456789012345678901234567890"};
const byte output[2][7][XMACC_MD5::DIGESTSIZE]={
{{0xcc,0xdd,0xef,0x00,0xfa,0x89,0x54,0x92,0x86,0x32,0xda,0x2a,0x3f,0x29,0xc5,0x52,0xa0,0x0d,0x05,0x13},
{0xcc,0xdd,0xef,0x01,0xae,0xdb,0x8b,0x7b,0x69,0x71,0xc7,0x91,0x71,0x48,0x9d,0x18,0xe7,0xdf,0x9d,0x5a},
{0xcc,0xdd,0xef,0x02,0x5e,0x01,0x2e,0x2e,0x4b,0xc3,0x83,0x62,0xc2,0xf4,0xe6,0x18,0x1c,0x44,0xaf,0xca},
{0xcc,0xdd,0xef,0x03,0x3e,0xa9,0xf1,0xe0,0x97,0x91,0xf8,0xe2,0xbe,0xe0,0xdf,0xf3,0x41,0x03,0xb3,0x5a},
{0xcc,0xdd,0xef,0x04,0x2e,0x6a,0x8d,0xb9,0x72,0xe3,0xce,0x9f,0xf4,0x28,0x45,0xe7,0xbc,0x80,0xa9,0xc7},
{0xcc,0xdd,0xef,0x05,0x1a,0xd5,0x40,0x78,0xfb,0x16,0x37,0xfc,0x7a,0x1d,0xce,0xb4,0x77,0x10,0xb2,0xa0},
{0xcc,0xdd,0xef,0x06,0x13,0x2f,0x11,0x47,0xd7,0x1b,0xb5,0x52,0x36,0x51,0x26,0xb0,0x96,0xd7,0x60,0x81}},
{{0x76,0x54,0x32,0x11,0xe9,0xcb,0x74,0x32,0x07,0x93,0xfe,0x01,0xdd,0x27,0xdb,0xde,0x6b,0x77,0xa4,0x56},
{0x76,0x54,0x32,0x12,0xcd,0x55,0x87,0x5c,0xc0,0x35,0x85,0x99,0x44,0x02,0xa5,0x0b,0x8c,0xe7,0x2c,0x68},
{0x76,0x54,0x32,0x13,0xac,0xfd,0x87,0x50,0xc3,0x8f,0xcd,0x58,0xaa,0xa5,0x7e,0x7a,0x25,0x63,0x26,0xd1},
{0x76,0x54,0x32,0x14,0xe3,0x30,0xf5,0xdd,0x27,0x2b,0x76,0x22,0x7f,0xaa,0x90,0x73,0x6a,0x48,0xdb,0x00},
{0x76,0x54,0x32,0x15,0xfc,0x57,0x00,0x20,0x7c,0x9d,0xf6,0x30,0x6f,0xbd,0x46,0x3e,0xfb,0x8a,0x2c,0x60},
{0x76,0x54,0x32,0x16,0xfb,0x0f,0xd3,0xdf,0x4c,0x4b,0xc3,0x05,0x9d,0x63,0x1e,0xba,0x25,0x2b,0xbe,0x35},
{0x76,0x54,0x32,0x17,0xc6,0xfe,0xe6,0x5f,0xb1,0x35,0x8a,0xf5,0x32,0x7a,0x80,0xbd,0xb8,0x72,0xee,0xae}}};
byte digest[XMACC_MD5::DIGESTSIZE];
bool pass=true, fail;
cout << "\nXMACC/MD5 validation suite running...\n";
for (int k=0; k<2; k++)
{
XMACC_MD5 mac(keys[k], counters[k]);
cout << "\nKEY: ";
for (int j=0;j<XMACC_MD5::KEYLENGTH;j++)
cout << setw(2) << setfill('0') << hex << (int)keys[k][j];
cout << " COUNTER: 0x" << hex << counters[k] << endl << endl;
for (int i=0;i<7;i++)
{
mac.Update((byte *)TestVals[i], strlen(TestVals[i]));
mac.Final(digest);
fail = memcmp(digest, output[k][i], XMACC_MD5::DIGESTSIZE)
|| !mac.VerifyDigest(output[k][i], (byte *)TestVals[i], strlen(TestVals[i]));
pass = pass && !fail;
cout << (fail ? "FAILED " : "passed ");
for (int j=0;j<XMACC_MD5::DIGESTSIZE;j++)
cout << setw(2) << setfill('0') << hex << (int)digest[j];
cout << " \"" << TestVals[i] << '\"' << endl;
}
}
return pass;
}
#endif
bool ValidateTTMAC()
{
const byte key[TTMAC::KEYLENGTH]={
0x00,0x11,0x22,0x33,0x44,0x55,0x66,0x77,0x88,0x99,
0xaa,0xbb,0xcc,0xdd,0xee,0xff,0x01,0x23,0x45,0x67};
const char *TestVals[8]={
"",
"a",
"abc",
"message digest",
"abcdefghijklmnopqrstuvwxyz",
"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
"12345678901234567890123456789012345678901234567890123456789012345678901234567890"};
const byte output[8][TTMAC::DIGESTSIZE]={
{0x2d,0xec,0x8e,0xd4,0xa0,0xfd,0x71,0x2e,0xd9,0xfb,0xf2,0xab,0x46,0x6e,0xc2,0xdf,0x21,0x21,0x5e,0x4a},
{0x58,0x93,0xe3,0xe6,0xe3,0x06,0x70,0x4d,0xd7,0x7a,0xd6,0xe6,0xed,0x43,0x2c,0xde,0x32,0x1a,0x77,0x56},
{0x70,0xbf,0xd1,0x02,0x97,0x97,0xa5,0xc1,0x6d,0xa5,0xb5,0x57,0xa1,0xf0,0xb2,0x77,0x9b,0x78,0x49,0x7e},
{0x82,0x89,0xf4,0xf1,0x9f,0xfe,0x4f,0x2a,0xf7,0x37,0xde,0x4b,0xd7,0x1c,0x82,0x9d,0x93,0xa9,0x72,0xfa},
{0x21,0x86,0xca,0x09,0xc5,0x53,0x31,0x98,0xb7,0x37,0x1f,0x24,0x52,0x73,0x50,0x4c,0xa9,0x2b,0xae,0x60},
{0x8a,0x7b,0xf7,0x7a,0xef,0x62,0xa2,0x57,0x84,0x97,0xa2,0x7c,0x0d,0x65,0x18,0xa4,0x29,0xe7,0xc1,0x4d},
{0x54,0xba,0xc3,0x92,0xa8,0x86,0x80,0x6d,0x16,0x95,0x56,0xfc,0xbb,0x67,0x89,0xb5,0x4f,0xb3,0x64,0xfb},
{0x0c,0xed,0x2c,0x9f,0x8f,0x0d,0x9d,0x03,0x98,0x1a,0xb5,0xc8,0x18,0x4b,0xac,0x43,0xdd,0x54,0xc4,0x84}};
byte digest[TTMAC::DIGESTSIZE];
bool pass=true, fail;
cout << "\nTwo-Track-MAC validation suite running...\n";
TTMAC mac(key, sizeof(key));
for (int k=0; k<sizeof(TestVals)/sizeof(TestVals[0]); k++)
{
mac.Update((byte *)TestVals[k], strlen(TestVals[k]));
mac.Final(digest);
fail = memcmp(digest, output[k], TTMAC::DIGESTSIZE)
|| !mac.VerifyDigest(output[k], (byte *)TestVals[k], strlen(TestVals[k]));
pass = pass && !fail;
cout << (fail ? "FAILED " : "passed ");
for (int j=0;j<TTMAC::DIGESTSIZE;j++)
cout << setw(2) << setfill('0') << hex << (int)digest[j];
cout << " \"" << TestVals[k] << '\"' << endl;
}
return true;
}
struct PBKDF_TestTuple
{
byte purpose;
unsigned int iterations;
const char *hexPassword, *hexSalt, *hexDerivedKey;
};
bool TestPBKDF(PasswordBasedKeyDerivationFunction &pbkdf, const PBKDF_TestTuple *testSet, unsigned int testSetSize)
{
bool pass = true;
for (unsigned int i=0; i<testSetSize; i++)
{
const PBKDF_TestTuple &tuple = testSet[i];
string password, salt, derivedKey;
StringSource(tuple.hexPassword, true, new HexDecoder(new StringSink(password)));
StringSource(tuple.hexSalt, true, new HexDecoder(new StringSink(salt)));
StringSource(tuple.hexDerivedKey, true, new HexDecoder(new StringSink(derivedKey)));
SecByteBlock derived(derivedKey.size());
pbkdf.DeriveKey(derived, derived.size(), tuple.purpose, (byte *)password.data(), password.size(), (byte *)salt.data(), salt.size(), tuple.iterations);
bool fail = memcmp(derived, derivedKey.data(), derived.size()) != 0;
pass = pass && !fail;
HexEncoder enc(new FileSink(cout));
cout << (fail ? "FAILED " : "passed ");
enc.Put(tuple.purpose);
cout << " " << tuple.iterations;
cout << " " << tuple.hexPassword << " " << tuple.hexSalt << " ";
enc.Put(derived, derived.size());
cout << endl;
}
return pass;
}
bool ValidatePBKDF()
{
bool pass = true;
{
// from OpenSSL PKCS#12 Program FAQ v1.77, at http://www.drh-consultancy.demon.co.uk/test.txt
PBKDF_TestTuple testSet[] =
{
{1, 1, "0073006D006500670000", "0A58CF64530D823F", "8AAAE6297B6CB04642AB5B077851284EB7128F1A2A7FBCA3"},
{2, 1, "0073006D006500670000", "0A58CF64530D823F", "79993DFE048D3B76"},
{1, 1, "0073006D006500670000", "642B99AB44FB4B1F", "F3A95FEC48D7711E985CFE67908C5AB79FA3D7C5CAA5D966"},
{2, 1, "0073006D006500670000", "642B99AB44FB4B1F", "C0A38D64A79BEA1D"},
{3, 1, "0073006D006500670000", "3D83C0E4546AC140", "8D967D88F6CAA9D714800AB3D48051D63F73A312"},
{1, 1000, "007100750065006500670000", "05DEC959ACFF72F7", "ED2034E36328830FF09DF1E1A07DD357185DAC0D4F9EB3D4"},
{2, 1000, "007100750065006500670000", "05DEC959ACFF72F7", "11DEDAD7758D4860"},
{1, 1000, "007100750065006500670000", "1682C0FC5B3F7EC5", "483DD6E919D7DE2E8E648BA8F862F3FBFBDC2BCB2C02957F"},
{2, 1000, "007100750065006500670000", "1682C0FC5B3F7EC5", "9D461D1B00355C50"},
{3, 1000, "007100750065006500670000", "263216FCC2FAB31C", "5EC4C7A80DF652294C3925B6489A7AB857C83476"}
};
PKCS12_PBKDF<SHA1> pbkdf;
cout << "\nPKCS #12 PBKDF validation suite running...\n\n";
pass = TestPBKDF(pbkdf, testSet, sizeof(testSet)/sizeof(testSet[0])) && pass;
}
{
// from draft-ietf-smime-password-03.txt, at http://www.imc.org/draft-ietf-smime-password
PBKDF_TestTuple testSet[] =
{
{0, 5, "70617373776f7264", "1234567878563412", "D1DAA78615F287E6"},
{0, 500, "416C6C206E2D656E746974696573206D75737420636F6D6D756E69636174652077697468206F74686572206E2d656E74697469657320766961206E2D3120656E746974656568656568656573", "1234567878563412","6A8970BF68C92CAEA84A8DF28510858607126380CC47AB2D"}
};
PKCS5_PBKDF2_HMAC<SHA1> pbkdf;
cout << "\nPKCS #5 PBKDF2 validation suite running...\n\n";
pass = TestPBKDF(pbkdf, testSet, sizeof(testSet)/sizeof(testSet[0])) && pass;
}
return pass;
}
| [
"tungnt.rec@gmail.com"
] | tungnt.rec@gmail.com |
9a26b6bc02688699384041efe03fa4c853984504 | a89bc39841d7ca7d8ef0002b4b83fb2a63c07a5a | /zp/manager/gamemodes.cpp | 8b74f65e8a98f9d0821c21e4c45ab611adf66b2c | [] | no_license | Zipcore/Zombie-Plague | c0e033eff196160bcc6e2deb303f25481ef43730 | bae371cca9e73528b8c3121d709ae76442146bb2 | refs/heads/master | 2020-04-11T06:35:51.715936 | 2018-12-10T11:53:26 | 2018-12-10T11:53:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 27,907 | cpp | /**
* ============================================================================
*
* Zombie Plague Mod #3 Generation
*
* File: gamemodes.cpp
* Type: Manager
* Description: Game Modes generator.
*
* Copyright (C) 2015-2018 Nikita Ushakov (Ireland, Dublin)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* ============================================================================
**/
/**
* Number of max valid game modes.
**/
#define GameModesMax 32
/**
* Array handle to store game mode native data.
**/
ArrayList arrayGameModes;
/**
* Mode native data indexes.
**/
enum
{
GAMEMODES_DATA_NAME,
GAMEMODES_DATA_DESCRIPTION,
GAMEMODES_DATA_SOUND,
GAMEMODES_DATA_SOUND_ID,
GAMEMODES_DATA_CHANCE,
GAMEMODES_DATA_MINPLAYERS,
GAMEMODES_DATA_RATIO,
GAMEMODES_DATA_INFECTION,
GAMEMODES_DATA_RESPAWN,
GAMEMODES_DATA_SURVIVOR,
GAMEMODES_DATA_NEMESIS
}
/**
* Initialization of game modes.
**/
void GameModesLoad(/*void*/)
{
// No game modes?
if(arrayGameModes == INVALID_HANDLE)
{
LogEvent(false, LogType_Fatal, LOG_CORE_EVENTS, LogModule_Gamemodes, "Game Mode Validation", "No game modes loaded");
}
// Initialize variable
static char sBuffer[NORMAL_LINE_LENGTH];
// Precache of the game modes
int iSize = arrayGameModes.Length;
for(int i = 0; i < iSize; i++)
{
// Load sounds
ModesGetSound(i, sBuffer, sizeof(sBuffer));
ModesSetSoundID(i, SoundsKeyToIndex(sBuffer));
}
// Forward event to modules (FakeHook)
RoundStartOnRoundPreStart();
RoundStartOnRoundStart();
// Create timer for starting game mode
CreateTimer(1.0, GameModesStart, _, TIMER_REPEAT | TIMER_FLAG_NO_MAPCHANGE);
}
/**
* Main timer for start zombie round.
*
* @param hTimer The timer handle.
**/
public Action GameModesStart(Handle hTimer)
{
// If gamemodes disabled, then stop
if(!gCvarList[CVAR_GAME_CUSTOM_START].IntValue)
{
return Plugin_Stop;
}
// If round didn't start yet
if(gServerData[Server_RoundNew])
{
// Gets amount of total alive players
int nAlive = fnGetAlive();
// Switch amount of alive players
switch(nAlive)
{
// Wait other players
case 0, 1 : { /*break*/ }
// If players exists
default :
{
// If counter is counting ?
if(gServerData[Server_RoundCount])
{
// Validate beginning
if(gServerData[Server_RoundCount] == (gCvarList[CVAR_GAME_CUSTOM_START].IntValue - 2))
{
// If help messages enabled, then proceed
if(gCvarList[CVAR_MESSAGES_HELP].BoolValue)
{
// Show help information
TranslationPrintToChatAll("general round objective");
TranslationPrintToChatAll("general ammunition reminder");
TranslationPrintHintTextAll("general buttons reminder");
}
// Emit round start sound
SoundsInputEmitToAll(gServerKey[Round_Start], 0, SOUND_FROM_PLAYER, SNDCHAN_STATIC, gCvarList[CVAR_GAME_CUSTOM_SOUND_LEVEL].IntValue);
}
// Validate counter
if(SoundsInputEmitToAll(gServerKey[Round_Count], gServerData[Server_RoundCount], SOUND_FROM_PLAYER, SNDCHAN_STATIC, gCvarList[CVAR_GAME_CUSTOM_SOUND_LEVEL].IntValue))
{
// If help messages enabled, then proceed
if(gCvarList[CVAR_MESSAGES_HELP].BoolValue)
{
// Show help information
TranslationPrintHintTextAll("zombie comming", gServerData[Server_RoundCount]);
}
}
}
// If else, than start game
else
{
GameModesEventStart();
}
// Substitute second
gServerData[Server_RoundCount]--;
}
}
}
// If not, then wait
return Plugin_Continue;
}
/**
* Called right before mode is started.
*
* @param modeIndex (Optional) The mode index.
* @param selectedIndex (Optional) The selected index.
**/
void GameModesEventStart(int modeIndex = -1, const int selectedIndex = 0)
{
// Initalize some variables
static int lastMode; static int defaultMode; int nAlive = fnGetAlive();
// Validate random mode
if(modeIndex == -1)
{
// i = mode number
int iCount = arrayGameModes.Length;
for(int i = 0; i < iCount; i++)
{
// Starting default game mode ?
if(lastMode != i && GetRandomInt(1, ModesGetChance(i)) == ModesGetChance(i) && nAlive > ModesGetMinPlayers(i)) modeIndex = i;
else if(!ModesGetChance(i)) defaultMode = i; //! Find a default mode
}
// Try choosing a default game mode
if(modeIndex == -1) modeIndex = defaultMode;
}
// Initialize buffer char
static char sBuffer[SMALL_LINE_LENGTH];
// Sets chosen game mode index
gServerData[Server_RoundMode] = modeIndex;
// Compute the maximumum zombie amount
int nMaxZombies = RoundToCeil(nAlive * ModesGetRatio(modeIndex));
if(nMaxZombies == nAlive) nMaxZombies--; //! Subsract for a high ratio
else if(!nMaxZombies) nMaxZombies++; //! Increment for a low ratio
// Print game mode description
ModesGetDesc(modeIndex, sBuffer, sizeof(sBuffer));
if(strlen(sBuffer)) TranslationPrintHintTextAll(sBuffer);
// Play game mode sounds
SoundsInputEmitToAll(ModesGetSoundID(modeIndex), 0, SOUND_FROM_PLAYER, SNDCHAN_STATIC, gCvarList[CVAR_GAME_CUSTOM_SOUND_LEVEL].IntValue);
// Random players should be zombie
GameModesTurnIntoZombie(selectedIndex, nMaxZombies);
// Remaining players should be humans
GameModesTurnIntoHuman();
// Call forward
API_OnZombieModStarted(modeIndex);
// Resets server grobal variables
gServerData[Server_RoundNew] = false;
gServerData[Server_RoundEnd] = false;
gServerData[Server_RoundStart] = true;
// Update mode index for the next round
lastMode = gServerData[Server_RoundMode];
}
/**
* Turn random players into the zombies.
*
* @param selectedIndex The selected index.
* @param MaxZombies The amount of zombies.
**/
void GameModesTurnIntoZombie(const int selectedIndex, const int MaxZombies)
{
// Validate client for a given client index
if(IsPlayerExist(selectedIndex))
{
// Validate survivor mode
if(ModesIsSurvivor(gServerData[Server_RoundMode]))
{
// Make a survivor
ClassMakeHuman(selectedIndex, true);
}
else
{
// Make a zombie/nemesis
ClassMakeZombie(selectedIndex, _, ModesIsNemesis(gServerData[Server_RoundMode]));
return;
}
}
// i = zombie index
for(int i = 0; i < MaxZombies; i++)
{
// Make a zombie/nemesis
ClassMakeZombie(fnGetRandomHuman(), _, ModesIsNemesis(gServerData[Server_RoundMode]));
}
}
/**
* Turn remaining players into the humans.
**/
void GameModesTurnIntoHuman(/*void*/)
{
// i = client index
for(int i = 1; i <= MaxClients; i++)
{
// Verify that the client is exist
if(!IsPlayerExist(i))
{
continue;
}
// Verify that the client is human
if(gClientData[i][Client_Zombie] || gClientData[i][Client_Survivor])
{
continue;
}
// Validate survivor mode
if(ModesIsSurvivor(gServerData[Server_RoundMode]))
{
// Make a survivor
ClassMakeHuman(i, true);
}
else
{
// Switch to CT
bool bState = ToolsGetClientDefuser(i);
ToolsSetClientTeam(i, TEAM_HUMAN);
ToolsSetClientDefuser(i, bState);
// Sets glowing for the zombie vision
ToolsSetClientDetecting(i, gCvarList[CVAR_ZOMBIE_XRAY].BoolValue);
}
}
}
/*
* Game modes natives API.
*/
/**
* Gets the current game mode.
*
* native int ZP_GetCurrentGameMode();
**/
public int API_GetCurrentGameMode(Handle isPlugin, const int iNumParams)
{
// Return the value
return gServerData[Server_RoundMode];
}
/**
* Gets the amount of all game modes.
*
* native int ZP_GetNumberGameMode();
**/
public int API_GetNumberGameMode(Handle isPlugin, const int iNumParams)
{
// Return the value
return arrayGameModes.Length;
}
/**
* Gets the index of a game mode at a given name.
*
* native int ZP_GetServerGameMode(name);
**/
public int API_GetServerGameMode(Handle isPlugin, const int iNumParams)
{
// Retrieves the string length from a native parameter string
int maxLen;
GetNativeStringLength(1, maxLen);
// Validate size
if(!maxLen)
{
LogEvent(false, LogType_Native, LOG_CORE_EVENTS, LogModule_Gamemodes, "Native Validation", "Can't find mode with an empty name");
return -1;
}
// Gets native data
static char sName[SMALL_LINE_LENGTH];
// General
GetNativeString(1, sName, sizeof(sName));
// i = mode number
int iCount = arrayGameModes.Length;
for(int i = 0; i < iCount; i++)
{
// Gets the name of a game mode at a given index
static char sModeName[SMALL_LINE_LENGTH];
ModesGetName(i, sModeName, sizeof(sModeName));
// If names match, then return index
if(!strcmp(sName, sModeName, false))
{
return i;
}
}
// Return on the unsuccess
return -1;
}
/**
* Sets the index of a game mode at a given name.
*
* native int ZP_SetServerGameMode(name, client);
**/
public int API_SetServerGameMode(Handle isPlugin, const int iNumParams)
{
// If mode doesn't started yet, then stop
if(!gServerData[Server_RoundNew])
{
LogEvent(false, LogType_Native, LOG_CORE_EVENTS, LogModule_Gamemodes, "Native Validation", "Can't start game mode during the round");
return -1;
}
// Retrieves the string length from a native parameter string
int maxLen;
GetNativeStringLength(1, maxLen);
// Validate size
if(!maxLen)
{
LogEvent(false, LogType_Native, LOG_CORE_EVENTS, LogModule_Gamemodes, "Native Validation", "Can't find mode with an empty name");
return -1;
}
// Gets native data
static char sName[SMALL_LINE_LENGTH];
// General
GetNativeString(1, sName, sizeof(sName));
// Gets real player index from native cell
int clientIndex = GetNativeCell(2);
// Validate client
if(clientIndex && !IsPlayerExist(clientIndex))
{
LogEvent(false, LogType_Native, LOG_CORE_EVENTS, LogModule_Gamemodes, "Native Validation", "Invalid the client index (%d)", clientIndex);
return -1;
}
// i = mode number
int iCount = arrayGameModes.Length;
for(int i = 0; i < iCount; i++)
{
// Gets the name of a game mode at a given index
static char sModeName[SMALL_LINE_LENGTH];
ModesGetName(i, sModeName, sizeof(sModeName));
// If names match, then return index
if(!strcmp(sName, sModeName, false))
{
// Start the game mode
GameModesEventStart(i, clientIndex);
return i;
}
}
// Return on the unsuccess
return -1;
}
/**
* Load game modes from other plugin.
*
* native int ZP_RegisterGameMode(name, desc, sound, chance, min, ratio, infect, respawn, survivor, nemesis)
**/
public int API_RegisterGameMode(Handle isPlugin, const int iNumParams)
{
// If array hasn't been created, then create
if(arrayGameModes == INVALID_HANDLE)
{
// Create array in handle
arrayGameModes = CreateArray(GameModesMax);
}
// Retrieves the string length from a native parameter string
int maxLen;
GetNativeStringLength(1, maxLen);
// Validate size
if(!maxLen)
{
LogEvent(false, LogType_Native, LOG_CORE_EVENTS, LogModule_Gamemodes, "Native Validation", "Can't register game mode with an empty name");
return -1;
}
// Gets game modes amount
int iCount = arrayGameModes.Length;
// Maximum amout of game modes
if(iCount >= GameModesMax)
{
LogEvent(false, LogType_Native, LOG_CORE_EVENTS, LogModule_Gamemodes, "Native Validation", "Maximum number of game modes reached (%d). Skipping other modes.", GameModesMax);
return -1;
}
// Initialize variables
char sModeBuffer[SMALL_LINE_LENGTH];
char sModeName[SMALL_LINE_LENGTH];
// General
GetNativeString(1, sModeBuffer, sizeof(sModeBuffer));
// i = mode number
for(int i = 0; i < iCount; i++)
{
// Gets the name of a game mode at a given index
ModesGetName(i, sModeName, sizeof(sModeName));
// If names match, then stop
if(!strcmp(sModeBuffer, sModeName, false))
{
return i;
}
}
// Initialize array block
ArrayList arrayGameMode = CreateArray(GameModesMax);
// Push native data into array
arrayGameMode.PushString(sModeBuffer); // Index: 0
GetNativeString(2, sModeBuffer, sizeof(sModeBuffer));
if(!TranslationPhraseExists(sModeBuffer) && strlen(sModeBuffer))
{
LogEvent(false, LogType_Native, LOG_CORE_EVENTS, LogModule_Gamemodes, "Native Validation", "Couldn't cache game mode desc: \"%s\" (check translation file)", sModeBuffer);
return -1;
}
arrayGameMode.PushString(sModeBuffer); // Index: 1
GetNativeString(3, sModeBuffer, sizeof(sModeBuffer));
arrayGameMode.PushString(sModeBuffer); // Index: 2
arrayGameMode.Push(-1); // Index: 3
arrayGameMode.Push(GetNativeCell(4)); // Index: 4
arrayGameMode.Push(GetNativeCell(5)); // Index: 5
arrayGameMode.Push(GetNativeCell(6)); // Index: 6
arrayGameMode.Push(GetNativeCell(7)); // Index: 7
arrayGameMode.Push(GetNativeCell(8)); // Index: 8
arrayGameMode.Push(GetNativeCell(9)); // Index: 9
arrayGameMode.Push(GetNativeCell(10)); // Index: 10
// Store this handle in the main array
arrayGameModes.Push(arrayGameMode);
// Return id under which we registered the item
return arrayGameModes.Length-1;
}
/**
* Gets the name of a game mode at a given index.
*
* native void ZP_GetGameModeName(iD, sName, maxLen);
**/
public int API_GetGameModeName(Handle isPlugin, const int iNumParams)
{
// Gets mode index from native cell
int iD = GetNativeCell(1);
// Validate no game mode
if(iD == -1)
{
return iD;
}
// Validate index
if(iD >= arrayGameModes.Length)
{
LogEvent(false, LogType_Native, LOG_CORE_EVENTS, LogModule_Gamemodes, "Native Validation", "Invalid the mode index (%d)", iD);
return -1;
}
// Gets string size from native cell
int maxLen = GetNativeCell(3);
// Validate size
if(!maxLen)
{
LogEvent(false, LogType_Native, LOG_CORE_EVENTS, LogModule_Gamemodes, "Native Validation", "No buffer size");
return -1;
}
// Initialize name char
static char sName[SMALL_LINE_LENGTH];
ModesGetName(iD, sName, sizeof(sName));
// Return on success
return SetNativeString(2, sName, maxLen);
}
/**
* Gets the description of a game mode at a given index.
*
* native void ZP_GetGameModeDesc(iD, sName, maxLen);
**/
public int API_GetGameModeDesc(Handle isPlugin, const int iNumParams)
{
// Gets mode index from native cell
int iD = GetNativeCell(1);
// Validate no game mode
if(iD == -1)
{
return iD;
}
// Validate index
if(iD >= arrayGameModes.Length)
{
LogEvent(false, LogType_Native, LOG_CORE_EVENTS, LogModule_Gamemodes, "Native Validation", "Invalid the mode index (%d)", iD);
return -1;
}
// Gets string size from native cell
int maxLen = GetNativeCell(3);
// Validate size
if(!maxLen)
{
LogEvent(false, LogType_Native, LOG_CORE_EVENTS, LogModule_Gamemodes, "Native Validation", "No buffer size");
return -1;
}
// Initialize description char
static char sName[SMALL_LINE_LENGTH];
ModesGetDesc(iD, sName, sizeof(sName));
// Return on success
return SetNativeString(2, sName, maxLen);
}
/**
* Gets the sound key of the game mode.
*
* native int ZP_GetGameModeSoundID(iD);
**/
public int API_GetGameModeSoundID(Handle isPlugin, const int iNumParams)
{
// Gets mode index from native cell
int iD = GetNativeCell(1);
// Validate no game mode
if(iD == -1)
{
return iD;
}
// Validate index
if(iD >= arrayGameModes.Length)
{
LogEvent(false, LogType_Native, LOG_CORE_EVENTS, LogModule_Gamemodes, "Native Validation", "Invalid the mode index (%d)", iD);
return -1;
}
// Return value
return ModesGetSoundID(iD);
}
/**
* Gets the chance of the game mode.
*
* native int ZP_GetGameModeChance(iD);
**/
public int API_GetGameModeChance(Handle isPlugin, const int iNumParams)
{
// Gets mode index from native cell
int iD = GetNativeCell(1);
// Validate no game mode
if(iD == -1)
{
return iD;
}
// Validate index
if(iD >= arrayGameModes.Length)
{
LogEvent(false, LogType_Native, LOG_CORE_EVENTS, LogModule_Gamemodes, "Native Validation", "Invalid the mode index (%d)", iD);
return -1;
}
// Return value
return ModesGetChance(iD);
}
/**
* Gets the min players of the game mode.
*
* native int ZP_GetGameModeMinPlayers(iD);
**/
public int API_GetGameModeMinPlayers(Handle isPlugin, const int iNumParams)
{
// Gets mode index from native cell
int iD = GetNativeCell(1);
// Validate no game mode
if(iD == -1)
{
return iD;
}
// Validate index
if(iD >= arrayGameModes.Length)
{
LogEvent(false, LogType_Native, LOG_CORE_EVENTS, LogModule_Gamemodes, "Native Validation", "Invalid the mode index (%d)", iD);
return -1;
}
// Return value
return ModesGetMinPlayers(iD);
}
/**
* Gets the ratio of the game mode.
*
* native float ZP_GetGameModeRatio(iD);
**/
public int API_GetGameModeRatio(Handle isPlugin, const int iNumParams)
{
// Gets mode index from native cell
int iD = GetNativeCell(1);
// Validate no game mode
if(iD == -1)
{
return iD;
}
// Validate index
if(iD >= arrayGameModes.Length)
{
LogEvent(false, LogType_Native, LOG_CORE_EVENTS, LogModule_Gamemodes, "Native Validation", "Invalid the mode index (%d)", iD);
return -1;
}
// Return value (Float fix)
return view_as<int>(ModesGetRatio(iD));
}
/**
* Check the infection type of the game mode.
*
* native bool ZP_IsGameModeInfect(iD);
**/
public int API_IsGameModeInfect(Handle isPlugin, const int iNumParams)
{
// Gets mode index from native cell
int iD = GetNativeCell(1);
// Validate no game mode
if(iD == -1)
{
return false;
}
// Validate index
if(iD >= arrayGameModes.Length)
{
LogEvent(false, LogType_Native, LOG_CORE_EVENTS, LogModule_Gamemodes, "Native Validation", "Invalid the mode index (%d)", iD);
return -1;
}
// Return value
return ModesIsInfection(iD);
}
/**
* Check the respawn type of the game mode.
*
* native bool ZP_IsGameModeRespawn(iD);
**/
public int API_IsGameModeRespawn(Handle isPlugin, const int iNumParams)
{
// Gets mode index from native cell
int iD = GetNativeCell(1);
// Validate no game mode
if(iD == -1)
{
return false;
}
// Validate index
if(iD >= arrayGameModes.Length)
{
LogEvent(false, LogType_Native, LOG_CORE_EVENTS, LogModule_Gamemodes, "Native Validation", "Invalid the mode index (%d)", iD);
return -1;
}
// Return value
return ModesIsRespawn(iD);
}
/**
* Check the survivor type of the game mode.
*
* native bool ZP_IsGameModeSurvivor(iD);
**/
public int API_IsGameModeSurvivor(Handle isPlugin, const int iNumParams)
{
// Gets mode index from native cell
int iD = GetNativeCell(1);
// Validate no game mode
if(iD == -1)
{
return false;
}
// Validate index
if(iD >= arrayGameModes.Length)
{
LogEvent(false, LogType_Native, LOG_CORE_EVENTS, LogModule_Gamemodes, "Native Validation", "Invalid the mode index (%d)", iD);
return -1;
}
// Return value
return ModesIsSurvivor(iD);
}
/**
* Check the nemesis type of the game mode.
*
* native bool ZP_IsGameModeNemesis(iD);
**/
public int API_IsGameModeNemesis(Handle isPlugin, const int iNumParams)
{
// Gets mode index from native cell
int iD = GetNativeCell(1);
// Validate no game mode
if(iD == -1)
{
return false;
}
// Validate index
if(iD >= arrayGameModes.Length)
{
LogEvent(false, LogType_Native, LOG_CORE_EVENTS, LogModule_Gamemodes, "Native Validation", "Invalid the mode index (%d)", iD);
return -1;
}
// Return value
return ModesIsNemesis(iD);
}
/*
* Game modes data reading API.
*/
/**
* Gets the name of a game mode at a given index.
*
* @param iD The game mode index.
* @param sName The string to return name in.
* @param iMaxLen The max length of the string.
**/
stock void ModesGetName(const int iD, char[] sName, const int iMaxLen)
{
// Gets array handle of game mode at given index
ArrayList arrayGameMode = arrayGameModes.Get(iD);
// Gets game mode name
arrayGameMode.GetString(GAMEMODES_DATA_NAME, sName, iMaxLen);
}
/**
* Gets the description of a game mode at a given index.
*
* @param iD The game mode index.
* @param sDesc The string to return name in.
* @param iMaxLen The max length of the string.
**/
stock void ModesGetDesc(const int iD, char[] sDesc, const int iMaxLen)
{
// Gets array handle of game mode at given index
ArrayList arrayGameMode = arrayGameModes.Get(iD);
// Gets game mode description
arrayGameMode.GetString(GAMEMODES_DATA_DESCRIPTION, sDesc, iMaxLen);
}
/**
* Gets the sound of a game mode at a given index.
*
* @param iD The game mode index.
* @param sDesc The string to return name in.
* @param iMaxLen The max length of the string.
**/
stock void ModesGetSound(const int iD, char[] sDesc, const int iMaxLen)
{
// Gets array handle of game mode at given index
ArrayList arrayGameMode = arrayGameModes.Get(iD);
// Gets game mode sound
arrayGameMode.GetString(GAMEMODES_DATA_SOUND, sDesc, iMaxLen);
}
/**
* Gets the sound key of the game mode.
*
* @param iD The game mode index.
* @return The key index.
**/
stock int ModesGetSoundID(const int iD)
{
// Gets array handle of game mode at given index
ArrayList arrayGameMode = arrayGameModes.Get(iD);
// Gets game mode sound key
return arrayGameMode.Get(GAMEMODES_DATA_SOUND_ID);
}
/**
* Sets the sound key of the game mode.
*
* @param iD The game mode index.
* @param iKey The key index.
**/
stock int ModesSetSoundID(const int iD, const int iKey)
{
// Gets array handle of game mode at given index
ArrayList arrayGameMode = arrayGameModes.Get(iD);
// Sets game mode sound key
arrayGameMode.Set(GAMEMODES_DATA_SOUND_ID, iKey);
}
/**
* Gets the chance of the game mode.
*
* @param iD The game mode index.
* @return The chance amount.
**/
stock int ModesGetChance(const int iD)
{
// Gets array handle of game mode at given index
ArrayList arrayGameMode = arrayGameModes.Get(iD);
// Gets game mode chance
return arrayGameMode.Get(GAMEMODES_DATA_CHANCE);
}
/**
* Gets the min players of the game mode.
*
* @param iD The game mode index.
* @return The min players amount.
**/
stock int ModesGetMinPlayers(const int iD)
{
// Gets array handle of game mode at given index
ArrayList arrayGameMode = arrayGameModes.Get(iD);
// Gets game mode chance
return arrayGameMode.Get(GAMEMODES_DATA_MINPLAYERS);
}
/**
* Gets the ratio of the game mode.
*
* @param iD The game mode index.
* @return The ratio amount.
**/
stock float ModesGetRatio(const int iD)
{
// Gets array handle of game mode at given index
ArrayList arrayGameMode = arrayGameModes.Get(iD);
// Gets game mode ratio
return arrayGameMode.Get(GAMEMODES_DATA_RATIO);
}
/**
* Check the infection type of the game mode.
*
* @param iD The game mode index.
* @return True or false.
**/
stock bool ModesIsInfection(const int iD)
{
// Validate no game mode
if(iD == -1)
{
return false;
}
// Gets array handle of game mode at given index
ArrayList arrayGameMode = arrayGameModes.Get(iD);
// Gets game mode infection type
return arrayGameMode.Get(GAMEMODES_DATA_INFECTION);
}
/**
* Check the respawn type of the game mode.
*
* @param iD The game mode index.
* @return True or false.
**/
stock bool ModesIsRespawn(const int iD)
{
// Validate no game mode
if(iD == -1)
{
return false;
}
// Gets array handle of game mode at given index
ArrayList arrayGameMode = arrayGameModes.Get(iD);
// Gets game mode respawn type
return arrayGameMode.Get(GAMEMODES_DATA_RESPAWN);
}
/**
* Check the survivor type of the game mode.
*
* @param iD The game mode index.
* @return True or false.
**/
stock bool ModesIsSurvivor(const int iD)
{
// Validate no game mode
if(iD == -1)
{
return false;
}
// Gets array handle of game mode at given index
ArrayList arrayGameMode = arrayGameModes.Get(iD);
// Gets game mode survivor type
return arrayGameMode.Get(GAMEMODES_DATA_SURVIVOR);
}
/**
* Check the nemesis type of the game mode.
*
* @param iD The game mode index.
* @return True or false.
**/
stock bool ModesIsNemesis(const int iD)
{
// Validate no game mode
if(iD == -1)
{
return false;
}
// Gets array handle of game mode at given index
ArrayList arrayGameMode = arrayGameModes.Get(iD);
// Gets game mode nemesis type
return arrayGameMode.Get(GAMEMODES_DATA_NEMESIS);
}
| [
"ushakovn@tcd.ie"
] | ushakovn@tcd.ie |
3344aec57938ac70c79e3dd75784140f7b8c58dd | b733a2069739e38162b68ee486d033b31e9aefb8 | /include/Lz/Take.hpp | 2e14508c6d207185629f80bd3c420a5599028403 | [
"MIT"
] | permissive | ywhwang/cpp-lazy | 88f93a30709096ecfa9840afb53df7612880dd66 | 6b989a4fac93937c18e52a6cf0bbf9d9b7b33fa2 | refs/heads/master | 2023-08-30T16:36:53.674785 | 2021-11-09T09:56:44 | 2021-11-09T09:56:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,469 | hpp | #pragma once
#ifndef LZ_TAKE_HPP
# define LZ_TAKE_HPP
# include "detail/BasicIteratorView.hpp"
namespace lz {
// Start of group
/**
* @defgroup ItFns Iterator free functions.
* These are the iterator functions and can all be used to iterate over in a
* `for (auto var : lz::someiterator(...))`-like fashion. Also, all objects contain a `toVector`,
* `toVector<Allocator>`, `toArray<N>`, `to<container>. toMap, toUnorderedMap` (specifying its value type of the container is not
* necessary, so e.g. `to<std::list>()` will do), `begin()`, `end()` methods and `value_type` and `iterator`
* typedefs.
* @{
*/
/**
* @brief This function takes a range between two iterators from [begin, end). Its `begin()` function returns a
* an iterator. If MSVC and the type is an STL iterator, pass a pointer iterator, not an actual
* iterator object.
* @param begin The beginning of the 'view'.
* @param end The ending of the 'view'.
* @return A Take object that can be converted to an arbitrary container or can be iterated over using
* `for (auto... lz::takeRange(...))`.
*/
template<LZ_CONCEPT_ITERATOR Iterator>
LZ_NODISCARD LZ_CONSTEXPR_CXX_20 internal::BasicIteratorView<Iterator>
takeRange(Iterator begin, Iterator end, const internal::DiffType<Iterator> amount) {
using lz::next;
using std::next;
static_cast<void>(end);
return { begin, next(begin, amount) };
}
/**
* @brief This function takes an iterable and slices `amount` from the beginning of the array. Essentially it is
* equivalent to [`iterable.begin(), iterable.begin() + amount`). Its `begin()` function returns a random
* access iterator.
* @param iterable An iterable with method `begin()`.
* @param amount The amount of elements to take from the beginning of the `iterable`.
* @return A Take object that can be converted to an arbitrary container or can be iterated over using
* `for (auto... lz::take(...))`.
*/
template<LZ_CONCEPT_ITERABLE Iterable, class IterType = internal::IterTypeFromIterable<Iterable>>
LZ_NODISCARD LZ_CONSTEXPR_CXX_20 internal::BasicIteratorView<IterType>
take(Iterable&& iterable, const internal::DiffType<IterType> amount) {
return takeRange(internal::begin(std::forward<Iterable>(iterable)), internal::end(std::forward<Iterable>(iterable)), amount);
}
/**
* Drops an amount of items, starting from begin.
* @param begin The beginning of the sequence.
* @param end The ending of the sequence.
* @param amount The amount of items to drop, which is equivalent to next(begin, amount)
* @return A Take iterator where the first `amount` items have been dropped.
*/
template<LZ_CONCEPT_ITERATOR Iterator>
LZ_NODISCARD LZ_CONSTEXPR_CXX_20 internal::BasicIteratorView<Iterator>
dropRange(Iterator begin, Iterator end, const internal::DiffType<Iterator> amount) {
using lz::next;
using std::next;
return takeRange(next(begin, amount), end, internal::getIterLength(begin, end) - amount);
}
/**
* Drops an amount of items, starting from begin.
* @param iterable The iterable to drop from.
* @param amount The amount of items to drop, which is equivalent to next(begin, amount)
* @return A Take iterator where the first `amount` items have been dropped.
*/
template<LZ_CONCEPT_ITERABLE Iterable, class IterType = internal::IterTypeFromIterable<Iterable>>
LZ_NODISCARD LZ_CONSTEXPR_CXX_20 internal::BasicIteratorView<IterType>
drop(Iterable&& iterable, const internal::DiffType<IterType> amount) {
using lz::next;
using std::next;
auto begin = std::begin(iterable);
auto end = std::end(iterable);
return takeRange(next(begin, amount), end, static_cast<internal::DiffTypeIterable<Iterable>>(iterable.size()) - amount);
}
/**
* @brief This function slices an iterable. It is equivalent to [`begin() + from, begin() + to`).
* Its `begin()` function returns an iterator.
* @param iterable An iterable with method `begin()`.
* @param from The offset from the beginning of the iterable.
* @param to The offset from the beginning to take. `from` must be higher than `to`.
* @return A Take object that can be converted to an arbitrary container or can be iterated over using
* `for (auto... lz::slice(...))`.
*/
template<LZ_CONCEPT_ITERABLE Iterable, class IterType = internal::IterTypeFromIterable<Iterable>>
LZ_NODISCARD LZ_CONSTEXPR_CXX_20 internal::BasicIteratorView<IterType>
slice(Iterable&& iterable, const internal::DiffType<IterType> from, const internal::DiffType<IterType> to) {
using lz::next;
using std::next;
LZ_ASSERT(to >= from, "parameter `to` cannot be more than `from`");
auto begin = internal::begin(std::forward<Iterable>(iterable));
begin = next(std::move(begin), from);
return takeRange(begin, internal::end(std::forward<Iterable>(iterable)), to - from);
}
# ifdef LZ_HAS_EXECUTION
/**
* @brief Takes elements from an iterator from [begin, ...) while the function returns true. If the function
* returns false, the iterator stops. Its `begin()` function returns an iterator.
* If MSVC and the type is an STL iterator, pass a pointer iterator, not an actual iterator object.
* @param begin The beginning of the iterator.
* @param end The beginning of the iterator.
* @param predicate A function that returns a bool and passes a value type in its argument. If the function returns
* false, the iterator stops.
* @param execution The execution policy. Must be one of `std::execution`'s tags. Performs the find using this execution.
* @return A Take object that can be converted to an arbitrary container or can be iterated over using
* `for (auto... lz::takeWhileRange(...))`.
*/
template<LZ_CONCEPT_ITERATOR Iterator, class Function, class Execution = std::execution::sequenced_policy>
LZ_NODISCARD LZ_CONSTEXPR_CXX_20 internal::BasicIteratorView<Iterator>
takeWhileRange(Iterator begin, Iterator end, Function predicate, Execution execution = std::execution::seq) {
if constexpr (internal::checkForwardAndPolicies<Execution, Iterator>()) {
end = std::find_if_not(begin, end, predicate);
}
else {
end = std::find_if_not(execution, begin, end, predicate);
}
return { std::move(begin), std::move(end) };
}
/**
* @brief This function does the same as `lz::takeWhileRange` except that it takes an iterable as parameter.
* Its `begin()` function returns an iterator.
* @param iterable An object that has methods `begin()` and `end()`.
* @param predicate A function that returns a bool and passes a value type in its argument. If the function returns
* false, the iterator stops.
* @param execution The execution policy. Must be one of `std::execution`'s tags. Performs the find using this execution.
* @return A Take object that can be converted to an arbitrary container or can be iterated over using
* `for (auto... lz::takeWhile(...))`.
*/
template<LZ_CONCEPT_ITERABLE Iterable, class Function, class Execution = std::execution::sequenced_policy>
LZ_NODISCARD LZ_CONSTEXPR_CXX_20 internal::BasicIteratorView<internal::IterTypeFromIterable<Iterable>>
takeWhile(Iterable&& iterable, Function predicate, Execution execution = std::execution::seq) {
return takeWhileRange(internal::begin(std::forward<Iterable>(iterable)), internal::end(std::forward<Iterable>(iterable)),
std::move(predicate), execution);
}
/**
* @brief Creates a Take iterator view object.
* @details This iterator view object can be used to skip values while `predicate` returns true. After the `predicate` returns
* false, no more values are being skipped.
* @param begin The beginning of the sequence.
* @param end The ending of the sequence.
* @param predicate Function that must return `bool`, and take a `Iterator::value_type` as function parameter.
* @param execution The execution policy. Must be one of std::execution::*
* @return A Take iterator view object.
*/
template<LZ_CONCEPT_ITERATOR Iterator, class Function, class Execution = std::execution::sequenced_policy>
LZ_NODISCARD LZ_CONSTEXPR_CXX_20 internal::BasicIteratorView<Iterator>
dropWhileRange(Iterator begin, Iterator end, Function predicate, Execution execution = std::execution::seq) {
using ValueType = internal::ValueType<Iterator>;
if constexpr (internal::checkForwardAndPolicies<Execution, Iterator>()) {
static_cast<void>(execution);
begin = std::find_if_not(std::move(begin), end, std::move(predicate));
}
else {
begin = std::find_if_not(execution, std::move(begin), end, std::move(predicate));
}
return takeRange(begin, end, internal::getIterLength(begin, end));
}
/**
* @brief Creates a Take iterator view object.
* @details This iterator view object can be used to skip values while `predicate` returns true. After the `predicate` returns
* false, no more values are being skipped.
* @param iterable The sequence with the values that can be iterated over.
* @param predicate Function that must return `bool`, and take a `Iterator::value_type` as function parameter.
* @param execution The execution policy. Must be one of std::execution::*
* @return A Take iterator view object.
*/
template<LZ_CONCEPT_ITERABLE Iterable, class Function, class Execution = std::execution::sequenced_policy>
LZ_NODISCARD LZ_CONSTEXPR_CXX_20 internal::BasicIteratorView<internal::IterTypeFromIterable<Iterable>>
dropWhile(Iterable&& iterable, Function predicate, Execution execution = std::execution::seq) {
return dropWhileRange(internal::begin(std::forward<Iterable>(iterable)), internal::end(std::forward<Iterable>(iterable)),
std::move(predicate), execution);
}
# else // ^^^ lz has execution vvv lz ! has execution
/**
* @brief Takes elements from an iterator from [begin, ...) while the function returns true. If the function
* returns false, the iterator stops. Its `begin()` function returns an iterator.
* If MSVC and the type is an STL iterator, pass a pointer iterator, not an actual iterator object.
* @param begin The beginning of the iterator.
* @param end The beginning of the iterator.
* @param predicate A function that returns a bool and passes a value type in its argument. If the function returns
* false, the iterator stops.
* @return A Take object that can be converted to an arbitrary container or can be iterated over using
* `for (auto... lz::takeWhileRange(...))`.
*/
template<LZ_CONCEPT_ITERATOR Iterator, class Function>
LZ_NODISCARD LZ_CONSTEXPR_CXX_20 internal::BasicIteratorView<Iterator>
takeWhileRange(Iterator begin, Iterator end, Function predicate) {
end = std::find_if_not(begin, end, predicate);
return { std::move(begin), std::move(end) };
}
/**
* @brief This function does the same as `lz::takeWhileRange` except that it takes an iterable as parameter.
* Its `begin()` function returns an iterator.
* @param iterable An object that has methods `begin()` and `end()`.
* @param predicate A function that returns a bool and passes a value type in its argument. If the function returns
* false, the iterator stops.
* @return A Take object that can be converted to an arbitrary container or can be iterated over using
* `for (auto... lz::takeWhile(...))`.
*/
template<LZ_CONCEPT_ITERABLE Iterable, class Function>
LZ_NODISCARD LZ_CONSTEXPR_CXX_20 internal::BasicIteratorView<internal::IterTypeFromIterable<Iterable>>
takeWhile(Iterable&& iterable, Function predicate) {
return takeWhileRange(internal::begin(std::forward<Iterable>(iterable)), internal::end(std::forward<Iterable>(iterable)),
std::move(predicate));
}
/**
* @brief Creates a Take iterator view object.
* @details This iterator view object can be used to skip values while `predicate` returns true. After the `predicate` returns
* false, no more values are being skipped.
* @param begin The beginning of the sequence.
* @param end The ending of the sequence.
* @param predicate Function that must return `bool`, and take a `Iterator::value_type` as function parameter.
* @return A Take iterator view object.
*/
template<LZ_CONCEPT_ITERATOR Iterator, class Function>
internal::BasicIteratorView<Iterator> dropWhileRange(Iterator begin, Iterator end, Function predicate) {
begin = std::find_if_not(std::move(begin), end, std::move(predicate));
return takeRange(begin, end, internal::getIterLength(begin, end));
}
/**
* @brief Creates a Take iterator view object.
* @details This iterator view object can be used to skip values while `predicate` returns true. After the `predicate` returns
* false, no more values are being skipped.
* @param iterable The sequence with the values that can be iterated over.
* @param predicate Function that must return `bool`, and take a `Iterator::value_type` as function parameter.
* @return A Take iterator view object.
*/
template<LZ_CONCEPT_ITERABLE Iterable, class Function>
internal::BasicIteratorView<internal::IterTypeFromIterable<Iterable>> dropWhile(Iterable&& iterable, Function predicate) {
return dropWhileRange(internal::begin(std::forward<Iterable>(iterable)), internal::end(std::forward<Iterable>(iterable)),
std::move(predicate));
}
# endif // LZ_HAS_EXECUTION
// End of group
/**
* @}
*/
} // namespace lz
#endif | [
"marc.dirven@student.hu.nl"
] | marc.dirven@student.hu.nl |
39aa4e232b05ec7ed2014616127fecf03ad2c05d | 9656ebbef39f30510919460db8369b678db7890b | /gestionbus/ProjetKhaled/projetkhaled.h | 5846ceb1064d75f8ef372d88f8cc8162337c30ff | [] | no_license | KhaledKhm/bus | 77cae0d700b37383bc1345ee5e9230c7642309d3 | e290b1e0fd25c62389cc6b612467f34f5a37bc2a | refs/heads/master | 2022-03-27T20:05:19.535966 | 2020-01-15T20:21:06 | 2020-01-15T20:21:06 | 221,741,893 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,676 | h | #ifndef PROJETKHALED_H
#define PROJETKHALED_H
#include <QMainWindow>
#include <QVBoxLayout>
#include "bus.h"
#include "fournisseur.h"
#include "materiel.h"
#include "stat.h"
#include "statistic.h"
QT_BEGIN_NAMESPACE
namespace Ui { class ProjetKhaled; }
QT_END_NAMESPACE
class ProjetKhaled : public QMainWindow
{
Q_OBJECT
public:
explicit ProjetKhaled(QWidget *parent = nullptr);
~ProjetKhaled();
private slots:
void on_ConfirmerAjoutBus_clicked();
void on_ConfirmerModifBus2_clicked();
void on_pb_supprimer_clicked();
void on_pbAjouterFournisseur_clicked();
void on_pbModifierFournisseur_clicked();
void on_pbSupprimerFournisseur_clicked();
void on_pbMaterielAjout_clicked();
void on_pbMaterielModif2_clicked();
void on_pbMaterielSupprimer_clicked();
void on_pbMaterielAfficher_clicked();
void on_pbFournisseurAfficher_clicked();
void on_pbBusAfficher_clicked();
void on_pbMaterielRechercher_clicked();
void on_pbBusRechercher_clicked();
void on_pbFournisseurRechercher_clicked();
void on_pbMaterielTri1Alpha_3_clicked();
void on_pbStat_clicked();
void on_comboBox_currentTextChanged(const QString &arg1);
void on_cbTriBus_currentTextChanged(const QString &arg1);
void on_cbTriBus_2_currentTextChanged(const QString &arg1);
void on_pbMaterielImprimer_clicked();
private:
Ui::ProjetKhaled *ui;
bus tmpBus;
fournisseur tmpFournisseur;
materiel tmpMateriel;
QVBoxLayout * mainLayout;
statistic s;
};
#endif // PROJETKHALED_H
| [
"noreply@github.com"
] | noreply@github.com |
8f32690410477c7ee423235382c339e4ab5bd7af | a9e308c81c27a80c53c899ce806d6d7b4a9bbbf3 | /SDK/include/WildMagic4/LibFoundation/Curves/Wm4CubicPolynomialCurve2.h | 00c4cf71a12d750c3c246ce1911d7af4866617cb | [
"BSL-1.0"
] | permissive | NikitaNikson/xray-2_0 | 00d8e78112d7b3d5ec1cb790c90f614dc732f633 | 82b049d2d177aac15e1317cbe281e8c167b8f8d1 | refs/heads/master | 2023-06-25T16:51:26.243019 | 2020-09-29T15:49:23 | 2020-09-29T15:49:23 | 390,966,305 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,572 | h | // Geometric Tools, LLC
// Copyright (c) 1998-2010
// Distributed under the Boost Software License, Version 1.0.
// http://www.boost.org/LICENSE_1_0.txt
// http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
//
// File Version: 4.10.0 (2009/11/18)
#ifndef WM4CUBICPOLYNOMIALCURVE2_H
#define WM4CUBICPOLYNOMIALCURVE2_H
#include "Wm4FoundationLIB.h"
#include "Wm4PolynomialCurve2.h"
namespace Wm4
{
template <class Real>
class WM4_FOUNDATION_ITEM CubicPolynomialCurve2
: public PolynomialCurve2<Real>
{
public:
// Construction and destruction. CubicPolynomialCurve2 accepts
// responsibility for deleting the input polynomials.
CubicPolynomialCurve2 (Polynomial1<Real>* pkXPoly,
Polynomial1<Real>* pkYPoly);
virtual ~CubicPolynomialCurve2 ();
// tessellation data
int GetVertexQuantity () const;
Vector2<Real>* Vertices ();
// tessellation by recursive subdivision
void Tessellate (int iLevel);
protected:
using PolynomialCurve2<Real>::m_fTMin;
using PolynomialCurve2<Real>::m_fTMax;
// precomputation
class WM4_FOUNDATION_ITEM IntervalParameters
{
public:
int m_iI0, m_iI1;
Vector2<Real> m_akXuu[2];
};
// subdivide curve into two halves
void Subdivide (int iLevel, Real fDSqr, Vector2<Real>* akX,
IntervalParameters& rkIP);
// tessellation data
int m_iVertexQuantity;
Vector2<Real>* m_akVertex;
};
typedef CubicPolynomialCurve2<float> CubicPolynomialCurve2f;
typedef CubicPolynomialCurve2<double> CubicPolynomialCurve2d;
}
#endif
| [
"loxotron@bk.ru"
] | loxotron@bk.ru |
3827c07fed814c435a85df793a93a235089b736c | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/squid/gumtree/squid_old_log_186.cpp | 83d089e8d6015f764f7012968952d9d65d7ee089 | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 268 | cpp | logfilePrintf(logfile, "%9d.%03d %03d %s %s\n",
(int) current_time.tv_sec,
(int) current_time.tv_usec / 1000,
last_status,
RequestMethodStr(request->method),
request->canonical); | [
"993273596@qq.com"
] | 993273596@qq.com |
4c42998701580a4f956233b72ad481d914187170 | feb8a44472202cd0a75ffc129e83f1728184e714 | /src/qt/paymentrequestplus.h | 3683922664f63a5642f5b00da3cb665bbb607ca2 | [
"MIT"
] | permissive | bitalley/BitAlley-Core | 9ec7fe02a3f5ca9aa31d7b752fce89ec0517ae57 | f92f5366988553cba423b6f534206fef41b5b666 | refs/heads/master | 2020-03-25T08:27:04.591960 | 2018-12-30T20:04:08 | 2018-12-30T20:04:08 | 143,613,026 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,391 | h | // Copyright (c) 2011-2014 The Bitcoin developers
// Copyright (c) 2017 The PIVX developers
// Copyright (c) 2018 The BITALLEY developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_QT_PAYMENTREQUESTPLUS_H
#define BITCOIN_QT_PAYMENTREQUESTPLUS_H
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#include "paymentrequest.pb.h"
#pragma GCC diagnostic pop
#include "base58.h"
#include <QByteArray>
#include <QList>
#include <QString>
//
// Wraps dumb protocol buffer paymentRequest
// with extra methods
//
class PaymentRequestPlus
{
public:
PaymentRequestPlus() {}
bool parse(const QByteArray& data);
bool SerializeToString(std::string* output) const;
bool IsInitialized() const;
QString getPKIType() const;
// Returns true if merchant's identity is authenticated, and
// returns human-readable merchant identity in merchant
bool getMerchant(X509_STORE* certStore, QString& merchant) const;
// Returns list of outputs, amount
QList<std::pair<CScript, CAmount> > getPayTo() const;
const payments::PaymentDetails& getDetails() const { return details; }
private:
payments::PaymentRequest paymentRequest;
payments::PaymentDetails details;
};
#endif // BITCOIN_QT_PAYMENTREQUESTPLUS_H
| [
"alonewolf2ksk@gmail.com"
] | alonewolf2ksk@gmail.com |
fb906d55d326da79a4c8d36befd7ebbdd49dcb0a | 07be3a375665f08cb9133833d26822da468450b2 | /c++/interfaces/pwm-interface.cpp | 3e445df480c9dcb8c935f3167a206ff940e6620f | [] | no_license | karayakar/libsimpleio | 254e4978260ae16c08f18e8298cd2e16608f17b4 | 7a3521317b28096086f86c2f6b30b96fd1bc3639 | refs/heads/master | 2020-07-08T16:19:21.569445 | 2019-08-12T07:33:44 | 2019-08-12T07:33:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,341 | cpp | // Abstract interface for PWM (Pulse Width Modulated) outputs
// Copyright (C)2018, Philip Munts, President, Munts AM Corp.
//
// 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.
//
// 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 HOLDER 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.
#include <pwm-interface.h>
void Interfaces::PWM::Output_Interface::operator =(const double dutycycle)
{
this->write(dutycycle);
}
| [
"svn@06ee2f96-5407-11de-8bab-f3d7589a4122"
] | svn@06ee2f96-5407-11de-8bab-f3d7589a4122 |
2b7c2f261b053f9e598aa0f1453398d8e89297b0 | cd790fb7e8ef78b1989531f5864f67649dcb1557 | /uvambl.cpp | 2b57b42ea8737cf2b533f6b53c6979a5bcf8663a | [] | no_license | FatimaTasnim/uva-solution | 59387c26816c271b17e9604255934b7c8c7faf11 | c7d75f0a5384229b243504dfbef4686052b9dea8 | refs/heads/master | 2020-03-27T22:23:18.611201 | 2018-10-23T05:53:46 | 2018-10-23T05:53:46 | 147,226,519 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,004 | cpp | #include<stdio.h>
#include<string.h>
int main()
{
char str[32],i;
while(gets(str))
{
for(i=0;str[i];i++)
{
if(str[i]=='A' || str[i]=='B' || str[i]=='C')
printf("2");
else if(str[i]=='D' || str[i]=='E' || str[i]=='F')
printf("3");
else if(str[i]=='G' || str[i]=='H' || str[i]=='I')
printf("4");
else if(str[i]=='J' || str[i]=='K' || str[i]=='L')
printf("5");
else if(str[i]=='M' || str[i]=='N' || str[i]=='O')
printf("6");
else if(str[i]=='P' || str[i]=='Q' || str[i]=='R' || str[i]=='S')
printf("7");
else if(str[i]=='T' || str[i]=='U' || str[i]=='V')
printf("8");
else if(str[i]=='W' || str[i]=='X' || str[i]=='Y' || str[i]=='Z')
printf("9");
else
printf("%c",str[i]);
}
printf("\n");
}
return 0;
}
| [
"tasnim.roujat@gmail.com"
] | tasnim.roujat@gmail.com |
562c34d4c9af9f486f9591db2486ea6d12b5184a | 75349e38b5590fa172b6c78a935f7bce3d369665 | /LintCode/76最长上升子序列.cpp | 87004f7ebdf6c1846118fb77c2757985c155de31 | [] | no_license | CmosZhang/Code_Practice | f5a329d5405987426a0094a7a252b11008752b87 | e901d82396a83d4b6e48cbc305551a346eb1073a | refs/heads/master | 2020-09-25T10:47:08.141466 | 2020-01-03T08:05:47 | 2020-01-03T08:05:47 | 225,989,438 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,638 | cpp | #include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
//76. 最长上升子序列
//您的提交打败了 81.20% 的提交!
int longestIncreasingSubsequence(vector<int> &nums)
{
// write your code here
if (nums.empty())
{
return 0;
}
int len = nums.size();
vector<int> dp(len, 1);
int res = 0;
for (int i = 1; i < len; i++)
{
for (int j = 0; j < i; j++)
{
if (nums[j] < nums[i])
{
dp[i] = max(dp[j] + 1, dp[i]);
}
}
res = max(res, dp[i]);
}
return res;
}
//使用二分法来做
int help(vector<int>&arr, int arr_size, int target) {
int start = 0;
int end = arr_size - 1;
int middle;
while (start + 1 < end) {
middle = start + (end - start) / 2;
if (target == arr[middle]) {
end = middle;
continue;
}
if (target < arr[middle]) {
end = middle;
continue;
}
start = middle;
}
if (arr[start] >= target) {
return start;
}
if (arr[end] >= target) {
return end;
}
return -1;
}
int longestIncreasingSubsequence(vector<int> &nums) {
// write your code here
if (nums.size() == 0) {
return 0;
}
if (nums.size() == 1) {
return 1;
}
int len = nums.size();
vector<int> arr(len + 1, INT_MAX);
arr[0] = INT_MIN;
for (int i = 0; i < nums.size(); i++) {
int index = help(arr, nums.size() + 1, nums[i]);
arr[index] = nums[i];
}
for (int i = nums.size(); i > 0; i--) {
if (arr[i] != INT_MAX) {
return i;
}
}
}
int main()
{
vector<int> nums = { 9,3,6,2,7 };
cout << longestIncreasingSubsequence(nums) << endl;
system("pause");
return 0;
} | [
"noreply@github.com"
] | noreply@github.com |
2bf620a4486fb18439088abc1600ac316bd15341 | 8ce87012895db97831518a7099a80cd6ebc96471 | /src/main.cpp | 33023a5d9619497c79975cb4c6467f655499a6ce | [
"MIT"
] | permissive | thealx-eech/SkyDolly | 48fc525d44ecc5647165cfd7f4caee0f0eeb92b7 | d37707b001041c84f7c4ba7242fa72b7d0cc7dd8 | refs/heads/main | 2023-03-29T15:49:21.524436 | 2021-04-06T09:57:06 | 2021-04-06T09:57:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,784 | cpp | /**
* Sky Dolly - The black sheep for your flight recordings
*
* Copyright (c) Oliver Knoll
* All rights reserved.
*
* MIT License
*
* 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 <QSettings>
#include <QStyleFactory>
#include "../../Kernel/src/Version.h"
#include "../../UserInterface/src/MainWindow.h"
#include "SkyDollyApplication.h"
int main(int argc, char *argv[])
{
QCoreApplication::setOrganizationName(Version::getOrganisationName());
QCoreApplication::setApplicationName(Version::getApplicationName());
SkyDollyApplication a(argc, argv);
QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
QCoreApplication::setAttribute(Qt::AA_DontShowIconsInMenus);
MainWindow w;
w.show();
return a.exec();
}
| [
"starsky.hutch@gmx.ch"
] | starsky.hutch@gmx.ch |
93142b0b7f80cbd3addcb4115b681d2d4ce28ea4 | 21042c8a26009a3940ead744ba0f0550e4f6c216 | /QuaternionBasedCameraInOpenGL/QuaternionBasedCameraInOpenGL/SpMatrix4x4.h | ddb2b56d8bcdf84e96d7a222cd88674919bd17af | [] | no_license | VeryNiceGuy/opengl-samples | c565f4c9de7e00c6501dfd2e30452def215b10c2 | de247ebbb29297be834aa7cf5704cbacad35c9ed | refs/heads/master | 2021-01-15T13:19:01.152553 | 2017-08-08T09:23:18 | 2017-08-08T09:23:18 | 99,670,071 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 10,939 | h |
#pragma once
#include <cmath>
class SpVector3;
class SpMatrix4x4
{
public:
SpMatrix4x4();
SpMatrix4x4(const SpMatrix4x4& matrix);
SpMatrix4x4
(float pm11, float pm12, float pm13, float pm14,
float pm21, float pm22, float pm23, float pm24,
float pm31, float pm32, float pm33, float pm34,
float pm41, float pm42, float pm43, float pm44);
~SpMatrix4x4();
void lookAtLh(const SpVector3& position, const SpVector3& target, const SpVector3& up);
void identity();
void zero();
SpMatrix4x4 lerp(const SpMatrix4x4& matrix, float t) const;
void orthoProjectionLhD3d(float width, float height, float zNear, float zFar);
void orthoProjectionRhD3d(float width, float height, float zNear, float zFar);
void perspectiveProjectionFovLhD3d(float fovY, float aspectRatio, float zNear, float zFar);
void perspectiveProjectionFovRhD3d(float fovY, float aspectRatio, float zNear, float zFar);
void orthoProjectionLhOgl(float width, float height, float zNear, float zFar);
void orthoProjectionRhOgl(float width, float height, float zNear, float zFar);
void perspectiveProjectionFovLhOgl(float fovY, float aspectRatio, float zNear, float zFar);
void perspectiveProjectionFovRhOgl(float fovY, float aspectRatio, float zNear, float zFar);
void transpose();
SpMatrix4x4 transposition() const;
void invert();
SpMatrix4x4 inverse() const;
float determinant() const;
SpMatrix4x4& operator = (const SpMatrix4x4& matrix);
SpMatrix4x4 operator * (const SpMatrix4x4& matrix) const;
SpMatrix4x4 operator + (const SpMatrix4x4& matrix) const;
SpMatrix4x4 operator - (const SpMatrix4x4& matrix) const;
SpMatrix4x4& operator *= (const SpMatrix4x4& matrix);
SpMatrix4x4& operator += (const SpMatrix4x4& matrix);
SpMatrix4x4& operator -= (const SpMatrix4x4& matrix);
SpMatrix4x4 operator * (float scalar) const;
SpMatrix4x4 operator / (float scalar) const;
SpMatrix4x4 operator + (float scalar) const;
SpMatrix4x4 operator - (float scalar) const;
SpMatrix4x4& operator *= (float scalar);
SpMatrix4x4& operator /= (float scalar);
SpMatrix4x4& operator += (float scalar);
SpMatrix4x4& operator -= (float scalar);
float m11, m12, m13, m14;
float m21, m22, m23, m24;
float m31, m32, m33, m34;
float m41, m42, m43, m44;
};
inline void SpMatrix4x4::identity()
{
m11 = m22 = m33 = m44 = 1.0f;
m12 = m13 = m14 = m21 =
m23 = m24 = m31 = m32 =
m34 = m41 = m42 = m43 = 0.0f;
}
inline void SpMatrix4x4::zero()
{
m11 = m12 = m13 = m14 =
m21 = m22 = m23 = m24 =
m31 = m32 = m33 = m34 =
m41 = m42 = m43 = m44 = 0.0f;
}
inline SpMatrix4x4 SpMatrix4x4::lerp(const SpMatrix4x4& matrix, float t) const
{
return SpMatrix4x4
((matrix.m11 - m11) * t + m11, (matrix.m12 - m12) * t + m12, (matrix.m13 - m13) * t + m13, (matrix.m14 - m14) * t + m14,
(matrix.m21 - m21) * t + m21, (matrix.m22 - m22) * t + m22, (matrix.m23 - m23) * t + m23, (matrix.m24 - m24) * t + m24,
(matrix.m31 - m31) * t + m31, (matrix.m32 - m32) * t + m32, (matrix.m33 - m33) * t + m33, (matrix.m34 - m34) * t + m34,
(matrix.m41 - m41) * t + m41, (matrix.m42 - m42) * t + m42, (matrix.m43 - m43) * t + m43, (matrix.m44 - m44) * t + m44);
}
inline void SpMatrix4x4::orthoProjectionLhD3d(float width, float height, float zNear, float zFar)
{
m11 = 2.0f / width;
m22 = 2.0f / height;
m33 = 1.0f / (zFar - zNear);
m43 = zNear / (zNear - zFar);
m44 = 1.0;
m12 = m13 = m14 = m21 =
m23 = m24 = m31 = m32 =
m34 = m41 = m42 = 0.0f;
}
inline void SpMatrix4x4::orthoProjectionRhD3d(float width, float height, float zNear, float zFar)
{
m11 = 2.0f / width;
m22 = 2.0f / height;
m33 = 1.0f / (zNear - zFar);
m43 = zNear / (zNear - zFar);
m44 = 1.0;
m12 = m13 = m14 = m21 =
m23 = m24 = m31 = m32 =
m34 = m41 = m42 = 0.0f;
}
inline void SpMatrix4x4::perspectiveProjectionFovLhD3d(float fovY, float aspectRatio, float zNear, float zFar)
{
float cotangent = 1.0f / tanf(fovY / 2.0f);
m11 = cotangent / aspectRatio;
m22 = cotangent;
m33 = zFar / (zFar - zNear);
m34 = 1.0f;
m43 = -zNear * zFar / (zFar - zNear);
m12 = m13 = m14 = m21 =
m23 = m24 = m31 = m32 =
m41 = m42 = m44 = 0.0f;
}
inline void SpMatrix4x4::perspectiveProjectionFovRhD3d(float fovY, float aspectRatio, float zNear, float zFar)
{
float cotangent = 1.0f / tanf(fovY / 2.0f);
m11 = cotangent / aspectRatio;
m22 = cotangent;
m33 = zFar / (zNear - zFar);
m34 = -1.0f;
m43 = zNear * zFar / (zNear - zFar);
m12 = m13 = m14 = m21 =
m23 = m24 = m31 = m32 =
m41 = m42 = m44 = 0.0f;
}
inline void SpMatrix4x4::orthoProjectionLhOgl(float width, float height, float zNear, float zFar)
{
m11 = 2.0f / width;
m22 = 2.0f / height;
m33 = 2.0f / (zFar - zNear);
m43 = (zNear + zFar) / (zNear - zFar);
m44 = 1.0;
m12 = m13 = m14 = m21 =
m23 = m24 = m31 = m32 =
m34 = m41 = m42 = 0.0f;
}
inline void SpMatrix4x4::orthoProjectionRhOgl(float width, float height, float zNear, float zFar)
{
m11 = 2.0f / width;
m22 = 2.0f / height;
m33 = 2.0f / (zNear - zFar);
m43 = (zNear + zFar) / (zNear - zFar);
m44 = 1.0;
m12 = m13 = m14 = m21 =
m23 = m24 = m31 = m32 =
m34 = m41 = m42 = 0.0f;
}
inline void SpMatrix4x4::perspectiveProjectionFovLhOgl(float fovY, float aspectRatio, float zNear, float zFar)
{
float cotangent = 1.0f / tanf(fovY / 2.0f);
m11 = cotangent / aspectRatio;
m22 = cotangent;
m33 = (zNear + zFar) / (zFar - zNear);
m34 = 1.0;
m43 = -2.0f * zNear * zFar / (zFar - zNear);
m12 = m13 = m14 = m21 =
m23 = m24 = m31 = m32 =
m41 = m42 = m44 = 0.0f;
}
inline void SpMatrix4x4::perspectiveProjectionFovRhOgl(float fovY, float aspectRatio, float zNear, float zFar)
{
float cotangent = 1.0f / tanf(fovY / 2.0f);
m11 = cotangent / aspectRatio;
m22 = cotangent;
m33 = (zNear + zFar) / (zNear - zFar);
m34 = -1.0;
m43 = 2.0f * zNear * zFar / (zNear - zFar);
m12 = m13 = m14 = m21 =
m23 = m24 = m31 = m32 =
m41 = m42 = m44 = 0.0f;
}
inline void SpMatrix4x4::transpose()
{
float lv12 = m12;
float lv13 = m13;
float lv14 = m14;
float lv23 = m23;
float lv24 = m24;
float lv34 = m34;
m12 = m21;
m13 = m31;
m14 = m41;
m23 = m32;
m24 = m42;
m34 = m43;
m21 = lv12;
m31 = lv13;
m41 = lv14;
m32 = lv23;
m42 = lv24;
m43 = lv34;
}
inline SpMatrix4x4 SpMatrix4x4::transposition() const
{
return SpMatrix4x4
(m11, m21, m31, m41,
m12, m22, m32, m42,
m13, m23, m33, m43,
m14, m24, m34, m44);
}
inline SpMatrix4x4& SpMatrix4x4::operator = (const SpMatrix4x4& matrix)
{
m11 = matrix.m11; m12 = matrix.m12; m13 = matrix.m13; m14 = matrix.m14;
m21 = matrix.m21; m22 = matrix.m22; m23 = matrix.m23; m24 = matrix.m24;
m31 = matrix.m31; m32 = matrix.m32; m33 = matrix.m33; m34 = matrix.m34;
m41 = matrix.m41; m42 = matrix.m42; m43 = matrix.m43; m44 = matrix.m44;
return *this;
}
inline SpMatrix4x4 SpMatrix4x4::operator + (const SpMatrix4x4& matrix) const
{
return SpMatrix4x4
(m11 + matrix.m11, m12 + matrix.m12, m13 + matrix.m13, m14 + matrix.m14,
m21 + matrix.m21, m22 + matrix.m22, m23 + matrix.m23, m24 + matrix.m24,
m31 + matrix.m31, m32 + matrix.m32, m33 + matrix.m33, m34 + matrix.m34,
m41 + matrix.m41, m42 + matrix.m42, m43 + matrix.m43, m44 + matrix.m44);
}
inline SpMatrix4x4 SpMatrix4x4::operator - (const SpMatrix4x4& matrix) const
{
return SpMatrix4x4
(m11 - matrix.m11, m12 - matrix.m12, m13 - matrix.m13, m14 - matrix.m14,
m21 - matrix.m21, m22 - matrix.m22, m23 - matrix.m23, m24 - matrix.m24,
m31 - matrix.m31, m32 - matrix.m32, m33 - matrix.m33, m34 - matrix.m34,
m41 - matrix.m41, m42 - matrix.m42, m43 - matrix.m43, m44 - matrix.m44);
}
inline SpMatrix4x4& SpMatrix4x4::operator += (const SpMatrix4x4& matrix)
{
m11 += matrix.m11; m12 += matrix.m12; m13 += matrix.m13; m14 += matrix.m14;
m21 += matrix.m21; m22 += matrix.m22; m23 += matrix.m23; m24 += matrix.m24;
m31 += matrix.m31; m32 += matrix.m32; m33 += matrix.m33; m34 += matrix.m34;
m41 += matrix.m41; m42 += matrix.m42; m43 += matrix.m43; m44 += matrix.m44;
return *this;
}
inline SpMatrix4x4& SpMatrix4x4::operator -= (const SpMatrix4x4& matrix)
{
m11 -= matrix.m11; m12 -= matrix.m12; m13 -= matrix.m13; m14 -= matrix.m14;
m21 -= matrix.m21; m22 -= matrix.m22; m23 -= matrix.m23; m24 -= matrix.m24;
m31 -= matrix.m31; m32 -= matrix.m32; m33 -= matrix.m33; m34 -= matrix.m34;
m41 -= matrix.m41; m42 -= matrix.m42; m43 -= matrix.m43; m44 -= matrix.m44;
return *this;
}
inline SpMatrix4x4 SpMatrix4x4::operator * (float scalar) const
{
return SpMatrix4x4
(m11 * scalar, m12 * scalar, m13 * scalar, m14 * scalar,
m21 * scalar, m22 * scalar, m23 * scalar, m24 * scalar,
m31 * scalar, m32 * scalar, m33 * scalar, m34 * scalar,
m41 * scalar, m42 * scalar, m43 * scalar, m44 * scalar);
}
inline SpMatrix4x4 SpMatrix4x4::operator / (float scalar) const
{
return SpMatrix4x4
(m11 / scalar, m12 / scalar, m13 / scalar, m14 / scalar,
m21 / scalar, m22 / scalar, m23 / scalar, m24 / scalar,
m31 / scalar, m32 / scalar, m33 / scalar, m34 / scalar,
m41 / scalar, m42 / scalar, m43 / scalar, m44 / scalar);
}
inline SpMatrix4x4 SpMatrix4x4::operator + (float scalar) const
{
return SpMatrix4x4
(m11 + scalar, m12 + scalar, m13 + scalar, m14 + scalar,
m21 + scalar, m22 + scalar, m23 + scalar, m24 + scalar,
m31 + scalar, m32 + scalar, m33 + scalar, m34 + scalar,
m41 + scalar, m42 + scalar, m43 + scalar, m44 + scalar);
}
inline SpMatrix4x4 SpMatrix4x4::operator - (float scalar) const
{
return SpMatrix4x4
(m11 - scalar, m12 - scalar, m13 - scalar, m14 - scalar,
m21 - scalar, m22 - scalar, m23 - scalar, m24 - scalar,
m31 - scalar, m32 - scalar, m33 - scalar, m34 - scalar,
m41 - scalar, m42 - scalar, m43 - scalar, m44 - scalar);
}
inline SpMatrix4x4& SpMatrix4x4::operator *= (float scalar)
{
m11 *= scalar; m12 *= scalar; m13 *= scalar; m14 *= scalar;
m21 *= scalar; m22 *= scalar; m23 *= scalar; m24 *= scalar;
m31 *= scalar; m32 *= scalar; m33 *= scalar; m34 *= scalar;
m41 *= scalar; m42 *= scalar; m43 *= scalar; m44 *= scalar;
return *this;
}
inline SpMatrix4x4& SpMatrix4x4::operator /= (float scalar)
{
m11 /= scalar; m12 /= scalar; m13 /= scalar; m14 /= scalar;
m21 /= scalar; m22 /= scalar; m23 /= scalar; m24 /= scalar;
m31 /= scalar; m32 /= scalar; m33 /= scalar; m34 /= scalar;
m41 /= scalar; m42 /= scalar; m43 /= scalar; m44 /= scalar;
return *this;
}
inline SpMatrix4x4& SpMatrix4x4::operator += (float scalar)
{
m11 += scalar; m12 += scalar; m13 += scalar; m14 += scalar;
m21 += scalar; m22 += scalar; m23 += scalar; m24 += scalar;
m31 += scalar; m32 += scalar; m33 += scalar; m34 += scalar;
m41 += scalar; m42 += scalar; m43 += scalar; m44 += scalar;
return *this;
}
inline SpMatrix4x4& SpMatrix4x4::operator -= (float scalar)
{
m11 -= scalar; m12 -= scalar; m13 -= scalar; m14 -= scalar;
m21 -= scalar; m22 -= scalar; m23 -= scalar; m24 -= scalar;
m31 -= scalar; m32 -= scalar; m33 -= scalar; m34 -= scalar;
m41 -= scalar; m42 -= scalar; m43 -= scalar; m44 -= scalar;
return *this;
}
| [
"killingmesoftlywithchainsaw@gmail.com"
] | killingmesoftlywithchainsaw@gmail.com |
13a7ecee5a9862a077981191393a721a9661982e | 13c1c87fc6e8e71934436ef1094965b53064d0b2 | /third-party/highwayhash/highwayhash/robust_statistics.h | 399a3318f234039c34ce8ab413040ec5c06bfe83 | [
"Apache-2.0"
] | permissive | jaehongyun/redisgraph-cpp | 744a999548d3d942872650f0bb6e7f0cce683b29 | 01e618a2f3a408661f83c4fb000b91f724299896 | refs/heads/master | 2020-12-28T14:33:16.536543 | 2019-12-17T14:59:47 | 2019-12-17T14:59:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,485 | h | // Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef HIGHWAYHASH_ROBUST_STATISTICS_H_
#define HIGHWAYHASH_ROBUST_STATISTICS_H_
// Robust statistics: Mode, Median, MedianAbsoluteDeviation.
#include <stddef.h>
#include <algorithm>
#include <cassert>
#include <cmath>
#include <limits>
#include <vector>
#include "highwayhash/arch_specific.h"
#include "highwayhash/compiler_specific.h"
namespace highwayhash {
// @return i in [idx_begin, idx_begin + half_count) that minimizes
// sorted[i + half_count] - sorted[i].
template <typename T>
size_t MinRange(const T* const HH_RESTRICT sorted, const size_t idx_begin,
const size_t half_count) {
T min_range = std::numeric_limits<T>::max();
size_t min_idx = 0;
for (size_t idx = idx_begin; idx < idx_begin + half_count; ++idx) {
assert(sorted[idx] <= sorted[idx + half_count]);
const T range = sorted[idx + half_count] - sorted[idx];
if (range < min_range) {
min_range = range;
min_idx = idx;
}
}
return min_idx;
}
// Returns an estimate of the mode by calling MinRange on successively
// halved intervals. "sorted" must be in ascending order. This is the
// Half Sample Mode estimator proposed by Bickel in "On a fast, robust
// estimator of the mode", with complexity O(N log N). The mode is less
// affected by outliers in highly-skewed distributions than the median.
// The averaging operation below assumes "T" is an unsigned integer type.
template <typename T>
T Mode(const T* const HH_RESTRICT sorted, const size_t num_values) {
size_t idx_begin = 0;
size_t half_count = num_values / 2;
while (half_count > 1) {
idx_begin = MinRange(sorted, idx_begin, half_count);
half_count >>= 1;
}
const T x = sorted[idx_begin + 0];
if (half_count == 0) {
return x;
}
assert(half_count == 1);
const T average = (x + sorted[idx_begin + 1] + 1) / 2;
return average;
}
// Sorts integral values in ascending order. About 3x faster than std::sort for
// input distributions with very few unique values.
template <class T>
void CountingSort(T* begin, T* end) {
// Unique values and their frequency (similar to flat_map).
using Unique = std::pair<T, int>;
std::vector<Unique> unique;
for (const T* p = begin; p != end; ++p) {
const T value = *p;
const auto pos =
std::find_if(unique.begin(), unique.end(),
[value](const Unique& u) { return u.first == value; });
if (pos == unique.end()) {
unique.push_back(std::make_pair(*p, 1));
} else {
++pos->second;
}
}
// Sort in ascending order of value (pair.first).
std::sort(unique.begin(), unique.end());
// Write that many copies of each unique value to the array.
T* HH_RESTRICT p = begin;
for (const auto& value_count : unique) {
std::fill(p, p + value_count.second, value_count.first);
p += value_count.second;
}
assert(p == end);
}
// Returns the median value. Side effect: sorts "samples".
template <typename T>
T Median(std::vector<T>* samples) {
assert(!samples->empty());
std::sort(samples->begin(), samples->end());
const size_t half = samples->size() / 2;
// Odd count: return middle
if (samples->size() % 2) {
return (*samples)[half];
}
// Even count: return average of middle two.
return ((*samples)[half] + (*samples)[half - 1]) / 2;
}
// Returns a robust measure of variability.
template <typename T>
T MedianAbsoluteDeviation(const std::vector<T>& samples, const T median) {
assert(!samples.empty());
std::vector<T> abs_deviations;
abs_deviations.reserve(samples.size());
for (const T sample : samples) {
abs_deviations.push_back(std::abs(sample - median));
}
return Median(&abs_deviations);
}
} // namespace highwayhash
#endif // HIGHWAYHASH_ROBUST_STATISTICS_H_
| [
"giorgio@apache.org"
] | giorgio@apache.org |
d2653f919899a88c4aa81296fe1157f58c90cdb4 | 96f7b825c92bca0a7aa59cd564056d8afbd6b9ba | /build/moc_GSSLineString.cpp | aa55de0ea0ecdec4f52f8c687a69de6d83ec6bfa | [] | no_license | AnderPijoan/GTPlat | 4d0a9452fcf56b0d018d987cecdbd22ffe355210 | 4981a430bf18eab26177e9cb2f1dfbeb1aff109e | refs/heads/master | 2020-12-30T14:45:32.494225 | 2017-05-12T11:56:24 | 2017-05-12T11:56:24 | 91,085,149 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,695 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'GSSLineString.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.5.1)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "utils/geometry/GSSLineString.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'GSSLineString.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.5.1. 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_GSSLineString_t {
QByteArrayData data[1];
char stringdata0[14];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_GSSLineString_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_GSSLineString_t qt_meta_stringdata_GSSLineString = {
{
QT_MOC_LITERAL(0, 0, 13) // "GSSLineString"
},
"GSSLineString"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_GSSLineString[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
0, 0, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
0 // eod
};
void GSSLineString::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
Q_UNUSED(_o);
Q_UNUSED(_id);
Q_UNUSED(_c);
Q_UNUSED(_a);
}
const QMetaObject GSSLineString::staticMetaObject = {
{ &GSSGeometry::staticMetaObject, qt_meta_stringdata_GSSLineString.data,
qt_meta_data_GSSLineString, qt_static_metacall, Q_NULLPTR, Q_NULLPTR}
};
const QMetaObject *GSSLineString::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *GSSLineString::qt_metacast(const char *_clname)
{
if (!_clname) return Q_NULLPTR;
if (!strcmp(_clname, qt_meta_stringdata_GSSLineString.stringdata0))
return static_cast<void*>(const_cast< GSSLineString*>(this));
return GSSGeometry::qt_metacast(_clname);
}
int GSSLineString::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = GSSGeometry::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
return _id;
}
QT_END_MOC_NAMESPACE
| [
"system@laboratorius.com"
] | system@laboratorius.com |
fe3852a25afc6f01d265bc77e1e672c15432aa68 | f62223da2505395adf6954d21a3443411229c23f | /GUI_Qt/gui_qt.h | 88e8319fb464f0fa2979ff29692c91a4226379b6 | [] | no_license | jell0wed/8tracksplayer | 08f0e7da42a84ff31b80634522bc169d94e07587 | 139b46b2d413c3832286c8ef0411b1771402b19f | refs/heads/master | 2021-01-01T18:17:47.282635 | 2015-01-23T05:47:15 | 2015-01-23T05:47:15 | 29,718,357 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 243 | h | #ifndef GUI_QT_H
#define GUI_QT_H
#include <QtWidgets/QMainWindow>
#include "ui_gui_qt.h"
class GUI_Qt : public QMainWindow
{
Q_OBJECT
public:
GUI_Qt(QWidget *parent = 0);
~GUI_Qt();
private:
Ui::GUI_QtClass ui;
};
#endif // GUI_QT_H
| [
"jeremie@weboxigen.com"
] | jeremie@weboxigen.com |
52ec5fd9d1c0eba468c1bb53b7dbd2f93b37b87a | e8e8c09ed9453b4bf904d2b26fc89883a9bcbd32 | /Staxx/src/game_tile.cpp | 8d3e423593fffe5bb95154255f02a3b7a5fee17a | [
"Apache-2.0"
] | permissive | k-kapp/Staxx-New | da2b2a98e4911114e9790e550243c573dd7e29e7 | 0f901eb195ec2c23132c7d9e3462bdd14d722ccf | refs/heads/master | 2021-01-20T18:07:17.792048 | 2020-06-29T15:54:45 | 2020-06-29T15:54:45 | 90,906,784 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,426 | cpp |
#include "../include/game_tile.h"
#include "../include/game.h"
#include "../include/block.h"
game_tile::game_tile(game * game_parent, int grid_x, int grid_y, int row_num, int col_num, unsigned size, SDL_Texture * off_texture,
SDL_Texture * on_texture, SDL_Renderer * renderer)
: basic_tile(col_num * size + grid_x, row_num * size + grid_y, size, size, off_texture, on_texture, renderer)
{
}
game_tile::game_tile(const game_tile &other)
: basic_tile(other.x_coord, other.y_coord, other.width, other.height, other.off_texture, other.on_texture, other.renderer), game_parent(game_parent)
{
}
game_tile::game_tile(int x_coord, int y_coord, unsigned x_size, unsigned y_size, SDL_Texture * off_texture, SDL_Texture * on_texture, SDL_Renderer * renderer)
: basic_tile(x_coord, y_coord, x_size, y_size, off_texture, on_texture, renderer)
{
}
game_tile & game_tile::operator = (const game_tile &other)
{
basic_tile::operator=(other);
active_block = other.active_block;
game_parent = other.game_parent;
return *this;
}
void game_tile::set_row_col(int row, int col)
{
if (row < 0)
{
row = 0;
}
if (col < 0)
{
col = 0;
}
row_num = row;
col_num = col;
}
void game_tile::set_parent(game * parent)
{
game_parent = parent;
}
bool game_tile::has_clash()
{
if (active_block && in_block())
{
if (is_active())
{
if (occupied)
return true;
}
}
return false;
}
bool game_tile::is_active()
{
int arr_row = row_num - active_block->get_row();
int arr_col = col_num - active_block->get_col();
return (*active_block)(arr_row, arr_col);
}
bool game_tile::in_block()
{
if (active_block->get_row() > row_num)
{
return false;
}
if (active_block->get_row() + active_block->get_height() <= row_num)
{
return false;
}
if (active_block->get_col() > col_num)
{
return false;
}
if (active_block->get_col() + active_block->get_width() <= col_num)
{
return false;
}
return true;
}
void game_tile::set_active_block(shared_ptr<block> active_block)
{
this->active_block = active_block;
}
void game_tile::update()
{
basic_tile::update();
if (is_occupied())
{
return;
}
if (in_block())
{
if (is_active())
{
set_activation_level(true);
set_on_texture(active_block->get_texture());
return;
}
}
set_activation_level(false);
}
void game_tile::set_occupied()
{
occupied = true;
set_activation_level(true);
}
bool game_tile::is_occupied()
{
return occupied;
}
| [
"k_kapp@yahoo.com"
] | k_kapp@yahoo.com |
5d5db4cc37676e68af35b7d99778429783aa9fe7 | d88eb7f7a090c28aab98bf677de1520413d14b00 | /Tutorial3/Inheritance/2 - AccountInheritance/CheckingAccount.h | 842def6f4dabb4821793714bc002103c769fc373 | [] | no_license | Harry41348/cplusplus | d0c17adeae1ddaf8d6808d5ba6764bba300f8496 | 877d9f066ad9e53e90d5c18acd4e3cc2c1770748 | refs/heads/master | 2023-03-31T04:20:43.752878 | 2021-04-02T20:52:00 | 2021-04-02T20:52:00 | 330,388,390 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 456 | h | // CheckingAccount.h
// Definition of CheckingAccount class.
#ifndef CHECKING_H
#define CHECKING_H
#include "Account.h"
class CheckingAccount : public Account
{
public:
CheckingAccount( double, double );
void credit( double ); // redefined credit function
bool debit( double ); // redefined debit function
private:
double transactionFee; // fee charged per transaction
// utility function to charge fee
void chargeFee();
};
#endif
| [
"hvalentinow@gmail.com"
] | hvalentinow@gmail.com |
ff98c8df75bb6eee7e6c0b6d077ce052954b8bac | 7e7246dc3b7c15c8dd3ab802382b42dd76055fca | /InfinityJump/GameStateMachine.h | bd78d4cb433301b49483252a8316413c7ba88a0a | [] | no_license | s34vv1nd/InfinityJump | 25ea925838d0fcb277cbc4ecaad3eee242874b74 | 8b19654f30c080b7bce25a601234f6d5665ac927 | refs/heads/master | 2022-12-11T04:29:52.421840 | 2020-09-15T14:19:08 | 2020-09-15T14:19:08 | 285,984,216 | 0 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 548 | h | #pragma once
#include <memory>
#include "GameStateBase.h"
#include "StatesType.h"
#include <list>
class GameStateBase;
class GameStateMachine
{
std::vector < std::shared_ptr<GameStateBase>> m_StateStack;
std::shared_ptr<GameStateBase> m_currentState;
bool m_running;
bool m_fullscreen;
public:
GameStateMachine();
~GameStateMachine();
void PushState(StateType stt);
void PopState();
std::shared_ptr<GameStateBase>& CurrentState();
std::shared_ptr<GameStateBase> PreviousState() const;
bool CountStates() const;
void Cleanup();
};
| [
"aquariuslee99@gmail.com"
] | aquariuslee99@gmail.com |
8e52e6a6630982fcbcc0b663351115b44056528b | 614a9024b762b2972f8da1ef968a6ea34a276098 | /obj.cpp | ac586eb2e8566c3c1b69b62518c4e69fff58da4e | [] | no_license | jimfinnis/Ochre | ea452ab26e58b05a4d94423d39025c519aac944c | 191e9b3cae7393e431f45457315fe8769b5b2f78 | refs/heads/master | 2023-07-06T14:34:36.517969 | 2023-07-01T16:45:17 | 2023-07-01T16:45:17 | 90,083,638 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,813 | cpp | /**
* @file obj.cpp
* @brief Brief description of file.
*
*/
#include <malloc.h>
#include <unistd.h>
#include <limits.h>
#include "obj.h"
#include "state.h"
#include "effect.h"
#include "vertexdata.h"
#include "except.h"
#define TINYOBJLOADER_IMPLEMENTATION
#include "tiny_obj_loader.h"
const float UNLITVERTEX::VERTEXEPSILON=0.001f;
const float UNLITVERTEX::NORMALEPSILON=0.00f;
const float UNLITVERTEX::UVEPSILON=0.01f;
static const int VERTEXBUFFER=0;
static const int INDEXBUFFER=1;
static std::vector<ObjMesh *> allMeshes;
static int addvert(std::vector<UNLITVERTEX>& verts,UNLITVERTEX &v){
// for(size_t i=0;i<verts.size();i++){
// if(verts[i].compare(&v))
// return i;
// }
verts.push_back(v);
return verts.size()-1;
}
ObjMesh::ObjMesh(const char *dir,const char *name){
tinyobj::attrib_t attrib;
std::vector<tinyobj::shape_t> shapes;
std::vector<tinyobj::material_t> materials;
printf("Loading OBJ %s/%s\n",dir,name);
char wd[PATH_MAX];
getcwd(wd,PATH_MAX);
if(chdir(dir))
throw Exception().set("cannot change to directory '%s'",dir);
std::string err;
bool ret = tinyobj::LoadObj(&attrib,&shapes,&materials,
&err,name);
if(!ret)
throw Exception().set("loader failure, %s",err.c_str());
// first, run through the materials cutting them down into
// our sort of material
mats = new Material[materials.size()];
for(size_t i=0;i<materials.size();i++){
tinyobj::material_t& tm = materials[i];
Material *m = mats+i;
std::string texname;
// work out what the texture name is.
if(!tm.diffuse_texname.empty())
texname = tm.diffuse_texname;
else {
if(!tm.ambient_texname.empty())
texname = tm.ambient_texname;
else if(!tm.emissive_texname.empty())
texname = tm.emissive_texname;
}
printf("Mat %ld : tex %s\n",i,texname.c_str());
// load the texture if any
if(!texname.empty()){
/* m->texture = TextureManager::getInstance()->createOrFind(texname.c_str());
if(!m->t){
printf("cannot load %s\n",texname.c_str());
}
*/
m->texture = 0;
}else
m->texture = 0;
// now set the diffuse (the only attrib we support)
m->diffuse[0] = tm.diffuse[0];
m->diffuse[1] = tm.diffuse[1];
m->diffuse[2] = tm.diffuse[2];
m->diffuse[3] = 1;
printf(" Diffuse: %f %f %f\n",m->diffuse[0],m->diffuse[1],m->diffuse[2]);
}
// combined vertices (pos+norm+uv)
std::vector<UNLITVERTEX> verts;
// indices into the above
std::vector<int> indx;
// and materials (which will have indices / 3, since triangles.
std::vector<int> matidx;
/* // find centroid (which we're not using at the mo)
float cx=0,cy=0,cz=0;
int ct=0;
for(size_t s=0;s<shapes.size();s++){
// for each face..
int indexoffset=0;
printf("Processing shape of %d polys\n",(int)
shapes[s].mesh.num_face_vertices.size());
for (size_t f = 0; f < shapes[s].mesh.num_face_vertices.size(); f++) {
if(shapes[s].mesh.num_face_vertices[f]!=3)
throw Exception("ooh, non-triangular face!");
for(int i=0;i<3;i++){
// build a vertex and add it, or get the index of the old
// one if it was used before. This combines all the elements
// into one.
tinyobj::index_t idx = shapes[s].mesh.indices[indexoffset+i];
cx += attrib.vertices[3*idx.vertex_index+0];
cy += attrib.vertices[3*idx.vertex_index+1];
cz += attrib.vertices[3*idx.vertex_index+2];
ct++;
}
indexoffset+=3;
}
}
cx/=(float)ct;
cy/=(float)ct;
cz/=(float)ct;
*/
// next step - build out of this mess a unified set of vertices
// and indices into them (as triples), and a material index list.
// for(size_t s=0;s<10;s++){
for(size_t s=0;s<shapes.size();s++){
// for each face..
int indexoffset=0;
printf("Processing shape of %d polys\n",(int)
shapes[s].mesh.num_face_vertices.size());
for (size_t f = 0; f < shapes[s].mesh.num_face_vertices.size(); f++) {
UNLITVERTEX v;
for(int i=0;i<3;i++){
// build a vertex and add it, or get the index of the old
// one if it was used before. This combines all the elements
// into one.
tinyobj::index_t idx = shapes[s].mesh.indices[indexoffset+i];
/*
v.x = attrib.vertices[3*idx.vertex_index+0]-cx;
v.y = attrib.vertices[3*idx.vertex_index+1]-cy;
v.z = attrib.vertices[3*idx.vertex_index+2]-cz;
*/
v.x = attrib.vertices[3*idx.vertex_index+0];
v.y = attrib.vertices[3*idx.vertex_index+1];
v.z = attrib.vertices[3*idx.vertex_index+2];
if(idx.normal_index<0){
throw Exception("Shape has no normals, re-export with normals.");
}
v.nx = attrib.normals[3*idx.normal_index+0];
v.ny = attrib.normals[3*idx.normal_index+1];
v.nz = attrib.normals[3*idx.normal_index+2];
if(idx.texcoord_index>=0){
v.u = attrib.texcoords[2*idx.texcoord_index+0];
v.v = attrib.texcoords[2*idx.texcoord_index+1];
} else {
v.u = v.v = 0;
}
int vertidx = addvert(verts,v);
// now add the index of the combined vertex
indx.push_back(vertidx);
// printf("%f,%f,%f %f,%f,%f %f,%f\n",
// v.x,v.y,v.z,v.nx,v.ny,v.nz);
}
indexoffset+=3;
matidx.push_back(shapes[s].mesh.material_ids[f]);
}
}
// blimey, that took ages. Now we need to create a material
// transition list.
int curmat=-1000;
int transct=0;
for(size_t i=0;i<matidx.size();i++)
{
if(matidx[i]!=curmat)
{
Transition t;
curmat=matidx[i];
t.matidx=curmat;
t.start=i*3;
if(transct)
transitions[transct-1].count=i*3-
transitions[transct-1].start;
transct++;
transitions.push_back(t);
}
}
transitions[transct-1].count=matidx.size()*3-
transitions[transct-1].start;
// we now have a list of material transitions we can use
// in the above list. What remains is to make things more
// permanent: create vbo and ib from the verts and idxs.
// create index and vertex buffers
glGenBuffers(2,buffers);
ERRCHK;
// bind the array and element array buffer to our buffers
glBindBuffer(GL_ARRAY_BUFFER,buffers[VERTEXBUFFER]);
ERRCHK;
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,buffers[INDEXBUFFER]);
ERRCHK;
// create the vertex and index buffer and fill them with data
glBufferData(GL_ELEMENT_ARRAY_BUFFER,
sizeof(GLuint)*indx.size(),
&indx[0],
GL_STATIC_DRAW);
ERRCHK;
glBufferData(GL_ARRAY_BUFFER,
sizeof(UNLITVERTEX)*verts.size(),
&verts[0],
GL_STATIC_DRAW);
ERRCHK;
chdir(wd);
printf("Loaded OK\n");
allMeshes.push_back(this);
}
void ObjMesh::renderAll(){
for(auto it = allMeshes.begin();it!=allMeshes.end();++it){
(*it)->renderQueue();
}
}
ObjMesh::~ObjMesh(){
glDeleteBuffers(2,buffers);
delete [] mats;
}
static Material defaultMat;
static Effect *eff;
void ObjMesh::startBatch(){
State *s = StateManager::getInstance()->get();
// use the state's effect if there is one.
if(s->effect)
eff = s->effect;
else
// otherwise use the standard.
eff = EffectManager::getInstance()->untex;
eff->begin();
// upload the matrices
eff->setUniforms();
// bind the arrays
glBindBuffer(GL_ARRAY_BUFFER,buffers[VERTEXBUFFER]);
ERRCHK;
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,buffers[INDEXBUFFER]);
ERRCHK;
// tell them about offsets
eff->setArrayOffsetsUnlit();
}
void ObjMesh::renderInBatch(glm::mat4 *world){
eff->setWorldMatrix(world);
// and iterate over the transitions
for(std::vector<Transition>::iterator
it=transitions.begin();it!=transitions.end();it++){
Material *m = it->matidx < 0 ? &defaultMat : mats+it->matidx;
eff->setMaterial(m->diffuse,0); // replace with texture if required
glDrawElements(GL_TRIANGLES,it->count,GL_UNSIGNED_INT,
(void *)(it->start*sizeof(GLuint)));
ERRCHK;
}
}
void ObjMesh::renderQueue(){
startBatch();
StateManager *sm = StateManager::getInstance();
State *s = sm->get();
sm->push();
for(auto it = queue.begin();it!=queue.end();++it){
QueueEntry *e = &*it;
*s = e->state;
glm::mat4 *w = &e->world;
renderInBatch(w);
}
sm->pop();
endBatch();
queue.clear();
}
void ObjMesh::endBatch(){
eff->end();
glBindBuffer(GL_ARRAY_BUFFER,0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,0);
}
void ObjMesh::render(glm::mat4 *world){
startBatch();
renderInBatch(world);
endBatch();
}
| [
"jim.finnis@gmail.com"
] | jim.finnis@gmail.com |
2753515a1f229557a518912f2c795244b3aa98a2 | 226b4cfe306c2dd33b177e7febc4cb512c97669f | /src/tests/gl_tests/DXTSRGBCompressedTextureTest.cpp | bb3fe1609ec018ba183c895d523b15c3cc46bfd5 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | hitmoon/angle | 55df09b86058222700940d8fbf958c2b61215138 | 19905aea14e0673454cc7b99fee928999f403a2d | refs/heads/master | 2020-05-20T11:46:27.007883 | 2019-04-26T07:48:31 | 2019-05-08T00:44:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,633 | cpp | //
// Copyright 2016 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// DXTSRGBCompressedTextureTest.cpp
// Tests for sRGB DXT textures (GL_EXT_texture_compression_s3tc_srgb)
//
#include "test_utils/ANGLETest.h"
#include "test_utils/gl_raii.h"
#include "media/pixel.inl"
#include "DXTSRGBCompressedTextureTestData.inl"
using namespace angle;
static constexpr int kWindowSize = 64;
class DXTSRGBCompressedTextureTest : public ANGLETest
{
protected:
DXTSRGBCompressedTextureTest()
{
setWindowWidth(kWindowSize);
setWindowHeight(kWindowSize);
setConfigRedBits(8);
setConfigGreenBits(8);
setConfigBlueBits(8);
setConfigAlphaBits(8);
}
void SetUp() override
{
ANGLETest::SetUp();
constexpr char kVS[] =
"precision highp float;\n"
"attribute vec4 position;\n"
"varying vec2 texcoord;\n"
"void main() {\n"
" gl_Position = position;\n"
" texcoord = (position.xy * 0.5) + 0.5;\n"
" texcoord.y = 1.0 - texcoord.y;\n"
"}";
constexpr char kFS[] =
"precision highp float;\n"
"uniform sampler2D tex;\n"
"varying vec2 texcoord;\n"
"void main() {\n"
" gl_FragColor = texture2D(tex, texcoord);\n"
"}\n";
mTextureProgram = CompileProgram(kVS, kFS);
ASSERT_NE(0u, mTextureProgram);
mTextureUniformLocation = glGetUniformLocation(mTextureProgram, "tex");
ASSERT_NE(-1, mTextureUniformLocation);
ASSERT_GL_NO_ERROR();
}
void TearDown() override
{
glDeleteProgram(mTextureProgram);
ANGLETest::TearDown();
}
void runTestChecks(const TestCase &test)
{
GLColor actual[kWindowSize * kWindowSize] = {0};
drawQuad(mTextureProgram, "position", 0.5f);
ASSERT_GL_NO_ERROR();
glReadPixels(0, 0, kWindowSize, kWindowSize, GL_RGBA, GL_UNSIGNED_BYTE,
reinterpret_cast<void *>(actual));
ASSERT_GL_NO_ERROR();
for (GLsizei y = 0; y < test.height; ++y)
{
for (GLsizei x = 0; x < test.width; ++x)
{
GLColor exp = reinterpret_cast<const GLColor *>(test.expected)[y * test.width + x];
size_t x_actual = (x * kWindowSize + kWindowSize / 2) / test.width;
size_t y_actual =
((test.height - y - 1) * kWindowSize + kWindowSize / 2) / test.height;
GLColor act = actual[y_actual * kWindowSize + x_actual];
EXPECT_COLOR_NEAR(exp, act, 2.0);
}
}
}
void runTest(GLenum format)
{
ANGLE_SKIP_TEST_IF(!IsGLExtensionEnabled("GL_EXT_texture_compression_s3tc_srgb"));
const TestCase &test = kTests.at(format);
GLTexture texture;
glBindTexture(GL_TEXTURE_2D, texture.get());
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glUseProgram(mTextureProgram);
glUniform1i(mTextureUniformLocation, 0);
ASSERT_GL_NO_ERROR();
glCompressedTexImage2D(GL_TEXTURE_2D, 0, format, test.width, test.height, 0, test.dataSize,
test.data);
ASSERT_GL_NO_ERROR() << "glCompressedTexImage2D(format=" << format << ")";
runTestChecks(test);
glCompressedTexImage2D(GL_TEXTURE_2D, 0, format, test.width, test.height, 0, test.dataSize,
nullptr);
ASSERT_GL_NO_ERROR() << "glCompressedTexImage2D(format=" << format << ", data=null)";
glCompressedTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, test.width, test.height, format,
test.dataSize, test.data);
ASSERT_GL_NO_ERROR() << "glCompressedTexSubImage2D(format=" << format << ")";
runTestChecks(test);
ASSERT_GL_NO_ERROR();
}
GLuint mTextureProgram = 0;
GLint mTextureUniformLocation = -1;
};
// Test correct decompression of 8x8 textures (four 4x4 blocks) of SRGB_S3TC_DXT1
TEST_P(DXTSRGBCompressedTextureTest, Decompression8x8RGBDXT1)
{
runTest(GL_COMPRESSED_SRGB_S3TC_DXT1_EXT);
}
// Test correct decompression of 8x8 textures (four 4x4 blocks) of SRGB_ALPHA_S3TC_DXT1
TEST_P(DXTSRGBCompressedTextureTest, Decompression8x8RGBADXT1)
{
runTest(GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT);
}
// Test correct decompression of 8x8 textures (four 4x4 blocks) of SRGB_ALPHA_S3TC_DXT3
TEST_P(DXTSRGBCompressedTextureTest, Decompression8x8RGBADXT3)
{
runTest(GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT);
}
// Test correct decompression of 8x8 textures (four 4x4 blocks) of SRGB_ALPHA_S3TC_DXT5
TEST_P(DXTSRGBCompressedTextureTest, Decompression8x8RGBADXT5)
{
runTest(GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT);
}
// Use this to select which configurations (e.g. which renderer, which GLES major version) these
// tests should be run against.
ANGLE_INSTANTIATE_TEST(DXTSRGBCompressedTextureTest,
ES2_D3D11(),
ES3_D3D11(),
ES2_OPENGL(),
ES3_OPENGL(),
ES2_OPENGLES(),
ES3_OPENGLES(),
ES2_VULKAN());
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
1d322f3d21e77f272bc7fd04da7904af77379d50 | b637dea49d3d67a5a7c4f7a012c5208ea0478ee6 | /old/script/abc065a.cpp | c43d153aa790c72d54edf5bf0b8e635a88fb97b1 | [] | no_license | orca37/atcoder | 0797a3ef14d7c962e3e8456cab138557bd93c0b2 | 71f9ff28e083a78112f628ff8214ab50bfa13a09 | refs/heads/master | 2021-07-25T11:43:36.602752 | 2020-04-23T16:38:55 | 2020-04-23T16:38:55 | 157,965,779 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 375 | cpp | #include<iostream>
#include<string>
#include<vector>
#include<iomanip>
#include<algorithm>
#include<queue>
#include<stack>
#include<map>
using namespace std;
#define ll long long
int main(){
int X,A,B;
cin >> X >> A >> B;
if(B<=X){
cout << "delicious";
}else if(B<=A+X){
cout << "safe";
}else{
cout << "dangerous";
}
return 0;
}
| [
"22870342+orca37@users.noreply,github.com"
] | 22870342+orca37@users.noreply,github.com |
6a9febf7710febd55246b135dc7e5bf281f9fb17 | 68e0727b9692f7491e9a1daa9fc0f550a0ea6637 | /src/component/InteractStringMap.cpp | 27a3403c422adbdbbab51e4490032a1c57a328af | [] | no_license | ConnorHeidema/EmmoriaV2 | b3ea1fb4266362137677d96d00b2996e5d074e84 | 982d941e8713e0106a60ac9f7e4adb0e10477268 | refs/heads/master | 2023-02-16T20:48:02.393694 | 2021-01-15T02:54:22 | 2021-01-15T02:54:22 | 282,720,526 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,817 | cpp | #include "component/InteractStringMap.hpp"
#include "component/tag/AllTagComp.hpp"
#include "component/functional/HealthComp.hpp"
#include "component/functional/LastPositionComp.hpp"
#include "component/functional/PositionComp.hpp"
#include "component/functional/LocationComp.hpp"
#include "component/functional/SwitchComp.hpp"
#include "component/functional/DoorComp.hpp"
#include "component/functional/ClickableComp.hpp"
#include "component/functional/stats/MaxHealthComp.hpp"
#include "component/functional/SizeComp.hpp"
#include "component/functional/DialogComp.hpp"
#include "component/functional/SignInfoComp.hpp"
#include "component/functional/ChestComp.hpp"
#include "entity/EntityLoaderFactory.hpp"
#include "util/PositionUtils.hpp"
#include <sstream>
#include <limits>
#include <iostream>
#include <SFML/Window.hpp>
#include "entity/EntityMacro.hpp"
#define INTERACT_STRING_TO_TYPE_MAPPING(name) { #name , InteractType_t:: name##_t },
std::unordered_map<std::string, InteractType_t> InteractStringMap::s_interactStringToType =
{
ALL_TAG_MACRO(INTERACT_STRING_TO_TYPE_MAPPING)
{ "INVALID", InteractType_t::NUM_INTERACTOR_TYPE }
};
#undef INTERACT_STRING_TO_TYPE_MAPPING
#define INTERACT_TYPE_TO_STRING_MAPPING(name) { InteractType_t:: name##_t, #name },
std::unordered_map<InteractType_t, std::string> InteractStringMap::s_interactTypeToString =
{
ALL_TAG_MACRO(INTERACT_TYPE_TO_STRING_MAPPING)
{ InteractType_t::NUM_INTERACTOR_TYPE, "INVALID" }
};
#undef INTERACT_TYPE_TO_STRING_MAPPING
#include "entity/EntityMacroEnd.hpp"
void InteractStringMap::InteractPlayerCompHealingPadComp(entt::registry& rReg, entt::entity& rInteractorEntity, entt::entity& /*rInteractableEntity*/)
{
auto& healthComp = rReg.get<HealthComp>(rInteractorEntity);
int maxHealth = INT32_MAX;
if (rReg.has<MaxHealthComp>(rInteractorEntity))
{
maxHealth = rReg.get<MaxHealthComp>(rInteractorEntity).m_maxHealth;
}
healthComp.m_health = std::min(healthComp.m_health + 1, maxHealth);
}
void InteractStringMap::InteractPlayerCompBlobComp(entt::registry& rReg, entt::entity& rInteractorEntity, entt::entity& /*rInteractableEntity*/)
{
auto& healthComp = rReg.get<HealthComp>(rInteractorEntity);
healthComp.m_health -= 1;
}
void InteractStringMap::InteractWallInteractorCompWallComp(entt::registry& rReg, entt::entity& rInteractorEntity, entt::entity& rInteractableEntity)
{
auto& playerPosition = rReg.get<PositionComp>(rInteractorEntity).m_position;
auto& playerLastPosition = rReg.get<LastPositionComp>(rInteractorEntity).m_lastPosition;
auto& playerSize = rReg.get<SizeComp>(rInteractorEntity).m_size;
auto& wallPosition = rReg.get<PositionComp>(rInteractableEntity).m_position;
auto& wallSize = rReg.get<SizeComp>(rInteractableEntity).m_size;
PositionUtils::SetObjectToViablePosition(playerPosition, playerLastPosition, playerSize, wallPosition, wallSize);
}
void InteractStringMap::InteractArrowCompBlobComp(entt::registry& rReg, entt::entity& rInteractorEntity, entt::entity& rInteractableEntity)
{
rReg.emplace_or_replace<DeleteAfterInteractionComp>(rInteractorEntity);
auto& blobHealth = rReg.get_or_emplace<HealthComp>(rInteractableEntity).m_health;
blobHealth -= 5;
}
void InteractStringMap::InteractSwordCompBlobComp(entt::registry& rReg, entt::entity& rInteractorEntity, entt::entity& rInteractableEntity)
{
rReg.emplace_or_replace<DeleteAfterInteractionComp>(rInteractorEntity);
auto& blobHealth = rReg.get_or_emplace<HealthComp>(rInteractableEntity).m_health;
blobHealth -= 2;
// sword doesn't seem to hit as it should?
}
void InteractStringMap::InteractPlayerCompHoleComp(entt::registry& rReg, entt::entity& /*rInteractorEntity*/, entt::entity& /*rInteractableEntity*/)
{
rReg.view<LocationComp>().each([&](auto& locationComp)
{
rReg.view<PlayerComp, PositionComp, HealthComp>().each([&](auto& positionComp, auto& healthComp)
{
healthComp.m_health /= 2;
healthComp.m_health -= 1;
positionComp.m_position.x = locationComp.xSpawnLocation;
positionComp.m_position.y = locationComp.ySpawnLocation;
});
});
}
void InteractStringMap::InteractBlobCompHoleComp(entt::registry& rReg, entt::entity& rInteractorEntity, entt::entity& rInteractableEntity)
{
auto& blobLastPosition = rReg.get<LastPositionComp>(rInteractorEntity).m_lastPosition;
auto& blobPosition = rReg.get<PositionComp>(rInteractorEntity).m_position;
auto& blobSize = rReg.get<SizeComp>(rInteractorEntity).m_size;
auto& wallPosition = rReg.get<PositionComp>(rInteractableEntity).m_position;
auto& wallSize = rReg.get<SizeComp>(rInteractableEntity).m_size;
PositionUtils::SetObjectToViablePosition(blobPosition, blobLastPosition, blobSize, wallPosition, wallSize);
}
void InteractStringMap::InteractDepressableCompWeightComp(entt::registry& rReg, entt::entity& rInteractorEntity, entt::entity& /*rInteractableEntity*/)
{
auto& switchComp = rReg.get_or_emplace<SwitchComp>(rInteractorEntity);
switchComp.m_bPressed = true;
rReg.view<DoorComp>().each([&](auto& doorComp)
{
if (switchComp.m_action == doorComp.m_action)
{
doorComp.m_bOpen = true;
}
});
}
void InteractStringMap::InteractNearbyPlayerCompSignComp(entt::registry& rReg, entt::entity& /*rInteractorEntity*/, entt::entity& rInteractableEntity)
{
auto& bLeftDown = rReg.get_or_emplace<ClickableComp>(rInteractableEntity).m_bLeftDown;
bool dialogExists = false;
rReg.view<DialogComp>().each([&](auto& /*dialogComp*/) { dialogExists = true; });
if ((sf::Keyboard::isKeyPressed(sf::Keyboard::Space) || bLeftDown) && !dialogExists)
{
std::istringstream s(rReg.get_or_emplace<SignInfoComp>(rInteractableEntity).m_text);
auto entity = rReg.create();
EntityLoaderFactory::LoadBottomDialog(rReg, entity, s);
}
}
void InteractStringMap::InteractNearbyPlayerCompChestTagComp(entt::registry& rReg, entt::entity& /*rInteractorEntity*/, entt::entity& rInteractableEntity)
{
auto& chestAlreadyOpened = rReg.get<ChestComp>(rInteractableEntity).m_bOpened;
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Space) && !chestAlreadyOpened)
{
std::cout << "chest opened" << std::endl;
chestAlreadyOpened = true;
}
}
std::unordered_map<int, fnEntityInteractor> InteractStringMap::CreateInteractionFnList()
{
#include "component/InteractMacro.hpp"
#define INSERT(interactor, interactable) fn[ \
static_cast<int>(InteractType_t:: interactor##Comp_t) * \
static_cast<int>(InteractType_t::NUM_INTERACTOR_TYPE) + \
static_cast<int>(InteractType_t:: interactable##Comp_t)] \
= InteractStringMap:: Interact ## interactor ## Comp ## interactable ## Comp;
std::unordered_map<int, fnEntityInteractor> fn;
ALL_INTERACTIONS(INSERT)
#include "component/EndInteractMacro.hpp"
#undef INSERT
return fn;
}
std::unordered_map<int, fnEntityInteractor> InteractStringMap::fnInteractionMap
= InteractStringMap::CreateInteractionFnList(); | [
"heidema.connor@gmail.com"
] | heidema.connor@gmail.com |
3179d125f4ffc89a65f2e690624cf3de275d552b | 777a75e6ed0934c193aece9de4421f8d8db01aac | /src/Providers/UNIXProviders/tests/UNIXProviders.Tests/UNIX_SSHSettingDataFixture.cpp | 802dedb8786b4d715a2ccdacb5ba56561dc6045d | [
"MIT"
] | permissive | brunolauze/openpegasus-providers-old | 20fc13958016e35dc4d87f93d1999db0eae9010a | b00f1aad575bae144b8538bf57ba5fd5582a4ec7 | refs/heads/master | 2021-01-01T20:05:44.559362 | 2014-04-30T17:50:06 | 2014-04-30T17:50:06 | 19,132,738 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,796 | cpp | //%LICENSE////////////////////////////////////////////////////////////////
//
// Licensed to The Open Group (TOG) under one or more contributor license
// agreements. Refer to the OpenPegasusNOTICE.txt file distributed with
// this work for additional information regarding copyright ownership.
// Each contributor licenses this file to you under the OpenPegasus Open
// Source License; you may not use this file except in compliance with the
// License.
//
// 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 "UNIX_SSHSettingDataFixture.h"
#include <SSHSettingData/UNIX_SSHSettingDataProvider.h>
UNIX_SSHSettingDataFixture::UNIX_SSHSettingDataFixture()
{
}
UNIX_SSHSettingDataFixture::~UNIX_SSHSettingDataFixture()
{
}
void UNIX_SSHSettingDataFixture::Run()
{
CIMName className("UNIX_SSHSettingData");
CIMNamespaceName nameSpace("root/cimv2");
UNIX_SSHSettingData _p;
UNIX_SSHSettingDataProvider _provider;
Uint32 propertyCount;
CIMOMHandle omHandle;
_provider.initialize(omHandle);
_p.initialize();
for(int pIndex = 0; _p.load(pIndex); pIndex++)
{
CIMInstance instance = _provider.constructInstance(className,
nameSpace,
_p);
CIMObjectPath path = instance.getPath();
cout << path.toString() << endl;
propertyCount = instance.getPropertyCount();
for(Uint32 i = 0; i < propertyCount; i++)
{
CIMProperty propertyItem = instance.getProperty(i);
cout << " Name: " << propertyItem.getName().getString() << " - Value: " << propertyItem.getValue().toString() << endl;
}
cout << "------------------------------------" << endl;
cout << endl;
}
_p.finalize();
}
| [
"brunolauze@msn.com"
] | brunolauze@msn.com |
f45022926bd2796dafefc577f81e102494085bae | 90775c213a79c9ce1dcd0ab5206c19f00e7cb3e3 | /5less/hw/1/1_main.cpp | 2ff7215b6b634e87ec83a57bdcbc7806c0d20bd8 | [] | no_license | julproh/3_sem | 7dfeef1795581c0cf7e0f4fc14375b06c3870a84 | e4507f4f3d529bfe2b041c3f62bae1a7bb715f00 | refs/heads/main | 2023-03-25T08:03:18.201113 | 2021-03-24T08:44:52 | 2021-03-24T08:44:52 | 351,006,310 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 309 | cpp | #include <iostream>
#include "1.h"
using namespace std;
int islegs = 1;
int main () {
furniture first;
check_legs(first, islegs);
cout << endl;
furniture second ("table","black", 70, 70, 80, 1 );
second.set_height(60);
check_legs(second, islegs);
cout << endl;
return 0;
} | [
"cherry5005@mail.ru"
] | cherry5005@mail.ru |
558f601be33f0e600c230133a4d673c59ce18af7 | c4cab2201d408a84ecee2e736dea4cf75c9e86ce | /frag/src/midi/Control.h | b489159325d24d8214c2bb50f83b40a2d3f15a70 | [
"MIT"
] | permissive | chao-mu/art | ecd911816467a2fbbd4269256b36f4c394d4df53 | 20c536f42146648f8c6a2a3771c1eed69315a693 | refs/heads/master | 2020-04-27T23:16:17.363806 | 2019-08-18T20:10:00 | 2019-08-18T20:10:00 | 174,768,860 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 692 | h | #ifndef FRAG_MIDI_CONTROL_H_
#define FRAG_MIDI_CONTROL_H_
// STL
#include <string>
namespace frag {
namespace midi {
enum ControlType {
CONTROL_TYPE_BUTTON,
CONTROL_TYPE_FADER,
CONTROL_TYPE_UNKNOWN
};
struct Control {
bool isPressed();
std::string name = "";
ControlType type = CONTROL_TYPE_UNKNOWN;
bool toggle = false;
unsigned char value = 0;
unsigned char last_value = 0;
unsigned char low = 0;
unsigned char high = 0;
unsigned char function = 0;
unsigned char channel = 0;
};
}
}
#endif
| [
"chao-mu@hackpoetic.com"
] | chao-mu@hackpoetic.com |
2034237c31a46cbecd34c0b471eba7856433c630 | b746e4639e27d351cebf4e8b15aa26c3bf7da83b | /2D-Arrays/4.rotate_image_1.cpp | 9ddd9104a11fd9788411fc551d45fa5d347b30d6 | [] | no_license | JanviMahajan14/Algorithms | 97a2d40449565ac0f0b91d8e47bfa953d348dfce | cd951af6496066027586a0fcd4a9f48ee028a173 | refs/heads/master | 2023-07-16T19:08:42.917575 | 2021-09-02T07:33:44 | 2021-09-02T07:33:44 | 273,521,356 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 538 | cpp | #include <iostream>
using namespace std;
int main(){
int n,r,s;
cin >> n;
r = n-1, s = 0;
int a[n][n];int rotate[n][n] = {0};
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
cin >> a[i][j];
}
}
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
rotate[r--][s] = a[i][j];
}
r = n-1;
s++;
}
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
cout << rotate[i][j] << " ";
}
cout << endl;
}
}
| [
"janvimahajan337@gmail.com"
] | janvimahajan337@gmail.com |
c90510775b97d96f6df3165284ccd4beb0338e8b | 0f194c0a1ad76b71bac3854f30072bf6a50a6094 | /test/CoverageMapping/derivedclass.cpp | 2ba81b4bc350cd0a1a4bd786fd45c180da335f49 | [
"NCSA"
] | permissive | zgf/clang | 3900b22997f712c53a34f3abceec9fe50263d0fe | 28ec93edee9c6c69edda079c8dff3c0602165c26 | refs/heads/master | 2020-12-30T18:16:55.916356 | 2014-08-08T23:49:58 | 2014-08-08T23:49:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,116 | cpp | // RUN: %clang_cc1 -fprofile-instr-generate -fcoverage-mapping -dump-coverage-mapping -emit-llvm-only -main-file-name derivedclass.cpp %s | FileCheck %s
class Base {
protected:
int x;
public:
Base(int i, int j)
: x(i)
{
}
virtual ~Base() {
x = 0;
}
int getX() const { return x; }
virtual void setX(int i) {
x = i;
}
};
class Derived: public Base {
int y;
public:
Derived(int i)
: Base(i, i), y(0)
{ }
virtual ~Derived() {
y = 0;
}
virtual void setX(int i) {
x = y = i;
}
int getY() const {
return y;
}
};
// CHECK: File 0, 14:20 -> 14:33 = #0 (HasCodeBefore = 0)
// CHECK: File 0, 25:3 -> 25:6 = #0 (HasCodeBefore = 0)
// CHECK: File 0, 29:28 -> 31:4 = #0 (HasCodeBefore = 0)
// CHECK: File 0, 26:22 -> 28:4 = #0 (HasCodeBefore = 0)
// CHECK: File 0, 11:19 -> 13:4 = #0 (HasCodeBefore = 0)
// CHECK: File 0, 15:28 -> 17:4 = #0 (HasCodeBefore = 0)
// CHECK: File 0, 9:3 -> 10:4 = #0 (HasCodeBefore = 0)
// CHECK: File 0, 32:20 -> 34:4 = 0 (HasCodeBefore = 0)
int main() {
Base *B = new Derived(42);
B->setX(B->getX());
delete B;
return 0;
}
| [
"arphaman@gmail.com"
] | arphaman@gmail.com |
ecb003a97e6751681a9537448231de2b1cfd4d51 | 9db1ec69814f02e20349ddf7ccd172d16dbc5e11 | /CodeChef CCDSAP/Singly link list.cpp | 5117d34dbc648df90d95876b545ba0e4e867617d | [] | no_license | sourabh-27/Competitive-Programming | 652b4a5cd76cd262ff0c01f1845ac951624fb279 | 9689edc17e3c3f8c52233f6b4d9b568281ace7db | refs/heads/master | 2021-01-07T12:14:30.713480 | 2020-05-28T21:19:38 | 2020-05-28T21:19:38 | 239,506,729 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,004 | cpp | #include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
struct node
{
int data;
node * next;
}*start = NULL;
void creation();
void insertion(node *);
int deletion(node *);
void display
void creation()
{
node start = new node;
cout << "Please enter the data-value for first node" << endl;
cin >> start->data;
start->next = NULL;
}
void insertion(node *p)
{
while(p->next != NULL)
{
p = p->next;
}
node *temp = new node;
cout << "Enter the data of new value" << endl;
cin >> temp->data;
temp->next = NULL;
}
int deletion(node *ptr)
{
node *ptrP = NULL;
if(ptr == NULL)
{
cout << "List is empty" << endl;
return 0;
}
int val;
cout << "Enter the data-value to delete" << endl;
cin >> val;
while(ptr != NULL && ptr->data != val)
{
ptr = ptr->next;
}
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
return 0;
} | [
"majumdars844@gmail.com"
] | majumdars844@gmail.com |
9e43b41ade60620622d735c65bf1ad3734b6980a | 678b862dde1f55e8993a3b23bded440eaa80c9cb | /Projects/Project 3/nachos/code/userprog/progtest.cc | 118ec15be104675a0e8981c3972b5f4a52b18c81 | [
"MIT-Modern-Variant"
] | permissive | jjceball/120CSEFA14 | c5c97933bac795d9a54702a38a10b7d92043cb09 | 2833adf6caa39f10fb7f33b677129230a0b40b8f | refs/heads/master | 2020-05-22T14:55:20.698713 | 2015-03-02T02:04:42 | 2015-03-02T02:04:42 | 29,695,090 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,279 | cc | // progtest.cc
// Test routines for demonstrating that Nachos can load
// a user program and execute it.
//
// Also, routines for testing the Console hardware device.
//
// Copyright (c) 1992-1993 The Regents of the University of California.
// All rights reserved. See copyright.h for copyright notice and limitation
// of liability and disclaimer of warranty provisions.
#include "copyright.h"
#include "system.h"
#include "console.h"
#include "addrspace.h"
#include "synch.h"
#include "memorymanager.h"
#include "synchconsole.h"
#include "processmanager.h"
//----------------------------------------------------------------------
// StartProcess
// Run a user program. Open the executable, load it into
// memory, and jump to it.
//----------------------------------------------------------------------
MemoryManager* memoryManager;
ProcessManager* processManager;
SynchConsole* synchconsole;
AddrSpace* addspace;
void
StartProcess(char *filename)
{
OpenFile *executable = fileSystem->Open(filename);
AddrSpace *space;
memoryManager = new MemoryManager(NumPhysPages);
processManager = new ProcessManager(MAX_PROCESS);
synchconsole = new SynchConsole(0, 0);
if (executable == NULL) {
printf("Unable to open file %s\n", filename);
return;
}
addspace = new AddrSpace();
int startPID = processManager->Alloc(currentThread);
currentThread->setPID(startPID);
if(addspace->Initialize(executable))
{
currentThread->space = addspace;
}
else
{
ASSERT(FALSE);
}
space->InitRegisters(); // set the initial register values
space->RestoreState(); // load page table register
int spaceID = processManager->Alloc((void*)currentThread);
ASSERT(spaceID == 1);
currentThread->setPID(spaceID);
machine->Run(); // jump to the user progam
ASSERT(FALSE); // machine->Run never returns;
// the address space exits
// by doing the syscall "exit"
}
// Data structures needed for the console test. Threads making
// I/O requests wait on a Semaphore to delay until the I/O completes.
static Console *console;
static Semaphore *readAvail;
static Semaphore *writeDone;
//----------------------------------------------------------------------
// ConsoleInterruptHandlers
// Wake up the thread that requested the I/O.
//----------------------------------------------------------------------
static void ReadAvail(int arg) {
readAvail->V();
}
static void WriteDone(int arg) {
writeDone->V();
}
//----------------------------------------------------------------------
// ConsoleTest
// Test the console by echoing characters typed at the input onto
// the output. Stop when the user types a 'q'.
//----------------------------------------------------------------------
void
ConsoleTest (char *in, char *out)
{
char ch;
console = new Console(in, out, ReadAvail, WriteDone, 0);
readAvail = new Semaphore("read avail", 0);
writeDone = new Semaphore("write done", 0);
for (;;) {
readAvail->P(); // wait for character to arrive
ch = console->GetChar();
console->PutChar(ch); // echo it!
writeDone->P() ; // wait for write to finish
if (ch == 'q') return; // if q, quit
}
}
| [
"jayceballos@Jays-MacBook-Pro.local"
] | jayceballos@Jays-MacBook-Pro.local |
67c1e5f2da3fd6b3829544ec26b2a8d1291928b5 | 45874c847c5a2fc4e89e05a7fc8ad9b63d8c4860 | /sycl/test/native_cpu/unnamed.cpp | 79add27d2175793d3ab124da23f30f7c6b053925 | [
"LicenseRef-scancode-unknown-license-reference",
"NCSA",
"LLVM-exception",
"Apache-2.0"
] | permissive | intel/llvm | 2f023cefec793a248d8a237267410f5e288116c5 | a3d10cf63ddbdcc23712c45afd1b6b0a2ff5b190 | refs/heads/sycl | 2023-08-24T18:53:49.800759 | 2023-08-24T17:38:35 | 2023-08-24T17:38:35 | 166,008,577 | 1,050 | 735 | NOASSERTION | 2023-09-14T20:35:07 | 2019-01-16T09:05:33 | null | UTF-8 | C++ | false | false | 1,418 | cpp | // REQUIRES: native_cpu_be
// RUN: %clangxx -fsycl -fsycl-targets=native_cpu %s -o %t
// RUN: env ONEAPI_DEVICE_SELECTOR=native_cpu:cpu %t
#include <sycl/sycl.hpp>
#include <array>
#include <iostream>
constexpr sycl::access::mode sycl_read = sycl::access::mode::read;
constexpr sycl::access::mode sycl_write = sycl::access::mode::write;
int main() {
const size_t N = 4;
std::array<int, N> A = {{1, 2, 3, 4}}, B = {{2, 3, 4, 5}}, C{{0, 0, 0, 0}};
sycl::queue deviceQueue;
sycl::range<1> numOfItems{N};
sycl::buffer<int, 1> bufferA(A.data(), numOfItems);
sycl::buffer<int, 1> bufferB(B.data(), numOfItems);
sycl::buffer<int, 1> bufferC(C.data(), numOfItems);
deviceQueue
.submit([&](sycl::handler &cgh) {
auto accessorA = bufferA.get_access<sycl_read>(cgh);
auto accessorB = bufferB.get_access<sycl_read>(cgh);
auto accessorC = bufferC.get_access<sycl_write>(cgh);
auto kern = [=](sycl::id<1> wiID) {
accessorC[wiID] = accessorA[wiID] + accessorB[wiID];
};
cgh.parallel_for(numOfItems, kern);
})
.wait();
for (unsigned int i = 0; i < N; i++) {
std::cout << "C[" << i << "] = " << C[i] << "\n";
if (C[i] != A[i] + B[i]) {
std::cout << "The results are incorrect (element " << i << " is " << C[i]
<< "!\n";
return 1;
}
}
std::cout << "The results are correct!\n";
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
bf5cf51f477acdd4ed6248d4d3b5fe02ed9a53b1 | 3c09087dfcb423a58174943935ff12d05ce73824 | /project3/src/project3/main.cpp | d16a98f908858cead6798ebf7b70dd679ab3c61b | [] | no_license | healthycheekums/KESP | 1eb54637d9078d391cdfea94be0be3f5b32318af | 69bfaa3e5d1f80b44b03bb46bf6541de2a7701db | refs/heads/master | 2021-01-09T05:27:01.390382 | 2017-04-04T18:46:36 | 2017-04-04T18:46:36 | 80,770,218 | 0 | 3 | null | 2017-02-09T03:31:45 | 2017-02-02T21:26:06 | TeX | UTF-8 | C++ | false | false | 2,488 | cpp | #define _USE_MATH_DEFINES
#include <iostream>
#include <cmath>
#include <cstring>
#include <fstream>
#include <random>
#include <chrono>
#include <time.h>
#include "planet.h"
#include "solver.h"
using namespace std;
void PrintInitialValues(int, double, double, double *, double *, int);
void PrintFinalValues(int, double *, double *);
int main()
{
int IntegrationPoints; // No. of integration points
double FinalTime; // End time of calculation
int Dimension; // No. of spatial dimensions
cout << "Earth-Sun binary system" << endl;
Dimension = 3;
IntegrationPoints = 10000;
FinalTime = 50.;
double TimeStep = FinalTime/((double) IntegrationPoints);
double x[3],v[3]; // positions and velocities
// initial position x = 1AU, y = z = 0, vx = 2pi, vy=0, vz=0
planet planet1(0.000003,1.,0.0,0.0,0.0,6.3,0.); // Earth: (mass,x,y,z,vx,vy,vz)
planet planet2(1.,0.,0.,0.,0.,0.,0.); // Sun: (mass,x,y,z,vx,vy,vz)
solver binary_vv(5.0);
binary_vv.add(planet1);
binary_vv.add(planet2);
PrintInitialValues(Dimension,TimeStep,FinalTime,x,v,IntegrationPoints);
cout << "Velocity Verlet results for the Sun-Earth system:" << endl;
binary_vv.VelocityVerlet(Dimension,IntegrationPoints,FinalTime,1,0.);
for(int j = 0; j < Dimension;j++){
x[j] = binary_vv.all_planets[0].position[j];
v[j] = binary_vv.all_planets[0].velocity[j];
}
PrintFinalValues(Dimension,x,v);
return 0;
}
void PrintInitialValues(int Dimension,double TimeStep, double FinalTime,double *x_initial,double *v_initial, int N){
// A function that prints out the set up of the calculation
cout << "Time step = " << TimeStep << "; final time = " << FinalTime << "; integration points = " << N << endl;
cout << "Initial position = ";
for(int j=0;j<Dimension;j++) cout << x_initial[j] << " ";
cout << endl;
cout << "Initial velocity = ";
for(int j=0;j<Dimension;j++) cout << v_initial[j] << " ";
cout << endl;
}
void PrintFinalValues(int Dimension,double *x_final,double *v_final){
// A function that prints out the final results of the calculation
cout << "Final position = ";
for(int j=0; j<Dimension; j++) cout << x_final[j] << " ";
cout << endl;
cout << "Final velocity = ";
for(int j=0; j<Dimension; j++) cout << v_final[j] << " ";
cout << endl;
}
| [
"healthycheekums@gmail.com"
] | healthycheekums@gmail.com |
9934ca2214e7d1868694c71f0461944dd22851ea | 7a2737c7228b434b758236cb85ad9f00adb9c07a | /include/error.hpp | 98fb3ee32703828e3e148989676f6cb65bf38be1 | [] | no_license | rocdat/PhD-1D-ghostfluidmethod | 8da65bdfcb7292c7e26717f234c29f4c7608916a | 1b3f19463ecba62c2690c25bcacf37f18d4e0903 | refs/heads/master | 2021-01-19T12:39:54.253082 | 2017-05-24T17:25:59 | 2017-05-24T17:25:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,902 | hpp | #ifndef ERROR_H
#define ERROR_H
#include "input.hpp"
#include "data_storage.hpp"
#include <blitz/array.h>
blitz::Array<double,2> get_cellwise_error (
fluid_state_array& fluid1,
settingsfile& SF
);
void get_density_errornorms (
blitz::Array<double,2> cellwise_error,
double& L1error,
double& Linferror
);
void get_velocity_errornorms (
blitz::Array<double,2> cellwise_error,
double& L1error,
double& Linferror
);
void get_pressure_errornorms (
blitz::Array<double,2> cellwise_error,
double& L1error,
double& Linferror
);
void output_errornorms_to_file (
fluid_state_array& fluid1,
settingsfile& SF
);
void output_cellwise_error (
fluid_state_array& fluid1,
settingsfile& SF
);
blitz::Array<double,2> get_twofluid_cellwise_error (
fluid_state_array& fluid1,
fluid_state_array& fluid2,
levelset_array& ls,
settingsfile& SF
);
void output_twofluid_errornorms_to_file (
fluid_state_array& fluid1,
fluid_state_array& fluid2,
levelset_array& ls,
settingsfile& SF
);
void output_twofluid_cellwise_error (
fluid_state_array& fluid1,
fluid_state_array& fluid2,
levelset_array& ls,
settingsfile& SF
);
void compute_total_U_onefluid (
fluid_state_array& fluid1,
blitz::Array<double,1> U0
);
void update_total_U_onefluid (
blitz::Array<double,1> FL,
blitz::Array<double,1> FR,
blitz::Array<double,1> U,
double dt
);
void output_conservation_errors_to_file (
blitz::Array<double,1> Ut,
blitz::Array<double,1> U0,
double t,
settingsfile& SF
);
void compute_total_U_twofluid (
fluid_state_array& fluid1,
fluid_state_array& fluid2,
levelset_array& ls,
blitz::Array<double,1> U0
);
void update_total_U_twofluid (
blitz::Array<double,1> FL1,
blitz::Array<double,1> FR1,
blitz::Array<double,1> FL2,
blitz::Array<double,1> FR2,
levelset_array& ls,
blitz::Array<double,1> U,
double dt,
fluid_state_array& fluid1
);
#endif
| [
"mcc74@cam.ac.uk"
] | mcc74@cam.ac.uk |
6d362c616b83dda7bc048b99b7676a74bb1a5862 | 96d75738600c6d295266fd4af5e81957a3a26a26 | /library/src/blas1/rocblas_rotmg.hpp | 49b1e2e319006687cb63b614fd8d03733fff7bd1 | [
"MIT"
] | permissive | streamhsa/rocBLAS | ab92a1dfcf92893a93c893ecb210ce455d96f2bd | effaa52647bfcbc1dc90db2a109e05ea230604d9 | refs/heads/develop | 2020-08-04T00:53:54.099353 | 2019-11-02T23:48:29 | 2019-11-02T23:48:29 | 211,943,149 | 0 | 0 | MIT | 2019-11-02T23:48:30 | 2019-09-30T19:50:32 | null | UTF-8 | C++ | false | false | 7,643 | hpp | /* ************************************************************************
* Copyright 2016-2019 Advanced Micro Devices, Inc.
* ************************************************************************ */
#include "handle.h"
#include "logging.h"
#include "rocblas.h"
#include "utility.h"
template <typename T>
__device__ __host__ void rocblas_rotmg_calc(T& d1, T& d2, T& x1, const T& y1, T* param)
{
const T gam = 4096;
const T gamsq = gam * gam;
const T rgamsq = 1 / gamsq;
T flag = -1;
T h11 = 0, h21 = 0, h12 = 0, h22 = 0;
if(d1 < 0)
{
d1 = d2 = x1 = 0;
}
else
{
T p2 = d2 * y1;
if(p2 == 0)
{
flag = -2;
param[0] = flag;
return;
}
T p1 = d1 * x1;
T q2 = p2 * y1;
T q1 = p1 * x1;
if(rocblas_abs(q1) > rocblas_abs(q2))
{
h21 = -y1 / x1;
h12 = p2 / p1;
T u = 1 - h12 * h21;
if(u > 0)
{
flag = 0;
d1 /= u;
d2 /= u;
x1 *= u;
}
}
else
{
if(q2 < 0)
{
d1 = d2 = x1 = 0;
}
else
{
flag = 1;
h11 = p1 / p2;
h22 = x1 / y1;
T u = 1 + h11 * h22;
T temp = d2 / u;
d2 = d1 / u;
d1 = temp;
x1 = y1 * u;
}
}
if(d1 != 0)
{
while((d1 <= rgamsq) || (d1 >= gamsq))
{
if(flag == 0)
{
h11 = h22 = 1;
flag = -1;
}
else
{
h21 = -1;
h12 = 1;
flag = -1;
}
if(d1 <= rgamsq)
{
d1 *= gamsq;
x1 /= gam;
h11 /= gam;
h12 /= gam;
}
else
{
d1 /= gamsq;
x1 *= gam;
h11 *= gam;
h12 *= gam;
}
}
}
if(d2 != 0)
{
while((rocblas_abs(d2) <= rgamsq) || (rocblas_abs(d2) >= gamsq))
{
if(flag == 0)
{
h11 = h22 = 1;
flag = -1;
}
else
{
h21 = -1;
h12 = 1;
flag = -1;
}
if(rocblas_abs(d2) <= rgamsq)
{
d2 *= gamsq;
h21 /= gam;
h22 /= gam;
}
else
{
d2 /= gamsq;
h21 *= gam;
h22 *= gam;
}
}
}
}
if(flag < 0)
{
param[1] = h11;
param[2] = h21;
param[3] = h12;
param[4] = h22;
}
else if(flag == 0)
{
param[2] = h21;
param[3] = h12;
}
else
{
param[1] = h11;
param[4] = h22;
}
param[0] = flag;
}
template <typename T, typename U>
__global__ void rocblas_rotmg_kernel(T d1_in,
rocblas_int offset_d1,
rocblas_stride stride_d1,
T d2_in,
rocblas_int offset_d2,
rocblas_stride stride_d2,
T x1_in,
rocblas_int offset_x1,
rocblas_stride stride_x1,
U y1_in,
rocblas_int offset_y1,
rocblas_stride stride_y1,
T param,
rocblas_int offset_param,
rocblas_stride stride_param,
rocblas_int batch_count)
{
auto d1 = load_ptr_batch(d1_in, hipBlockIdx_x, offset_d1, stride_d1);
auto d2 = load_ptr_batch(d2_in, hipBlockIdx_x, offset_d2, stride_d2);
auto x1 = load_ptr_batch(x1_in, hipBlockIdx_x, offset_x1, stride_x1);
auto y1 = load_ptr_batch(y1_in, hipBlockIdx_x, offset_y1, stride_y1);
auto p = load_ptr_batch(param, hipBlockIdx_x, offset_param, stride_param);
rocblas_rotmg_calc(*d1, *d2, *x1, *y1, p);
}
template <typename T, typename U>
rocblas_status rocblas_rotmg_template(rocblas_handle handle,
T d1_in,
rocblas_int offset_d1,
rocblas_stride stride_d1,
T d2_in,
rocblas_int offset_d2,
rocblas_stride stride_d2,
T x1_in,
rocblas_int offset_x1,
rocblas_stride stride_x1,
U y1_in,
rocblas_int offset_y1,
rocblas_stride stride_y1,
T param,
rocblas_int offset_param,
rocblas_stride stride_param,
rocblas_int batch_count)
{
if(!batch_count)
return rocblas_status_success;
hipStream_t rocblas_stream = handle->rocblas_stream;
if(rocblas_pointer_mode_device == handle->pointer_mode)
{
hipLaunchKernelGGL(rocblas_rotmg_kernel,
batch_count,
1,
0,
rocblas_stream,
d1_in,
offset_d1,
stride_d1,
d2_in,
offset_d2,
stride_d2,
x1_in,
offset_x1,
stride_x1,
y1_in,
offset_y1,
stride_y1,
param,
offset_param,
stride_param,
batch_count);
}
else
{
RETURN_IF_HIP_ERROR(hipStreamSynchronize(rocblas_stream));
// TODO: make this faster for a large number of batches.
for(int i = 0; i < batch_count; i++)
{
auto d1 = load_ptr_batch(d1_in, i, offset_d1, stride_d1);
auto d2 = load_ptr_batch(d2_in, i, offset_d2, stride_d2);
auto x1 = load_ptr_batch(x1_in, i, offset_x1, stride_x1);
auto y1 = load_ptr_batch(y1_in, i, offset_y1, stride_y1);
auto p = load_ptr_batch(param, i, offset_param, stride_param);
rocblas_rotmg_calc(*d1, *d2, *x1, *y1, p);
}
}
return rocblas_status_success;
} | [
"noreply@github.com"
] | noreply@github.com |
42782a460cc9e5010e9da368d195ba5c1ec5f1ef | f6cb7601235761d72ef6e17e5552b8a83e123ec8 | /uni10/src/uni10/uni10_lapack_cpu/uni10_elem_sub.cpp | 569f31130c0fc70c62445767d198f983c39694a5 | [] | no_license | kvzhao/Templates_uni10 | 3ea3905aee4880301f5f6acd1991f2e683fb6fcb | efeeb280f7c05f2c14598b366eb2581c4a357f9a | refs/heads/master | 2020-06-13T13:34:51.129402 | 2016-12-01T15:29:18 | 2016-12-01T15:29:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,755 | cpp | #include "uni10/uni10_lapack_cpu/uni10_elem_linalg_lapack_cpu.h"
namespace uni10{
void matrixSub(uni10_elem_double64* A, uni10_bool* isAdiag, const uni10_elem_double64* B, uni10_const_bool* isBdiag,
const uni10_uint64* M, const uni10_uint64* N){
if(isAdiag && !isBdiag){
uni10_uint64 elemNum = A->__elemNum;
uni10_double64* _elem = (uni10_double64*)malloc(A->__elemNum * sizeof(uni10_double64));
uni10_elem_copy_cpu(_elem, A->__elem, A->__elemNum*sizeof(uni10_double64));
*isAdiag = false;
A->init(*M, *N, false, B->__elem);
uni10_double64 alpha = -1.;
uni10_linalg::vectorScal(alpha , A->__elem, A->__elemNum);
for(int i = 0; i < (int)elemNum; i++)
A->__elem[i*(*N)+i] += _elem[i];
free(_elem);
}
else if(!isAdiag && isBdiag){
uni10_uint64 elemNum = B->__elemNum;
for(int i = 0; i < (int)elemNum; i++)
A->__elem[i*(*N)+i] -= B->__elem[i];
}
else
uni10_linalg::vectorSub(A->__elem, B->__elem, B->__elemNum);
}
void matrixSub(uni10_elem_complex128* A, uni10_bool* isAdiag, const uni10_elem_complex128* B, uni10_const_bool* isBdiag,
const uni10_uint64* M, const uni10_uint64* N){
if(isAdiag && !isBdiag){
uni10_uint64 elemNum = A->__elemNum;
uni10_complex128* _elem = (uni10_complex128*)malloc(A->__elemNum * sizeof(uni10_complex128));
uni10_elem_copy_cpu(_elem, A->__elem, A->__elemNum*sizeof(uni10_complex128));
*isAdiag = false;
A->init(*M, *N, false, B->__elem);
uni10_double64 alpha = -1.;
uni10_linalg::vectorScal(alpha , A->__elem, A->__elemNum);
for(int i = 0; i < (int)elemNum; i++)
A->__elem[i*(*N)+i] += _elem[i];
free(_elem);
}
else if(!isAdiag && isBdiag){
uni10_uint64 elemNum = B->__elemNum;
for(int i = 0; i < (int)elemNum; i++)
A->__elem[i*(*N)+i] -= B->__elem[i];
}
else
uni10_linalg::vectorSub(A->__elem, B->__elem, B->__elemNum);
}
void matrixSub(uni10_elem_complex128* A, uni10_bool* isAdiag, const uni10_elem_double64* B, uni10_const_bool* isBdiag,
const uni10_uint64* M, const uni10_uint64* N){
if(isAdiag && !isBdiag){
uni10_uint64 elemNum = A->__elemNum;
uni10_complex128* _elem = (uni10_complex128*)malloc(A->__elemNum * sizeof(uni10_complex128));
uni10_elem_copy_cpu(_elem, A->__elem, A->__elemNum*sizeof(uni10_double64));
*isAdiag = false;
A->init(*M, *N, false, NULL);
uni10_elem_cast_cpu(A->__elem, B->__elem, B->__elemNum);
uni10_double64 alpha = -1.;
uni10_linalg::vectorScal(alpha , A->__elem, A->__elemNum);
for(int i = 0; i < (int)elemNum; i++)
A->__elem[i*(*N)+i] += _elem[i];
free(_elem);
}
else if(!isAdiag && isBdiag){
uni10_uint64 elemNum = B->__elemNum;
for(int i = 0; i < (int)elemNum; i++)
A->__elem[i*(*N)+i] -= B->__elem[i];
}
else
uni10_linalg::vectorSub(A->__elem, B->__elem, B->__elemNum);
}
void matrixSub(const uni10_elem_double64* A, uni10_const_bool* isAdiag, const uni10_elem_double64* B, uni10_const_bool* isBdiag,
const uni10_uint64* M, const uni10_uint64* N, uni10_elem_double64* C){
if( !*isAdiag && !*isBdiag ){
uni10_elem_copy_cpu(C->__elem, A->__elem, A->__elemNum * sizeof(uni10_double64) );
uni10_linalg::vectorSub(C->__elem, B->__elem, C->__elemNum);
}
else if( *isAdiag && !*isBdiag ){
uni10_elem_copy_cpu(C->__elem, B->__elem, B->__elemNum * sizeof(uni10_double64) );
uni10_uint64 min = std::min(*M, *N);
uni10_linalg::vectorScal(-1., C->__elem, C->__elemNum);
for(int i = 0; i < (int)min; i++){
C->__elem[i * (*N) + i] += A->__elem[i];
}
}
else if( !*isAdiag && *isBdiag ){
uni10_elem_copy_cpu(C->__elem, A->__elem, A->__elemNum * sizeof(uni10_double64) );
uni10_uint64 min = std::min(*M, *N);
for(int i = 0; i < (int)min; i++)
C->__elem[i * (*N) + i] -= B->__elem[i];
}
else{
uni10_elem_copy_cpu(C->__elem, A->__elem, C->__elemNum*sizeof(uni10_double64));
uni10_linalg::vectorSub(C->__elem, B->__elem, C->__elemNum);
}
}
void matrixSub(const uni10_elem_complex128* A, uni10_const_bool* isAdiag, const uni10_elem_complex128* B, uni10_const_bool* isBdiag,
const uni10_uint64* M, const uni10_uint64* N, uni10_elem_complex128* C){
if( !*isAdiag && !*isBdiag ){
uni10_elem_copy_cpu(C->__elem, A->__elem, A->__elemNum * sizeof(uni10_complex128));
uni10_linalg::vectorSub(C->__elem, B->__elem, C->__elemNum);
}
else if( *isAdiag && !*isBdiag ){
uni10_elem_copy_cpu(C->__elem, B->__elem, B->__elemNum * sizeof(uni10_complex128));
uni10_uint64 min = std::min(*M, *N);
uni10_linalg::vectorScal(-1., C->__elem, C->__elemNum);
for(int i = 0; i < (int)min; i++){
C->__elem[i * (*N) + i] += A->__elem[i];
}
}
else if( !*isAdiag && *isBdiag ){
uni10_elem_copy_cpu(C->__elem, A->__elem, A->__elemNum * sizeof(uni10_complex128));
uni10_uint64 min = std::min(*M, *N);
for(int i = 0; i < (int)min; i++)
C->__elem[i * (*N) + i] -= B->__elem[i];
}
else{
uni10_elem_copy_cpu(C->__elem, A->__elem, A->__elemNum*sizeof(uni10_complex128));
uni10_linalg::vectorSub(C->__elem, B->__elem, C->__elemNum);
}
}
void matrixSub(const uni10_elem_double64* A, uni10_const_bool* isAdiag, const uni10_elem_complex128* B, uni10_const_bool* isBdiag,
const uni10_uint64* M, const uni10_uint64* N, uni10_elem_complex128* C){
uni10_error_msg(true, "%s", "Debugging !!!");
if( !*isAdiag && !*isBdiag ){
uni10_elem_copy_cpu(C->__elem, B->__elem, B->__elemNum * sizeof(uni10_complex128) );
uni10_linalg::vectorSub(C->__elem, A->__elem, C->__elemNum);
}
else if( *isAdiag && !*isBdiag ){
uni10_elem_copy_cpu(C->__elem, B->__elem, B->__elemNum * sizeof(uni10_complex128) );
uni10_uint64 min = std::min(*M, *N);
for(int i = 0; i < (int)min; i++)
C->__elem[i * (*N) + i] -= A->__elem[i];
}
else if( !*isAdiag && *isBdiag ){
uni10_elem_cast_cpu(C->__elem, A->__elem, C->__elemNum);
uni10_uint64 min = std::min(*M, *N);
for(int i = 0; i < (int)min; i++)
C->__elem[i * (*N) + i] -= B->__elem[i];
}
else{
uni10_elem_copy_cpu(C->__elem, B->__elem, C->__elemNum*sizeof(uni10_complex128));
uni10_linalg::vectorSub(C->__elem, A->__elem, C->__elemNum);
}
}
void matrixSub(const uni10_elem_complex128* A, uni10_const_bool* isAdiag, const uni10_elem_double64* B, uni10_const_bool* isBdiag,
const uni10_uint64* M, const uni10_uint64* N, uni10_elem_complex128* C){
uni10_error_msg(true, "%s", "Debugging !!!");
if( !*isAdiag && !*isBdiag ){
uni10_elem_copy_cpu(C->__elem, A->__elem, A->__elemNum * sizeof(uni10_complex128) );
uni10_linalg::vectorSub(C->__elem, B->__elem, C->__elemNum);
}
else if( *isAdiag && !*isBdiag ){
uni10_elem_cast_cpu(C->__elem, B->__elem, B->__elemNum);
uni10_uint64 min = std::min(*M, *N);
for(int i = 0; i < (int)min; i++)
C->__elem[i * (*N) + i] -= A->__elem[i];
}
else if( !*isAdiag && *isBdiag ){
uni10_elem_copy_cpu(C->__elem, A->__elem, A->__elemNum * sizeof(uni10_complex128) );
uni10_uint64 min = std::min(*M, *N);
for(int i = 0; i < (int)min; i++)
C->__elem[i * (*N) + i] -= B->__elem[i];
}
else{
uni10_elem_copy_cpu(C->__elem, A->__elem, A->__elemNum*sizeof(uni10_complex128));
uni10_linalg::vectorSub(C->__elem, A->__elem, C->__elemNum);
}
}
}
| [
"hunterlj3201@gmail.com"
] | hunterlj3201@gmail.com |
1163df5d814fdf1290f9c655809a6a3d609d82b6 | d905d94ae2f3de42f137fb8f8d794a2727de2fff | /459-A: Pashmak and Garden.cpp | 0f800c804ba06fb16c17d2a97e986750a60764c9 | [] | no_license | paramgoswami/Codeforces-Codes | 80f00cd5e790e7154ac8daba5df87d7105b6fe69 | 3ea93d341b942e4ead30d530be36d066f0f29e7d | refs/heads/master | 2022-11-24T01:14:26.880617 | 2020-07-21T19:33:53 | 2020-07-21T19:33:53 | 258,705,937 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 845 | cpp | //https://codeforces.com/contest/459/problem/A
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main()
{
int x1,x2,y1,y2;
int x3,y3,x4,y4;
int c=0;
cin>>x1>>y1>>x2>>y2;
if(x1==x2)
{
y3=y1;y4=y2;
if((x1+y4-y3<=1000) && (x1+y4-y3>=-1000))
{
x3=x1+y4-y3;
x4=x3;
}
else
{
x3=x1+y3-y4;
x4=x3;
}
}
else if(y1==y2)
{
x3=x1,x4=x2;
if((y1+x3-x2<=1000) &&(y1+x3-x2>=-1000))
{
y3=y1+x3-x2;
y4=y3;
}
else{
y3=y1+x2-x3;
y4=y1;
}
}
else
{
if(abs(x1-x2)==abs(y1-y2))
{
x3=x1;y3=y2;
x4=x2;y4=y1;
}
else c++;
}
if(c) cout<<-1<<endl;
else cout<<x3<<" "<<y3<<" "<<x4<<" "<<y4<<endl;
} | [
"paramgoswami2000@gmail.com"
] | paramgoswami2000@gmail.com |
ae8a3360dbac6f7fe883bcd073a36bf6c6cabbb5 | 03b5b626962b6c62fc3215154b44bbc663a44cf6 | /src/keywords/atomic_cancel.h | 82d52065137f4aaf88db14c84fa01ca0354065fa | [] | no_license | haochenprophet/iwant | 8b1f9df8ee428148549253ce1c5d821ece0a4b4c | 1c9bd95280216ee8cd7892a10a7355f03d77d340 | refs/heads/master | 2023-06-09T11:10:27.232304 | 2023-05-31T02:41:18 | 2023-05-31T02:41:18 | 67,756,957 | 17 | 5 | null | 2018-08-11T16:37:37 | 2016-09-09T02:08:46 | C++ | UTF-8 | C++ | false | false | 250 | h | #ifndef ATOMIC_CANCEL_H
#define ATOMIC_CANCEL_H
#include "../object.h"
namespace n_atomic_cancel {
class Catomic_cancel :public Object
{
public:
Catomic_cancel();
int my_init(void *p=nullptr);
};
}
using namespace n_atomic_cancel;
#endif
| [
"hao__chen@sina.com"
] | hao__chen@sina.com |
5511c9becb7b3fc70c31981120a5ca3985dcdc02 | 7fd5e6156d6a42b305809f474659f641450cea81 | /boost/spirit/include/classic_core.hpp | 183ba7561919c8b88ea95eb0c832253c641cffa5 | [] | no_license | imos/icfpc2015 | 5509b6cfc060108c9e5df8093c5bc5421c8480ea | e998055c0456c258aa86e8379180fad153878769 | refs/heads/master | 2020-04-11T04:30:08.777739 | 2015-08-10T11:53:12 | 2015-08-10T11:53:12 | 40,011,767 | 8 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 576 | hpp | /*=============================================================================
Copyright (c) 2001-2008 Joel de Guzman
Copyright (c) 2001-2008 Hartmut Kaiser
http://spirit.sourceforge.net/
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_SPIRIT_INCLUDE_CLASSIC_CORE
#define BOOST_SPIRIT_INCLUDE_CLASSIC_CORE
#include "boost/spirit/home/classic/core.hpp"
#endif
| [
"git@imoz.jp"
] | git@imoz.jp |
cd8e73ab3d4ab87ef423a4af52cc35f1e815c0bc | 0d4e28f7e9d961e45d32a4735ad7c1f76bbda34a | /ocs2_thirdparty/include/cppad/local/utility/cppad_vector_itr.hpp | e4679839812e02e8b9b7354f93762fcb3c82855d | [
"BSD-3-Clause",
"EPL-2.0",
"GPL-2.0-only"
] | permissive | RoboMark9/ocs2 | a4fc0c215ccb3a86afeffe93b6a67fb0d9dd9450 | b037d819c9a02a674de9badb628b32646ce11d6a | refs/heads/main | 2023-08-29T15:20:07.117885 | 2021-10-20T13:09:37 | 2021-10-20T13:09:37 | 453,286,119 | 1 | 0 | BSD-3-Clause | 2022-01-29T03:30:28 | 2022-01-29T03:30:27 | null | UTF-8 | C++ | false | false | 11,720 | hpp | # ifndef CPPAD_LOCAL_UTILITY_CPPAD_VECTOR_ITR_HPP
# define CPPAD_LOCAL_UTILITY_CPPAD_VECTOR_ITR_HPP
/* --------------------------------------------------------------------------
CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-19 Bradley M. Bell
CppAD is distributed under the terms of the
Eclipse Public License Version 2.0.
This Source Code may also be made available under the following
Secondary License when the conditions for such availability set forth
in the Eclipse Public License, Version 2.0 are satisfied:
GNU General Public License, Version 2.0 or later.
---------------------------------------------------------------------------- */
# include <cstddef>
# include <cppad/core/cppad_assert.hpp>
/*
------------------------------------------------------------------------------
$begin cppad_vector_itr_define$$
$spell
Iterator
cppad
itr
undef
const
endif
hpp
$$
$section Vector Class Iterator Preprocessor Definitions$$
$head Syntax$$
$codep
# define CPPAD_CONST 0
# include <cppad/local/utility/cppad_vector_itr.hpp>
# undef CPPAD_LOCAL_UTILITY_CPPAD_VECTOR_ITR_HPP
# define CPPAD_CONST 1
# include <cppad/local/utility/cppad_vector_itr.hpp>
%$$
$head Beginning of cppad_vector_itr.hpp$$
The following preprocessor definition appears at the beginning of
$code cppad_vector_itr.hpp$$ and is used for the class definition in this file:
$codep
# if CPPAD_CONST
# define CPPAD_VECTOR_ITR const_cppad_vector_itr
# else
# define CPPAD_VECTOR_ITR cppad_vector_itr
# endif
$$
$head End of cppad_vector_itr.hpp$$
The following preprocessor definition appears at the end of
$code cppad_vector_itr.hpp$$ so that it can be included with a different
value for $code CPPAD_CONST$$:
$codep
# undef CPPAD_CONST
# undef CPPAD_VECTOR_ITR
$$
$end
*/
# if CPPAD_CONST
# define CPPAD_VECTOR_ITR const_cppad_vector_itr
# else
# define CPPAD_VECTOR_ITR cppad_vector_itr
# endif
// BEGIN_CPPAD_LOCAL_UTILITY_NAMESPACE
namespace CppAD { namespace local { namespace utility {
// so can be declared friend in cppad_vector_itr<Type>
template <class Type> class const_cppad_vector_itr;
// ==========================================================================
template <class Type> class CPPAD_VECTOR_ITR {
// ==========================================================================
/*
-----------------------------------------------------------------------------
$begin cppad_vector_itr_traits$$
$spell
Iterator
$$
$section Vector Class Iterator Traits and Friends$$
$srccode%hpp% */
# if ! CPPAD_CONST
friend class const_cppad_vector_itr<Type>;
# endif
public:
typedef std::random_access_iterator_tag iterator_category;
typedef Type value_type;
typedef std::ptrdiff_t difference_type;
typedef Type* pointer;
typedef Type& reference;
/* %$$
$end
-------------------------------------------------------------------------------
$begin cppad_vector_itr_ctor$$
$spell
Iterator
ptr
cppad
Namespace
CppAD
const
iterators
itr
$$
$section Vector Class Iterator Member Data and Constructors$$
$head Constructors$$
$subhead Constant$$
$codei%const_cppad_vector_itr %itr%()
%$$
$codei%const_cppad_vector_itr %itr%(%data%, %length%, %index%)
%$$
$codei%const_cppad_vector_itr %itr%(%other%)
%$$
$codei%const_cppad_vector_itr %itr%(%non_const_other%)
%$$
$subhead Not Constant$$
$codei%cppad_vector_itr %itr%()
%$$
$codei%cppad_vector_itr %itr%(%data%, %length%, %index%)
%$$
$codei%cppad_vector_itr %itr%(%other%)
%$$
$head Namespace$$
These definitions are in the $code CppAD::local::utility$$ namespace.
$head Indirection$$
We use an extra level of indirection in this routine so that
the iterator has the same values as the vector even if the vector changes.
$head data_$$
is a pointer to a constant pointer to data for this vector
(used by operations that are not supported by constant iterators).
$head length_$$
is a pointer to the length of the corresponding vector.
$head index_$$
is the current vector index corresponding to this iterator.
$head check_element$$
generates an assert with a known cause when the $code index_$$
does not correspond go a valid element and
$code NDEBUG$$ is not defined.
$head check_cop$$
Generates an assert with a known cause when the $code data_$$
for this vector is different from the other vector and
$code NDEBUG$$ is not defined.
This should be used by operators that compare iterators.
$head Source$$
$srccode%hpp% */
private:
# if CPPAD_CONST
const Type* const* data_;
# else
Type* const* data_;
# endif
const size_t* length_;
difference_type index_;
void check_element(void) const CPPAD_NDEBUG_NOEXCEPT
{ CPPAD_ASSERT_KNOWN( 0 <= index_ && size_t(index_) < *length_,
"CppAD vector iterator: accessing element out of range"
);
}
void check_cop(const CPPAD_VECTOR_ITR& other) const CPPAD_NDEBUG_NOEXCEPT
{ CPPAD_ASSERT_KNOWN( data_ == other.data_,
"CppAD vector iterator: comparing indices from different vectors"
);
}
public:
CPPAD_VECTOR_ITR(void) CPPAD_NOEXCEPT
: data_(CPPAD_NULL), length_(CPPAD_NULL), index_(0)
{ }
# if CPPAD_CONST
const_cppad_vector_itr(
const Type* const* data, const size_t* length, difference_type index
) CPPAD_NOEXCEPT
: data_(data), length_(length), index_( difference_type(index) )
{ }
// ctor a const_iterator from an iterator
const_cppad_vector_itr(
const cppad_vector_itr<Type>& non_const_other
) CPPAD_NOEXCEPT
{ data_ = non_const_other.data_;
length_ = non_const_other.length_;
index_ = non_const_other.index_;
}
# else
cppad_vector_itr(
Type* const* data, const size_t* length, difference_type index
) CPPAD_NOEXCEPT
: data_(data), length_(length), index_( difference_type(index) )
{ }
# endif
void operator=(const CPPAD_VECTOR_ITR& other) CPPAD_NOEXCEPT
{ data_ = other.data_;
length_ = other.length_;
index_ = other.index_;
}
CPPAD_VECTOR_ITR(const CPPAD_VECTOR_ITR& other) CPPAD_NOEXCEPT
{ *this = other; }
/* %$$
$end
-------------------------------------------------------------------------------
$begin cppad_vector_itr_inc$$
$spell
Iterator
itr
$$
$section Vector Class Iterator Increment Operators$$
$head Syntax$$
$codei%++%itr%
%$$
$codei%--%itr%
%$$
$icode%itr%++
%$$
$icode%itr%--
%$$
$head Source$$
$srccode%hpp% */
public:
CPPAD_VECTOR_ITR& operator++(void) CPPAD_NOEXCEPT
{ ++index_;
return *this;
}
CPPAD_VECTOR_ITR& operator--(void) CPPAD_NOEXCEPT
{ --index_;
return *this;
}
CPPAD_VECTOR_ITR operator++(int) CPPAD_NOEXCEPT
{ CPPAD_VECTOR_ITR ret(*this);
++index_;
return ret;
}
CPPAD_VECTOR_ITR operator--(int) CPPAD_NOEXCEPT
{ CPPAD_VECTOR_ITR ret(*this);
--index_;
return ret;
}
/* %$$
$end
-------------------------------------------------------------------------------
$begin cppad_vector_itr_equal$$
$spell
itr
Iterator
$$
$section Vector Class Iterator Equality Operators$$
$spell
iterators
$$
$head Syntax$$
$icode%itr% == %other%
%$$
$icode%itr% != %other%
%$$
$head Restrictions$$
It is an error to compare iterators corresponding to different
$code data_$$ vectors
$head Source$$
$srccode%hpp% */
public:
bool operator==(const CPPAD_VECTOR_ITR& other) const CPPAD_NDEBUG_NOEXCEPT
{ check_cop(other);
return index_ == other.index_;
}
bool operator!=(const CPPAD_VECTOR_ITR& other) const CPPAD_NDEBUG_NOEXCEPT
{ check_cop(other);
return index_ != other.index_;
}
/* %$$
$end
-------------------------------------------------------------------------------
$begin cppad_vector_itr_element$$
$spell
itr
Iterator
$$
$section Vector Class Iterator Access Elements$$
$head Syntax$$
$icode%element% = *%itr%
%$$
$codei%*%itr% = %element%
%$$
$head Source$$
$srccode%hpp% */
public:
const Type& operator*(void) const
{ check_element();
return (*data_)[index_];
}
# if ! CPPAD_CONST
Type& operator*(void)
{ check_element();
return (*data_)[index_];
}
# endif
/* %$$
$end
-------------------------------------------------------------------------------
$begin cppad_vector_itr_random$$
$spell
itr
Iterator
bool
iterators
$$
$section Vector Class Iterator Random Access$$
$head Syntax$$
$icode%element% = %itr%[%n%]
%$$
$icode%itr%[%n%] = %element%
%$$
$icode%itr% %+-% = %n%
%$$
$icode%itr% = %other% %+-% %n%
%$$
$icode%itr% = %n% %+-% %other%
%$$
$icode%n% = %itr% - %other%
%$$
$code%b% = %itr% %cop% %other%
%$$
$subhead +-$$
The notation $icode +-$$ above is either $code +$$ or $code -$$.
$subhead cop$$
is one of the following:
$code <$$, $code <=$$,
$code >$$, $code >=$$.
$head itr, other$$
are iterators of the same type.
$head n$$
is a $code difference_type$$ object.
$head b$$
is a $code bool$$.
$head Restrictions$$
It is an error to use a $icode cop$$ with iterators corresponding to different
$code data_$$ vectors
$head Source$$
$srccode%hpp% */
public:
CPPAD_VECTOR_ITR operator[](difference_type n)
{ return *(*this + n);
}
// sum and difference operators
CPPAD_VECTOR_ITR& operator+=(difference_type n) CPPAD_NOEXCEPT
{ index_ += n;
return *this;
}
CPPAD_VECTOR_ITR& operator-=(difference_type n) CPPAD_NOEXCEPT
{ index_ -= n;
return *this;
}
CPPAD_VECTOR_ITR operator+(difference_type n) const CPPAD_NOEXCEPT
{ return CPPAD_VECTOR_ITR(data_, length_, index_ + n);
}
CPPAD_VECTOR_ITR operator-(difference_type n) const CPPAD_NOEXCEPT
{ return CPPAD_VECTOR_ITR(data_, length_, index_ - n);
}
difference_type operator-(const CPPAD_VECTOR_ITR& other) const
CPPAD_NOEXCEPT
{ return index_ - other.index_;
}
// comparison operators
bool operator<(const CPPAD_VECTOR_ITR& other) const CPPAD_NDEBUG_NOEXCEPT
{ check_cop(other);
return index_ < other.index_;
}
bool operator<=(const CPPAD_VECTOR_ITR& other) const CPPAD_NDEBUG_NOEXCEPT
{ check_cop(other);
return index_ <= other.index_;
}
bool operator>(const CPPAD_VECTOR_ITR& other) const CPPAD_NDEBUG_NOEXCEPT
{ check_cop(other);
return index_ > other.index_;
}
bool operator>=(const CPPAD_VECTOR_ITR& other) const CPPAD_NDEBUG_NOEXCEPT
{ check_cop(other);
return index_ >= other.index_;
}
/* %$$
$srcfile%include/cppad/local/utility/cppad_vector_itr.hpp%
0%// BEGIN_BINARY_OP%// END_BINARY_OP%1
%$$
$end
*/
// ==========================================================================
}; // END_TEMPLATE_CLASS_CPPAD_VECTOR_ITR
// ==========================================================================
// BEGIN_BINARY_OP
template <class Type> CPPAD_VECTOR_ITR<Type> operator+(
typename CPPAD_VECTOR_ITR<Type>::difference_type n ,
const CPPAD_VECTOR_ITR<Type>& other ) CPPAD_NOEXCEPT
{ return
CPPAD_VECTOR_ITR<Type>(other.data_, other.length_, n + other.index_ );
}
template <class Type> CPPAD_VECTOR_ITR<Type> operator-(
typename CPPAD_VECTOR_ITR<Type>::difference_type n ,
const CPPAD_VECTOR_ITR<Type>& other ) CPPAD_NOEXCEPT
{ return
CPPAD_VECTOR_ITR<Type>(other.data_, other.length_, n - other.index_ );
}
// END_BINARY_OP
} } } // END_CPPAD_LOCAL_UTILITY_NAMESPACE
# undef CPPAD_CONST
# undef CPPAD_VECTOR_ITR
# endif
| [
"Johannes.Pankert@mavt.ethz.ch"
] | Johannes.Pankert@mavt.ethz.ch |
21d738535fda3ad6cc8e506458752856a96fa56f | 1d9b1b78887bdff6dd5342807c4ee20f504a2a75 | /lib/libcxx/include/stdio.h | ad1b4c05f1fa42001f1080274ff376ce7e7da003 | [
"LLVM-exception",
"Apache-2.0",
"MIT",
"LicenseRef-scancode-other-permissive",
"NCSA"
] | permissive | mikdusan/zig | 86831722d86f518d1734ee5a1ca89d3ffe9555e8 | b2ffe113d3fd2835b25ddf2de1cc8dd49f5de722 | refs/heads/master | 2023-08-31T21:29:04.425401 | 2022-11-13T15:43:29 | 2022-11-13T15:43:29 | 173,955,807 | 1 | 0 | MIT | 2021-11-02T03:19:36 | 2019-03-05T13:52:53 | Zig | UTF-8 | C++ | false | false | 3,524 | h | // -*- C++ -*-
//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#if defined(__need_FILE) || defined(__need___FILE)
#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
# pragma GCC system_header
#endif
#include_next <stdio.h>
#elif !defined(_LIBCPP_STDIO_H)
#define _LIBCPP_STDIO_H
/*
stdio.h synopsis
Macros:
BUFSIZ
EOF
FILENAME_MAX
FOPEN_MAX
L_tmpnam
NULL
SEEK_CUR
SEEK_END
SEEK_SET
TMP_MAX
_IOFBF
_IOLBF
_IONBF
stderr
stdin
stdout
Types:
FILE
fpos_t
size_t
int remove(const char* filename);
int rename(const char* old, const char* new);
FILE* tmpfile(void);
char* tmpnam(char* s);
int fclose(FILE* stream);
int fflush(FILE* stream);
FILE* fopen(const char* restrict filename, const char* restrict mode);
FILE* freopen(const char* restrict filename, const char * restrict mode,
FILE * restrict stream);
void setbuf(FILE* restrict stream, char* restrict buf);
int setvbuf(FILE* restrict stream, char* restrict buf, int mode, size_t size);
int fprintf(FILE* restrict stream, const char* restrict format, ...);
int fscanf(FILE* restrict stream, const char * restrict format, ...);
int printf(const char* restrict format, ...);
int scanf(const char* restrict format, ...);
int snprintf(char* restrict s, size_t n, const char* restrict format, ...); // C99
int sprintf(char* restrict s, const char* restrict format, ...);
int sscanf(const char* restrict s, const char* restrict format, ...);
int vfprintf(FILE* restrict stream, const char* restrict format, va_list arg);
int vfscanf(FILE* restrict stream, const char* restrict format, va_list arg); // C99
int vprintf(const char* restrict format, va_list arg);
int vscanf(const char* restrict format, va_list arg); // C99
int vsnprintf(char* restrict s, size_t n, const char* restrict format, // C99
va_list arg);
int vsprintf(char* restrict s, const char* restrict format, va_list arg);
int vsscanf(const char* restrict s, const char* restrict format, va_list arg); // C99
int fgetc(FILE* stream);
char* fgets(char* restrict s, int n, FILE* restrict stream);
int fputc(int c, FILE* stream);
int fputs(const char* restrict s, FILE* restrict stream);
int getc(FILE* stream);
int getchar(void);
char* gets(char* s); // removed in C++14
int putc(int c, FILE* stream);
int putchar(int c);
int puts(const char* s);
int ungetc(int c, FILE* stream);
size_t fread(void* restrict ptr, size_t size, size_t nmemb,
FILE* restrict stream);
size_t fwrite(const void* restrict ptr, size_t size, size_t nmemb,
FILE* restrict stream);
int fgetpos(FILE* restrict stream, fpos_t* restrict pos);
int fseek(FILE* stream, long offset, int whence);
int fsetpos(FILE*stream, const fpos_t* pos);
long ftell(FILE* stream);
void rewind(FILE* stream);
void clearerr(FILE* stream);
int feof(FILE* stream);
int ferror(FILE* stream);
void perror(const char* s);
*/
#include <__config>
#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
# pragma GCC system_header
#endif
#include_next <stdio.h>
#ifdef __cplusplus
#undef getc
#undef putc
#undef clearerr
#undef feof
#undef ferror
#endif
#endif // _LIBCPP_STDIO_H
| [
"andrew@ziglang.org"
] | andrew@ziglang.org |
5423e4f8d4d190ea4b136a3a0273ef7e54712d32 | ab98581b2cda55e55c855d0c8089cfe03a264f1d | /thrift/lib/cpp2/transport/core/testutil/TransportCompatibilityTest.cpp | 909186ec8a1ffb1162d1f4faa3098a1094a83a49 | [
"Apache-2.0"
] | permissive | malmerey/fbthrift | ceb4ac8e4c8ac97534e072f043d283ba121e3778 | 2984cccced9aa5f430598974b6256fcca73e500a | refs/heads/master | 2020-06-12T01:11:47.779381 | 2019-06-27T16:49:45 | 2019-06-27T16:53:04 | 194,147,059 | 0 | 0 | Apache-2.0 | 2019-06-27T18:48:31 | 2019-06-27T18:48:30 | null | UTF-8 | C++ | false | false | 39,806 | cpp | /*
* Copyright 2017-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <folly/Conv.h>
#include <folly/portability/GFlags.h>
#include <folly/portability/GTest.h>
#include <glog/logging.h>
#include <folly/ScopeGuard.h>
#include <folly/io/async/EventBase.h>
#include <folly/io/async/ScopedEventBaseThread.h>
#include <folly/synchronization/Baton.h>
#include <thrift/lib/cpp/async/TAsyncSSLSocket.h>
#include <thrift/lib/cpp/async/TAsyncSocket.h>
#include <thrift/lib/cpp/async/TAsyncTransport.h>
#include <thrift/lib/cpp/transport/THeader.h>
#include <thrift/lib/cpp2/async/HTTPClientChannel.h>
#include <thrift/lib/cpp2/async/HeaderClientChannel.h>
#include <thrift/lib/cpp2/async/PooledRequestChannel.h>
#include <thrift/lib/cpp2/async/RSocketClientChannel.h>
#include <thrift/lib/cpp2/async/RocketClientChannel.h>
#include <thrift/lib/cpp2/transport/core/ThriftClient.h>
#include <thrift/lib/cpp2/transport/core/ThriftClientCallback.h>
#include <thrift/lib/cpp2/transport/core/testutil/MockCallback.h>
#include <thrift/lib/cpp2/transport/core/testutil/TAsyncSocketIntercepted.h>
#include <thrift/lib/cpp2/transport/core/testutil/TransportCompatibilityTest.h>
#include <thrift/lib/cpp2/transport/core/testutil/gen-cpp2/TestService.h>
#include <thrift/lib/cpp2/transport/util/ConnectionManager.h>
DECLARE_bool(use_ssl);
DECLARE_string(transport);
DEFINE_string(host, "::1", "host to connect to");
namespace apache {
namespace thrift {
using namespace async;
using namespace testing;
using namespace apache::thrift;
using namespace apache::thrift::transport;
using namespace testutil::testservice;
TransportCompatibilityTest::TransportCompatibilityTest()
: handler_(std::make_shared<
StrictMock<testutil::testservice::TestServiceMock>>()),
server_(std::make_unique<
SampleServer<testutil::testservice::TestServiceMock>>(handler_)) {
}
template <typename Service>
SampleServer<Service>::SampleServer(std::shared_ptr<Service> handler)
: handler_(std::move(handler)) {
setupServer();
}
// Tears down after the test.
template <typename Service>
SampleServer<Service>::~SampleServer() {
stopServer();
}
// Event handler to attach to the Thrift server so we know when it is
// ready to serve and also so we can determine the port it is
// listening on.
class TransportCompatibilityTestEventHandler
: public server::TServerEventHandler {
public:
// This is a callback that is called when the Thrift server has
// initialized and is ready to serve RPCs.
void preServe(const folly::SocketAddress* address) override {
port_ = address->getPort();
baton_.post();
}
int32_t waitForPortAssignment() {
baton_.wait();
return port_;
}
private:
folly::Baton<> baton_;
int32_t port_;
};
template <typename Service>
void SampleServer<Service>::addRoutingHandler(
std::unique_ptr<TransportRoutingHandler> routingHandler) {
DCHECK(server_) << "First call setupServer() function";
server_->addRoutingHandler(std::move(routingHandler));
}
template <typename Service>
ThriftServer* SampleServer<Service>::getServer() {
DCHECK(server_) << "First call setupServer() function";
return server_.get();
}
void TransportCompatibilityTest::addRoutingHandler(
std::unique_ptr<TransportRoutingHandler> routingHandler) {
return server_->addRoutingHandler(std::move(routingHandler));
}
ThriftServer* TransportCompatibilityTest::getServer() {
return server_->getServer();
}
template <typename Service>
void SampleServer<Service>::setupServer() {
DCHECK(!server_) << "First close the server with stopServer()";
auto cpp2PFac =
std::make_shared<ThriftServerAsyncProcessorFactory<Service>>(handler_);
server_ = std::make_unique<ThriftServer>();
observer_ = std::make_shared<FakeServerObserver>();
server_->setObserver(observer_);
server_->setPort(0);
server_->setNumIOWorkerThreads(numIOThreads_);
server_->setNumCPUWorkerThreads(numWorkerThreads_);
server_->setProcessorFactory(cpp2PFac);
server_->setGetLoad([](const auto& counter) {
if (counter == THeader::QUERY_LOAD_HEADER) {
return 123;
}
return -1;
});
}
template <typename Service>
void SampleServer<Service>::startServer() {
DCHECK(server_) << "First call setupServer() function";
auto eventHandler =
std::make_shared<TransportCompatibilityTestEventHandler>();
server_->setServerEventHandler(eventHandler);
server_->setup();
// Get the port that the server has bound to
port_ = eventHandler->waitForPortAssignment();
}
void TransportCompatibilityTest::startServer() {
server_->startServer();
}
template <typename Service>
void SampleServer<Service>::stopServer() {
if (server_) {
server_->cleanUp();
server_.reset();
handler_.reset();
}
}
void TransportCompatibilityTest::connectToServer(
folly::Function<void(std::unique_ptr<TestServiceAsyncClient>)> callMe) {
connectToServer([callMe = std::move(callMe)](
std::unique_ptr<TestServiceAsyncClient> client,
auto) mutable { callMe(std::move(client)); });
}
void TransportCompatibilityTest::connectToServer(
folly::Function<void(
std::unique_ptr<TestServiceAsyncClient>,
std::shared_ptr<ClientConnectionIf>)> callMe) {
server_->connectToServer(
FLAGS_transport,
[callMe = std::move(callMe)](
std::shared_ptr<RequestChannel> channel,
std::shared_ptr<ClientConnectionIf> connection) mutable {
auto client =
std::make_unique<TestServiceAsyncClient>(std::move(channel));
callMe(std::move(client), std::move(connection));
});
}
template <typename Service>
void SampleServer<Service>::connectToServer(
std::string transport,
folly::Function<void(
std::shared_ptr<RequestChannel>,
std::shared_ptr<ClientConnectionIf>)> callMe) {
ASSERT_GT(port_, 0) << "Check if the server has started already";
if (transport == "header") {
auto addr = folly::SocketAddress(FLAGS_host, port_);
TAsyncSocket::UniquePtr sock(new TAsyncSocketIntercepted(
folly::EventBaseManager::get()->getEventBase(), addr));
auto chan = HeaderClientChannel::newChannel(std::move(sock));
chan->setProtocolId(apache::thrift::protocol::T_COMPACT_PROTOCOL);
callMe(std::move(chan), nullptr);
} else if (transport == "rsocket") {
std::shared_ptr<RSocketClientChannel> channel;
evbThread_.getEventBase()->runInEventBaseThreadAndWait([&]() {
channel = RSocketClientChannel::newChannel(
TAsyncSocket::UniquePtr(new TAsyncSocketIntercepted(
evbThread_.getEventBase(), FLAGS_host, port_)));
});
auto channelPtr = channel.get();
std::shared_ptr<RSocketClientChannel> destroyInEvbChannel(
channelPtr,
[channel_ = std::move(channel),
eventBase = evbThread_.getEventBase()](RSocketClientChannel*) mutable {
eventBase->runImmediatelyOrRunInEventBaseThreadAndWait(
[channel__ = std::move(channel_)] {});
});
callMe(std::move(destroyInEvbChannel), nullptr);
} else if (transport == "rocket") {
std::shared_ptr<RocketClientChannel> channel;
evbThread_.getEventBase()->runInEventBaseThreadAndWait([&]() {
channel = RocketClientChannel::newChannel(
TAsyncSocket::UniquePtr(new TAsyncSocketIntercepted(
evbThread_.getEventBase(), FLAGS_host, port_)));
});
auto channelPtr = channel.get();
std::shared_ptr<RocketClientChannel> destroyInEvbChannel(
channelPtr,
[channel_ = std::move(channel),
eventBase = evbThread_.getEventBase()](RocketClientChannel*) mutable {
eventBase->runImmediatelyOrRunInEventBaseThreadAndWait(
[channel__ = std::move(channel_)] {});
});
callMe(std::move(destroyInEvbChannel), nullptr);
} else if (transport == "legacy-http2") {
// We setup legacy http2 for synchronous calls only - we do not
// drive this event base.
auto executor = std::make_shared<folly::ScopedEventBaseThread>();
auto eventBase = executor->getEventBase();
auto channel = PooledRequestChannel::newChannel(
eventBase, executor, [port = std::move(port_)](folly::EventBase& evb) {
TAsyncSocket::UniquePtr socket(
new TAsyncSocketIntercepted(&evb, FLAGS_host, port));
if (FLAGS_use_ssl) {
auto sslContext = std::make_shared<folly::SSLContext>();
sslContext->setAdvertisedNextProtocols({"h2", "http"});
auto sslSocket = new TAsyncSSLSocket(
sslContext, &evb, socket->detachNetworkSocket().toFd(), false);
sslSocket->sslConn(nullptr);
socket.reset(sslSocket);
}
return HTTPClientChannel::newHTTP2Channel(std::move(socket));
});
callMe(std::move(channel), nullptr);
} else {
auto mgr = ConnectionManager::getInstance();
auto connection = mgr->getConnection(FLAGS_host, port_);
auto channel = ThriftClient::Ptr(new ThriftClient(connection));
channel->setProtocolId(apache::thrift::protocol::T_COMPACT_PROTOCOL);
callMe(std::move(channel), std::move(connection));
}
}
void TransportCompatibilityTest::callSleep(
TestServiceAsyncClient* client,
int32_t timeoutMs,
int32_t sleepMs) {
auto cb = std::make_unique<MockCallback>(false, timeoutMs < sleepMs);
RpcOptions opts;
opts.setTimeout(std::chrono::milliseconds(timeoutMs));
opts.setQueueTimeout(std::chrono::milliseconds(5000));
client->sleep(opts, std::move(cb), sleepMs);
}
void TransportCompatibilityTest::TestConnectionStats() {
connectToServer([this](std::unique_ptr<TestServiceAsyncClient> client) {
EXPECT_EQ(0, server_->observer_->connAccepted_);
EXPECT_EQ(0, server_->observer_->activeConns_);
EXPECT_CALL(*handler_.get(), sumTwoNumbers_(1, 2)).Times(1);
EXPECT_EQ(3, client->future_sumTwoNumbers(1, 2).get());
EXPECT_EQ(1, server_->observer_->connAccepted_);
EXPECT_EQ(server_->numIOThreads_, server_->observer_->activeConns_);
});
}
void TransportCompatibilityTest::TestObserverSendReceiveRequests() {
connectToServer([this](std::unique_ptr<TestServiceAsyncClient> client) {
EXPECT_CALL(*handler_.get(), sumTwoNumbers_(1, 2)).Times(2);
EXPECT_CALL(*handler_.get(), add_(1));
EXPECT_CALL(*handler_.get(), add_(2));
EXPECT_CALL(*handler_.get(), add_(5));
// Send a message
EXPECT_EQ(3, client->future_sumTwoNumbers(1, 2).get());
EXPECT_EQ(1, client->future_add(1).get());
auto future = client->future_add(2);
EXPECT_EQ(3, std::move(future).get());
EXPECT_EQ(3, client->future_sumTwoNumbers(1, 2).get());
EXPECT_EQ(8, client->future_add(5).get());
// Now check the stats
EXPECT_EQ(5, server_->observer_->sentReply_);
EXPECT_EQ(5, server_->observer_->receivedRequest_);
});
}
void TransportCompatibilityTest::TestConnectionContext() {
connectToServer([this](std::unique_ptr<TestServiceAsyncClient> client) {
auto channel = dynamic_cast<ClientChannel*>(client->getChannel());
int32_t port{0};
channel->getEventBase()->runInEventBaseThreadAndWait([&] {
auto socket = dynamic_cast<TAsyncSocket*>(channel->getTransport());
folly::SocketAddress localAddress;
socket->getLocalAddress(&localAddress);
port = localAddress.getPort();
});
EXPECT_NE(0, port);
EXPECT_CALL(*handler_.get(), checkPort_(port));
client->future_checkPort(port).get();
});
}
void TransportCompatibilityTest::TestClientIdentityHook() {
bool flag{false};
auto hook = [&flag](
const folly::AsyncTransportWrapper* /* unused */,
const X509* /* unused */,
const folly::SocketAddress& /* unused */) {
flag = true;
return std::unique_ptr<void, void (*)(void*)>(nullptr, [](void*) {});
};
server_->getServer()->setClientIdentityHook(std::move(hook));
connectToServer([&](std::unique_ptr<TestServiceAsyncClient> client) {
EXPECT_CALL(*handler_.get(), sumTwoNumbers_(1, 2));
EXPECT_EQ(3, client->future_sumTwoNumbers(1, 2).get());
EXPECT_TRUE(flag);
});
}
void TransportCompatibilityTest::TestRequestResponse_Simple() {
connectToServer([this](std::unique_ptr<TestServiceAsyncClient> client) {
EXPECT_CALL(*handler_.get(), sumTwoNumbers_(1, 2)).Times(2);
EXPECT_CALL(*handler_.get(), add_(1));
EXPECT_CALL(*handler_.get(), add_(2));
EXPECT_CALL(*handler_.get(), add_(5));
// Send a message
EXPECT_EQ(3, client->future_sumTwoNumbers(1, 2).get());
EXPECT_EQ(1, client->future_add(1).get());
auto future = client->future_add(2);
EXPECT_EQ(3, std::move(future).get());
EXPECT_EQ(3, client->future_sumTwoNumbers(1, 2).get());
EXPECT_EQ(8, client->future_add(5).get());
});
}
void TransportCompatibilityTest::TestRequestResponse_Sync() {
connectToServer([this](std::unique_ptr<TestServiceAsyncClient> client) {
EXPECT_CALL(*handler_.get(), sumTwoNumbers_(1, 2)).Times(2);
EXPECT_CALL(*handler_.get(), add_(1));
EXPECT_CALL(*handler_.get(), add_(2));
EXPECT_CALL(*handler_.get(), add_(5));
// Send a message
EXPECT_EQ(3, client->future_sumTwoNumbers(1, 2).get());
EXPECT_EQ(1, client->future_add(1).get());
EXPECT_EQ(3, client->future_add(2).get());
EXPECT_EQ(3, client->future_sumTwoNumbers(1, 2).get());
EXPECT_EQ(8, client->future_add(5).get());
});
}
void TransportCompatibilityTest::TestRequestResponse_Destruction() {
connectToServer([](std::unique_ptr<TestServiceAsyncClient> client) {
auto future =
client->future_sleep(100).thenTry([&](folly::Try<folly::Unit> t) {
client.reset();
EXPECT_TRUE(t.hasException());
});
auto channel = static_cast<ClientChannel*>(client->getChannel());
channel->getEventBase()->runInEventBaseThreadAndWait(
[&]() { channel->getTransport()->closeNow(); });
std::move(future).get();
});
}
void TransportCompatibilityTest::TestRequestResponse_MultipleClients() {
const int clientCount = 10;
EXPECT_CALL(*handler_.get(), sumTwoNumbers_(1, 2)).Times(2 * clientCount);
EXPECT_CALL(*handler_.get(), add_(1)).Times(clientCount);
EXPECT_CALL(*handler_.get(), add_(2)).Times(clientCount);
EXPECT_CALL(*handler_.get(), add_(5)).Times(clientCount);
auto lambda = [](std::unique_ptr<TestServiceAsyncClient> client) {
// Send a message
EXPECT_EQ(3, client->future_sumTwoNumbers(1, 2).get());
EXPECT_LE(1, client->future_add(1).get());
auto future = client->future_add(2);
EXPECT_LE(3, std::move(future).get());
EXPECT_EQ(3, client->future_sumTwoNumbers(1, 2).get());
EXPECT_LE(8, client->future_add(5).get());
};
std::vector<folly::ScopedEventBaseThread> threads(clientCount);
std::vector<folly::Promise<folly::Unit>> promises(clientCount);
std::vector<folly::Future<folly::Unit>> futures;
for (int i = 0; i < clientCount; ++i) {
auto& promise = promises[i];
futures.emplace_back(promise.getFuture());
threads[i].getEventBase()->runInEventBaseThread([&promise, lambda, this]() {
connectToServer(lambda);
promise.setValue();
});
}
folly::collectAllSemiFuture(futures).get();
threads.clear();
}
void TransportCompatibilityTest::TestRequestResponse_ExpectedException() {
EXPECT_THROW(
connectToServer(
[&](auto client) { client->future_throwExpectedException(1).get(); }),
TestServiceException);
EXPECT_THROW(
connectToServer(
[&](auto client) { client->future_throwExpectedException(1).get(); }),
TestServiceException);
}
void TransportCompatibilityTest::TestRequestResponse_UnexpectedException() {
EXPECT_THROW(
connectToServer([&](auto client) {
client->future_throwUnexpectedException(2).get();
}),
apache::thrift::TApplicationException);
EXPECT_THROW(
connectToServer([&](auto client) {
client->future_throwUnexpectedException(2).get();
}),
apache::thrift::TApplicationException);
}
void TransportCompatibilityTest::TestRequestResponse_Timeout() {
connectToServer([this](std::unique_ptr<TestServiceAsyncClient> client) {
// These are all async calls. The first batch of calls get
// dispatched immediately, then there is a sleep, and then the
// second batch of calls get dispatched. All calls have separate
// timeouts and different delays on the server side.
callSleep(client.get(), 1, 100);
callSleep(client.get(), 100, 0);
callSleep(client.get(), 1, 100);
callSleep(client.get(), 100, 0);
callSleep(client.get(), 2000, 500);
/* sleep override */
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
callSleep(client.get(), 100, 1000);
callSleep(client.get(), 200, 0);
/* Sleep to give time for all callbacks to be completed */
/* sleep override */
std::this_thread::sleep_for(std::chrono::milliseconds(2000));
EXPECT_EQ(3, server_->observer_->taskTimeout_);
EXPECT_EQ(0, server_->observer_->queueTimeout_);
});
}
void TransportCompatibilityTest::TestRequestResponse_Header() {
connectToServer([](std::unique_ptr<TestServiceAsyncClient> client) {
{ // Future
apache::thrift::RpcOptions rpcOptions;
rpcOptions.setWriteHeader("header_from_client", "2");
auto future = client->header_future_headers(rpcOptions);
auto tHeader = std::move(future).get().second;
auto keyValue = tHeader->getHeaders();
EXPECT_NE(keyValue.end(), keyValue.find("header_from_server"));
EXPECT_STREQ("1", keyValue.find("header_from_server")->second.c_str());
}
{ // Callback
apache::thrift::RpcOptions rpcOptions;
rpcOptions.setWriteHeader("header_from_client", "2");
folly::Promise<folly::Unit> executed;
auto future = executed.getFuture();
client->headers(
rpcOptions,
std::unique_ptr<RequestCallback>(
new FunctionReplyCallback([&](ClientReceiveState&& state) {
auto keyValue = state.header()->getHeaders();
EXPECT_NE(keyValue.end(), keyValue.find("header_from_server"));
EXPECT_STREQ(
"1", keyValue.find("header_from_server")->second.c_str());
auto exw = TestServiceAsyncClient::recv_wrapped_headers(state);
EXPECT_FALSE(exw);
executed.setValue();
})));
auto& waited = future.wait(folly::Duration(100));
EXPECT_TRUE(waited.isReady());
}
});
}
void TransportCompatibilityTest::TestRequestResponse_Header_Load() {
connectToServer([](std::unique_ptr<TestServiceAsyncClient> client) {
RpcOptions rpcOptions;
rpcOptions.setWriteHeader("header_from_client", "2");
rpcOptions.setWriteHeader(THeader::QUERY_LOAD_HEADER, {});
auto resultAndHeaders = client->header_future_headers(rpcOptions).get();
const auto readHeaders =
std::move(resultAndHeaders.second)->releaseHeaders();
EXPECT_NE(readHeaders.end(), readHeaders.find("header_from_server"));
const auto loadIt = readHeaders.find(THeader::QUERY_LOAD_HEADER);
ASSERT_NE(readHeaders.end(), loadIt);
EXPECT_EQ(123, folly::to<int64_t>(loadIt->second));
});
}
void TransportCompatibilityTest::
TestRequestResponse_Header_ExpectedException() {
connectToServer([](std::unique_ptr<TestServiceAsyncClient> client) {
{ // Future
apache::thrift::RpcOptions rpcOptions;
rpcOptions.setWriteHeader("header_from_client", "2");
rpcOptions.setWriteHeader("expected_exception", "1");
auto future = client->header_future_headers(rpcOptions);
auto& waited = future.wait();
auto& ftry = waited.getTry();
EXPECT_TRUE(ftry.hasException());
EXPECT_THAT(
ftry.tryGetExceptionObject()->what(),
HasSubstr("TestServiceException"));
}
{ // Callback
apache::thrift::RpcOptions rpcOptions;
rpcOptions.setWriteHeader("header_from_client", "2");
rpcOptions.setWriteHeader("expected_exception", "1");
folly::Promise<folly::Unit> executed;
auto future = executed.getFuture();
client->headers(
rpcOptions,
std::unique_ptr<RequestCallback>(
new FunctionReplyCallback([&](ClientReceiveState&& state) {
auto exw = TestServiceAsyncClient::recv_wrapped_headers(state);
EXPECT_TRUE(exw.get_exception());
EXPECT_THAT(
exw.what().c_str(), HasSubstr("TestServiceException"));
executed.setValue();
})));
auto& waited = future.wait(folly::Duration(100));
ASSERT_TRUE(waited.isReady());
}
});
}
void TransportCompatibilityTest::
TestRequestResponse_Header_UnexpectedException() {
connectToServer([](std::unique_ptr<TestServiceAsyncClient> client) {
{ // Future
apache::thrift::RpcOptions rpcOptions;
rpcOptions.setWriteHeader("header_from_client", "2");
rpcOptions.setWriteHeader("unexpected_exception", "1");
auto future = client->header_future_headers(rpcOptions);
EXPECT_THROW(
std::move(future).get(), apache::thrift::TApplicationException);
}
{ // Callback
apache::thrift::RpcOptions rpcOptions;
rpcOptions.setWriteHeader("header_from_client", "2");
rpcOptions.setWriteHeader("unexpected_exception", "1");
folly::Promise<folly::Unit> executed;
auto future = executed.getFuture();
client->headers(
rpcOptions,
std::unique_ptr<RequestCallback>(
new FunctionReplyCallback([&](ClientReceiveState&& state) {
auto exw = TestServiceAsyncClient::recv_wrapped_headers(state);
EXPECT_TRUE(exw.get_exception());
EXPECT_THAT(
exw.what().c_str(), HasSubstr("TApplicationException"));
executed.setValue();
})));
auto& waited = future.wait(folly::Duration(100));
EXPECT_TRUE(waited.isReady());
}
});
}
void TransportCompatibilityTest::TestRequestResponse_Saturation() {
connectToServer([this](auto client, auto connection) {
EXPECT_CALL(*handler_.get(), add_(3)).Times(2);
// note that no EXPECT_CALL for add_(5)
connection->getEventBase()->runInEventBaseThreadAndWait(
[&]() { connection->setMaxPendingRequests(0u); });
EXPECT_THROW(client->semifuture_add(5).get(), TTransportException);
connection->getEventBase()->runInEventBaseThreadAndWait(
[&]() { connection->setMaxPendingRequests(1u); });
EXPECT_EQ(3, client->semifuture_add(3).get());
EXPECT_EQ(6, client->semifuture_add(3).get());
});
}
void TransportCompatibilityTest::TestRequestResponse_Connection_CloseNow() {
connectToServer([](std::unique_ptr<TestServiceAsyncClient> client) {
// It should not reach to server: no EXPECT_CALL for add_(3)
// Observe the behavior if the connection is closed already
auto channel = static_cast<ClientChannel*>(client->getChannel());
channel->getEventBase()->runInEventBaseThreadAndWait(
[&]() { channel->closeNow(); });
try {
client->future_add(3).get();
EXPECT_TRUE(false) << "future_add should have thrown";
} catch (TTransportException& ex) {
EXPECT_EQ(TTransportException::NOT_OPEN, ex.getType());
}
});
}
void TransportCompatibilityTest::TestRequestResponse_ServerQueueTimeout() {
connectToServer([this](
std::unique_ptr<TestServiceAsyncClient> client) mutable {
int32_t numCores = sysconf(_SC_NPROCESSORS_ONLN);
int callCount = numCores + 1; // more than the core count!
// Queue expiration - executes some of the tasks ( = thread count)
server_->getServer()->setQueueTimeout(std::chrono::milliseconds(10));
server_->getServer()->setTaskExpireTime(std::chrono::milliseconds(10));
std::vector<folly::Future<folly::Unit>> futures(callCount);
for (int i = 0; i < callCount; ++i) {
RpcOptions opts;
opts.setTimeout(std::chrono::milliseconds(10));
futures[i] = client->future_sleep(100);
}
int taskTimeoutCount = 0;
int successCount = 0;
for (auto& future : futures) {
auto& waitedFuture = future.wait();
auto& triedFuture = waitedFuture.getTry();
if (triedFuture.withException([](TApplicationException& ex) {
EXPECT_EQ(
TApplicationException::TApplicationExceptionType::TIMEOUT,
ex.getType());
})) {
++taskTimeoutCount;
} else {
ASSERT_FALSE(triedFuture.hasException());
++successCount;
}
}
EXPECT_LE(1, taskTimeoutCount) << "at least 1 task is expected to timeout";
EXPECT_LE(1, successCount) << "at least 1 task is expected to succeed";
// Task expires - even though starts executing the tasks, all expires
server_->getServer()->setQueueTimeout(std::chrono::milliseconds(1000));
server_->getServer()->setUseClientTimeout(false);
server_->getServer()->setTaskExpireTime(std::chrono::milliseconds(1));
for (int i = 0; i < callCount; ++i) {
futures[i] = client->future_sleep(100 + i);
}
taskTimeoutCount = 0;
for (auto& future : futures) {
auto& waitedFuture = future.wait();
auto& triedFuture = waitedFuture.getTry();
if (triedFuture.withException([](TApplicationException& ex) {
EXPECT_EQ(
TApplicationException::TApplicationExceptionType::TIMEOUT,
ex.getType());
})) {
++taskTimeoutCount;
} else {
ASSERT_FALSE(triedFuture.hasException());
}
}
EXPECT_EQ(callCount, taskTimeoutCount)
<< "all tasks are expected to be timed out";
});
}
void TransportCompatibilityTest::TestRequestResponse_ResponseSizeTooBig() {
connectToServer([this](std::unique_ptr<TestServiceAsyncClient> client) {
// Execute the function, but fail when sending the response
EXPECT_CALL(*handler_.get(), hello_(_));
server_->getServer()->setMaxResponseSize(1);
try {
std::string longName(1, 'f');
auto result = client->future_hello(longName).get();
EXPECT_TRUE(false) << "future_hello should have thrown";
} catch (TApplicationException& ex) {
EXPECT_EQ(TApplicationException::INTERNAL_ERROR, ex.getType());
}
});
}
void TransportCompatibilityTest::TestRequestResponse_Checksumming() {
connectToServer([this](std::unique_ptr<TestServiceAsyncClient> client) {
enum class CorruptionType : int {
NONE = 0,
REQUESTS = 1,
RESPONSES = 2,
};
EXPECT_CALL(*handler_.get(), echo_(_)).Times(2);
auto setCorruption = [&](CorruptionType corruptionType) {
auto channel = static_cast<ClientChannel*>(client->getChannel());
channel->getEventBase()->runInEventBaseThreadAndWait([&]() {
auto p = std::make_shared<TAsyncSocketIntercepted::Params>();
p->corruptLastWriteByte_ = corruptionType == CorruptionType::REQUESTS;
p->corruptLastReadByte_ = corruptionType == CorruptionType::RESPONSES;
p->corruptLastReadByteMinSize_ = 1 << 10;
dynamic_cast<TAsyncSocketIntercepted*>(channel->getTransport())
->setParams(p);
});
};
for (CorruptionType testType : {CorruptionType::NONE,
CorruptionType::REQUESTS,
CorruptionType::RESPONSES}) {
static const int kSize = 32 << 10;
std::string asString(kSize, 'a');
std::unique_ptr<folly::IOBuf> payload =
folly::IOBuf::copyBuffer(asString);
setCorruption(testType);
auto future = client->future_echo(*payload);
if (testType == CorruptionType::NONE) {
EXPECT_EQ(asString, std::move(future).get());
} else {
bool didThrow = false;
try {
auto res = std::move(future).get();
} catch (TApplicationException& ex) {
EXPECT_EQ(TApplicationException::CHECKSUM_MISMATCH, ex.getType());
didThrow = true;
}
EXPECT_TRUE(didThrow);
}
}
setCorruption(CorruptionType::NONE);
});
}
void TransportCompatibilityTest::TestOneway_Simple() {
connectToServer([this](std::unique_ptr<TestServiceAsyncClient> client) {
EXPECT_CALL(*handler_.get(), add_(0));
EXPECT_CALL(*handler_.get(), addAfterDelay_(0, 5));
client->future_addAfterDelay(0, 5).get();
// Sleep a bit for oneway call to complete on server
/* sleep override */
std::this_thread::sleep_for(std::chrono::milliseconds(200));
EXPECT_EQ(5, client->future_add(0).get());
});
}
void TransportCompatibilityTest::TestOneway_WithDelay() {
connectToServer([this](std::unique_ptr<TestServiceAsyncClient> client) {
EXPECT_CALL(*handler_.get(), add_(0)).Times(2);
EXPECT_CALL(*handler_.get(), addAfterDelay_(800, 5));
// Perform an add on the server after a delay
client->future_addAfterDelay(800, 5).get();
// Call add to get result before the previous addAfterDelay takes
// place - this verifies that the addAfterDelay call is really
// oneway.
EXPECT_EQ(0, client->future_add(0).get());
// Sleep to wait for oneway call to complete on server
/* sleep override */
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
EXPECT_EQ(5, client->future_add(0).get());
});
}
void TransportCompatibilityTest::TestOneway_Saturation() {
connectToServer([this](auto client, auto connection) {
EXPECT_CALL(*handler_.get(), add_(3));
// note that no EXPECT_CALL for addAfterDelay_(0, 5)
connection->getEventBase()->runInEventBaseThreadAndWait(
[&]() { connection->setMaxPendingRequests(0u); });
EXPECT_THROW(
client->semifuture_addAfterDelay(0, 5).get(), TTransportException);
connection->getEventBase()->runInEventBaseThreadAndWait(
[&]() { connection->setMaxPendingRequests(1u); });
EXPECT_EQ(3, client->semifuture_add(3).get());
});
}
void TransportCompatibilityTest::TestOneway_UnexpectedException() {
connectToServer([this](std::unique_ptr<TestServiceAsyncClient> client) {
EXPECT_CALL(*handler_.get(), onewayThrowsUnexpectedException_(100));
EXPECT_CALL(*handler_.get(), onewayThrowsUnexpectedException_(0));
client->future_onewayThrowsUnexpectedException(100).get();
client->future_onewayThrowsUnexpectedException(0).get();
std::this_thread::sleep_for(std::chrono::milliseconds(200));
});
}
void TransportCompatibilityTest::TestOneway_Connection_CloseNow() {
connectToServer([](std::unique_ptr<TestServiceAsyncClient> client) {
// It should not reach server - no EXPECT_CALL for addAfterDelay_(0, 5)
// Observe the behavior if the connection is closed already
auto channel = static_cast<ClientChannel*>(client->getChannel());
channel->getEventBase()->runInEventBaseThreadAndWait(
[&]() { channel->closeNow(); });
EXPECT_THROW(
client->future_addAfterDelay(0, 5).get(),
apache::thrift::TTransportException);
});
}
void TransportCompatibilityTest::TestOneway_ServerQueueTimeout() {
// TODO: Even though we observe that the timeout functionality works fine for
// Oneway PRC calls, the AsyncProcesor still executes the `cancelled`
// requests.
connectToServer(
[this](std::unique_ptr<TestServiceAsyncClient> client) mutable {
int32_t numCores = sysconf(_SC_NPROCESSORS_ONLN);
int callCount = numCores + 1; // more than the core count!
// TODO: fixme T22871783: Oneway tasks don't get cancelled
EXPECT_CALL(*handler_.get(), addAfterDelay_(100, 5))
.Times(AtMost(2 * callCount));
server_->getServer()->setQueueTimeout(std::chrono::milliseconds(1));
for (int i = 0; i < callCount; ++i) {
EXPECT_NO_THROW(client->future_addAfterDelay(100, 5).get());
}
server_->getServer()->setQueueTimeout(std::chrono::milliseconds(1000));
server_->getServer()->setUseClientTimeout(false);
server_->getServer()->setTaskExpireTime(std::chrono::milliseconds(1));
for (int i = 0; i < callCount; ++i) {
EXPECT_NO_THROW(client->future_addAfterDelay(100, 5).get());
}
});
}
void TransportCompatibilityTest::TestOneway_Checksumming() {
connectToServer([this](std::unique_ptr<TestServiceAsyncClient> client) {
EXPECT_CALL(*handler_.get(), onewayLogBlob_(_));
auto setCorruption = [&](bool val) {
auto channel = static_cast<ClientChannel*>(client->getChannel());
channel->getEventBase()->runInEventBaseThreadAndWait([&]() {
auto p = std::make_shared<TAsyncSocketIntercepted::Params>();
p->corruptLastWriteByte_ = val;
dynamic_cast<TAsyncSocketIntercepted*>(channel->getTransport())
->setParams(p);
});
};
for (bool shouldCorrupt : {false, true}) {
static const int kSize = 32 << 10; // > IOBuf buf sharing thresh
std::string asString(kSize, 'a');
setCorruption(shouldCorrupt);
auto payload = folly::IOBuf::copyBuffer(asString);
client->future_onewayLogBlob(*payload).get();
// Unlike request/response case, no exception is thrown here for
// a one-way RPC.
/* sleep override */
std::this_thread::sleep_for(std::chrono::milliseconds(200));
}
setCorruption(false);
});
}
void TransportCompatibilityTest::TestRequestContextIsPreserved() {
EXPECT_CALL(*handler_.get(), add_(5)).Times(1);
// A separate server/client is spun up to verify that a client backed by a new
// transport behaves correctly and does not trample the currently set
// RequestContext. In this case, a THeader server is spun up, which is known
// to correctly set RequestContext. A request/response is made through the
// transport being tested, and it's verified that the RequestContext doesn't
// change.
auto service = std::make_shared<StrictMock<IntermHeaderService>>(
FLAGS_host, server_->port_);
SampleServer<IntermHeaderService> server(service);
server.startServer();
server.connectToServer(
"header", [](std::shared_ptr<RequestChannel> channel, auto) mutable {
auto client = std::make_unique<IntermHeaderServiceAsyncClient>(
std::move(channel));
EXPECT_EQ(5, client->sync_callAdd(5));
});
server.stopServer();
}
void TransportCompatibilityTest::TestBadPayload() {
connectToServer([](std::unique_ptr<TestServiceAsyncClient> client) {
auto cb = std::make_unique<MockCallback>(true, false);
auto channel = static_cast<ClientChannel*>(client->getChannel());
channel->getEventBase()->runInEventBaseThreadAndWait([&]() {
RequestRpcMetadata metadata;
metadata.set_clientTimeoutMs(10000);
metadata.set_kind(RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE);
metadata.set_name("name");
metadata.set_seqId(0);
metadata.set_protocol(ProtocolId::BINARY);
// Put a bad payload!
auto payload = std::make_unique<folly::IOBuf>();
RpcOptions rpcOptions;
auto ctx = std::make_unique<ContextStack>("temp");
auto header = std::make_shared<THeader>();
channel->sendRequest(
rpcOptions,
std::move(cb),
std::move(ctx),
std::move(payload),
std::move(header));
});
});
}
void TransportCompatibilityTest::TestEvbSwitch() {
connectToServer([this](std::unique_ptr<TestServiceAsyncClient> client) {
EXPECT_CALL(*handler_.get(), sumTwoNumbers_(1, 2)).Times(3);
folly::ScopedEventBaseThread sevbt;
EXPECT_EQ(3, client->future_sumTwoNumbers(1, 2).get());
auto channel = static_cast<ClientChannel*>(client->getChannel());
auto evb = channel->getEventBase();
evb->runInEventBaseThreadAndWait([&]() {
EXPECT_TRUE(channel->isDetachable());
channel->detachEventBase();
});
sevbt.getEventBase()->runInEventBaseThreadAndWait(
[&]() { channel->attachEventBase(sevbt.getEventBase()); });
// Execution happens on the new event base
EXPECT_EQ(3, client->future_sumTwoNumbers(1, 2).get());
// Attach the old one back
sevbt.getEventBase()->runInEventBaseThreadAndWait([&]() {
EXPECT_TRUE(channel->isDetachable());
channel->detachEventBase();
});
evb->runInEventBaseThreadAndWait([&]() { channel->attachEventBase(evb); });
// Execution happens on the old event base, along with the destruction
EXPECT_EQ(3, client->future_sumTwoNumbers(1, 2).get());
});
}
void TransportCompatibilityTest::TestEvbSwitch_Failure() {
connectToServer([this](std::unique_ptr<TestServiceAsyncClient> client) {
auto channel = static_cast<ClientChannel*>(client->getChannel());
auto evb = channel->getEventBase();
// If isDetachable() is called when a function is executing, it should
// not be detachable
callSleep(client.get(), 5000, 1000);
/* sleep override - make sure request is started */
std::this_thread::sleep_for(std::chrono::milliseconds(10));
evb->runInEventBaseThreadAndWait([&]() {
// As we have an active request, it should not be detachable!
EXPECT_FALSE(channel->isDetachable());
});
// Once the request finishes, it should be detachable again
/* sleep override - make sure request is finished */
std::this_thread::sleep_for(std::chrono::milliseconds(2000));
evb->runInEventBaseThreadAndWait([&]() {
// As we have an active request, it should not be detachable!
EXPECT_TRUE(channel->isDetachable());
});
// If the latest request is sent while previous ones are still finishing
// it should still not be detachable
EXPECT_CALL(*handler_.get(), sumTwoNumbers_(1, 2)).Times(1);
callSleep(client.get(), 5000, 1000);
/* sleep override - make sure request is started */
std::this_thread::sleep_for(std::chrono::milliseconds(10));
client->future_sumTwoNumbers(1, 2).get();
evb->runInEventBaseThreadAndWait([&]() {
// As we have an active request, it should not be detachable!
EXPECT_FALSE(channel->isDetachable());
});
/* sleep override - make sure request is finished */
std::this_thread::sleep_for(std::chrono::milliseconds(2000));
evb->runInEventBaseThreadAndWait([&]() {
// Should be detachable now
EXPECT_TRUE(channel->isDetachable());
// Detach to prove that we can destroy the object even if evb is detached
channel->detachEventBase();
});
});
}
class CloseCallbackTest : public CloseCallback {
public:
void channelClosed() override {
EXPECT_FALSE(closed_);
closed_ = true;
}
bool isClosed() {
return closed_;
}
private:
bool closed_{false};
};
void TransportCompatibilityTest::TestCloseCallback() {
connectToServer([](std::unique_ptr<TestServiceAsyncClient> client) {
auto closeCb = std::make_unique<CloseCallbackTest>();
auto channel = static_cast<ClientChannel*>(client->getChannel());
channel->setCloseCallback(closeCb.get());
EXPECT_FALSE(closeCb->isClosed());
auto evb = channel->getEventBase();
evb->runInEventBaseThreadAndWait([&]() { channel->closeNow(); });
EXPECT_TRUE(closeCb->isClosed());
});
}
} // namespace thrift
} // namespace apache
| [
"facebook-github-bot@users.noreply.github.com"
] | facebook-github-bot@users.noreply.github.com |
7879d5d6aed9342760050a4ce5ba49af82f3c35e | cf5d9e9e54a0c4f087866d5a549175a7a8ad38c5 | /uuu/buildincmd.h | 3efd833d64e37610fe286ece26fc433a6651c702 | [
"LGPL-2.0-or-later",
"BSD-3-Clause",
"Zlib",
"LicenseRef-scancode-unknown-license-reference",
"LGPL-2.1-only"
] | permissive | JeonghunLee/mfgtools | e3a55bcd00c2aa185dee0a9fefea77bfea553b74 | 854fe3e4d306a2548559881d84f6799d9da92326 | refs/heads/master | 2020-12-23T16:18:14.963228 | 2020-02-20T08:48:39 | 2020-02-20T08:48:39 | 237,202,562 | 0 | 0 | BSD-3-Clause | 2020-01-30T11:51:38 | 2020-01-30T11:51:38 | null | UTF-8 | C++ | false | false | 6,185 | h | /*
* Copyright 2018 NXP.
*
* 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 the NXP Semiconductor 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 HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
#pragma once
#include <string>
#include <vector>
#include <map>
#include <locale>
using namespace std;
extern char * g_vt_yellow ;
extern char * g_vt_default ;
extern char * g_vt_green ;
extern char * g_vt_red ;
extern char * g_vt_kcyn ;
extern char * g_vt_boldwhite ;
struct BuildCmd
{
const char *m_cmd;
const char *m_buildcmd;
const char *m_desc;
};
class Arg
{
public:
string m_arg;
string m_desc;
uint32_t m_flags;
string m_options;
enum
{
ARG_MUST = 0x1,
ARG_OPTION = 0x2,
ARG_OPTION_KEY = 0x4,
};
Arg() { m_flags = ARG_MUST; }
int parser(string option)
{
size_t pos;
pos = option.find('[');
if (pos == string::npos)
return 0;
m_options = option.substr(pos + 1, option.find(']') - pos - 1);
m_flags = ARG_OPTION | ARG_OPTION_KEY;
return 0;
}
};
class BuildInScript
{
public:
string m_script;
string m_desc;
string m_cmd;
vector<Arg> m_args;
bool find_args(string arg)
{
for (size_t i = 0; i < m_args.size(); i++)
{
if (m_args[i].m_arg == arg)
return true;
}
return false;
}
BuildInScript() {};
BuildInScript(BuildCmd*p)
{
m_script = p->m_buildcmd;
if(p->m_desc)
m_desc = p->m_desc;
if(p->m_cmd)
m_cmd = p->m_cmd;
for (size_t i = 1; i < m_script.size(); i++)
{
size_t off;
string param;
if (m_script[i] == '_' && m_script[i - 1] == ' ')
{
off = m_script.find(' ', i);
size_t ofn = m_script.find('\n', i);
if (ofn < off)
off = ofn;
if (off == string::npos)
off = m_script.size() + 1;
param = m_script.substr(i, off - i);
if (!find_args(param))
{
Arg a;
a.m_arg = param;
a.m_flags = Arg::ARG_MUST;
m_args.push_back(a);
}
}
}
for (size_t i = 0; i < m_args.size(); i++)
{
size_t pos = 0;
string str;
str += "@";
str += m_args[i].m_arg;
pos = m_script.find(str);
if (pos != string::npos) {
string def;
size_t start_descript;
start_descript = m_script.find('|', pos);
if (start_descript != string::npos)
{
m_args[i].m_desc = m_script.substr(start_descript + 1,
m_script.find('\n', start_descript) - start_descript - 1);
def = m_script.substr(pos, start_descript - pos);
m_args[i].parser(def);
}
}
}
}
void show()
{
printf("%s\n", m_script.c_str());
}
void show_cmd()
{
printf("\t%s%s%s\t%s\n", g_vt_boldwhite, m_cmd.c_str(), g_vt_default, m_desc.c_str());
for (size_t i=0; i < m_args.size(); i++)
{
string desc;
desc += m_args[i].m_arg;
if (m_args[i].m_flags & Arg::ARG_OPTION)
{
desc += g_vt_boldwhite;
desc += "[Optional]";
desc += g_vt_default;
}
desc += " ";
desc += m_args[i].m_desc;
printf("\t\targ%d: %s\n", (int)i, desc.c_str());
}
}
inline string str_to_upper(string str)
{
std::locale loc;
string s;
for (size_t i = 0; i < str.size(); i++)
s.push_back(std::toupper(str[i], loc));
return s;
}
string replace_str(string str, string key, string replace)
{
if (replace.size() > 4)
{
if (str_to_upper(replace.substr(replace.size() - 4)) == ".BZ2")
{
replace += "/*";
}
}
for (size_t j = 0; (j = str.find(key, j)) != string::npos;)
{
str.replace(j, key.size(), replace);
j += key.size();
}
return str;
}
string replace_script_args(vector<string> args)
{
string script = m_script;
for (size_t i = 0; i < args.size() && i < m_args.size(); i++)
{
script = replace_str(script, m_args[i].m_arg, args[i]);
}
//handle option args;
for (size_t i = args.size(); i < m_args.size(); i++)
{
if (m_args[i].m_flags & Arg::ARG_OPTION_KEY)
{
for (size_t j = 0; j < args.size(); j++)
{
if (m_args[j].m_arg == m_args[i].m_options)
{
script = replace_str(script, m_args[i].m_arg, args[j]);
break;
}
}
}
}
return script;
}
};
class BuildInScriptVector : public map<string, BuildInScript>
{
public:
BuildInScriptVector(BuildCmd*p)
{
while (p->m_cmd)
{
BuildInScript one(p);
(*this)[one.m_cmd] = one;
p++;
}
}
void ShowAll()
{
for (auto iCol = begin(); iCol != end(); ++iCol)
{
iCol->second.show_cmd();
}
}
void ShowCmds()
{
printf("<");
for (auto iCol = begin(); iCol != end(); ++iCol)
{
printf("%s%s%s", g_vt_boldwhite, iCol->first.c_str(), g_vt_default);
auto i = iCol;
i++;
if(i != end())
printf("|");
}
printf(">");
}
void PrintAutoComplete(string match, const char *space=" " )
{
for (auto iCol = begin(); iCol != end(); ++iCol)
{
if(iCol->first.substr(0, match.size()) == match)
printf("%s%s\n", iCol->first.c_str(), space);
}
}
};
extern BuildInScriptVector g_BuildScripts;
| [
"Frank.Li@nxp.com"
] | Frank.Li@nxp.com |
3ed8f87c8e6f0df8d43fe14e9c50539290833f02 | bd1fea86d862456a2ec9f56d57f8948456d55ee6 | /000/115/046/CWE762_Mismatched_Memory_Management_Routines__delete_wchar_t_malloc_51a.cpp | c5a84c415b521667d486d3efbbaf6dcd92840495 | [] | no_license | CU-0xff/juliet-cpp | d62b8485104d8a9160f29213368324c946f38274 | d8586a217bc94cbcfeeec5d39b12d02e9c6045a2 | refs/heads/master | 2021-03-07T15:44:19.446957 | 2020-03-10T12:45:40 | 2020-03-10T12:45:40 | 246,275,244 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,663 | cpp | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE762_Mismatched_Memory_Management_Routines__delete_wchar_t_malloc_51a.cpp
Label Definition File: CWE762_Mismatched_Memory_Management_Routines__delete.label.xml
Template File: sources-sinks-51a.tmpl.cpp
*/
/*
* @description
* CWE: 762 Mismatched Memory Management Routines
* BadSource: malloc Allocate data using malloc()
* GoodSource: Allocate data using new
* Sinks:
* GoodSink: Deallocate data using free()
* BadSink : Deallocate data using delete
* Flow Variant: 51 Data flow: data passed as an argument from one function to another in different source files
*
* */
#include "std_testcase.h"
namespace CWE762_Mismatched_Memory_Management_Routines__delete_wchar_t_malloc_51
{
#ifndef OMITBAD
/* bad function declaration */
void badSink(wchar_t * data);
void bad()
{
wchar_t * data;
/* Initialize data*/
data = NULL;
/* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */
data = (wchar_t *)malloc(100*sizeof(wchar_t));
badSink(data);
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* good function declarations */
void goodG2BSink(wchar_t * data);
void goodB2GSink(wchar_t * data);
/* goodG2B uses the GoodSource with the BadSink */
static void goodG2B()
{
wchar_t * data;
/* Initialize data*/
data = NULL;
/* FIX: Allocate memory from the heap using new */
data = new wchar_t;
goodG2BSink(data);
}
/* goodB2G uses the BadSource with the GoodSink */
static void goodB2G()
{
wchar_t * data;
/* Initialize data*/
data = NULL;
/* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */
data = (wchar_t *)malloc(100*sizeof(wchar_t));
goodB2GSink(data);
}
void good()
{
goodG2B();
goodB2G();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
using namespace CWE762_Mismatched_Memory_Management_Routines__delete_wchar_t_malloc_51; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| [
"frank@fischer.com.mt"
] | frank@fischer.com.mt |
aea4ffbaca43f5fc9c0f3ce525faf326118ac13b | 1399def334a538c3c4a38c63a2f8c7993cc6b18c | /src/CodeModel.hh | 4d11b031226ff0a0b307aab41b37716aab807894 | [
"MIT"
] | permissive | mpsm/spyc | 39e7c432d873ec9eddef4702074a0eec20c69608 | 60c2f53941c30aaf688b0966bd87978bc511342e | refs/heads/master | 2020-07-31T17:24:23.076759 | 2019-10-28T21:07:17 | 2019-11-02T22:11:56 | 200,090,439 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,116 | hh | #ifndef __SPYC_CODEMODEL_HH__
#define __SPYC_CODEMODEL_HH__
#include "Call.hh"
#include "Method.hh"
#include <functional>
#include <memory>
#include <string>
#include <unordered_map>
#include <unordered_set>
namespace spyc {
class CodeModelInterface {
public:
virtual std::shared_ptr<Method> getMethod(Method::ID) = 0;
virtual void addCall(Method& caller, Method& callee) = 0;
virtual ~CodeModelInterface() {}
};
class CodeModel : public CodeModelInterface {
public:
using funcmap = std::unordered_map<Method::ID, std::shared_ptr<Method>>;
virtual ~CodeModel() = default;
const funcmap& getFunctions() const;
const CallSet& getCalls() const;
std::vector<std::shared_ptr<Method>> findMethodsByName(
const std::string& name) const;
std::shared_ptr<Method> getMethod(Method::ID id);
void addCall(Method& caller, Method& callee);
private:
bool hasMethod(const Method& m);
funcmap functions;
CallSet calls;
};
} // namespace spyc
#endif /* __SPYC_CODEMODEL_HH__ */ | [
"smoczynski.marcin@gmail.com"
] | smoczynski.marcin@gmail.com |
931d80e08b4368177916710e46d1388daa8467b4 | cde72953df2205c2322aac3debf058bb31d4f5b9 | /win10.19042/SysWOW64/SystemSettings.DataModel.dll.cpp | cf8672bddc61058fc2d78cde777387cb00917c8d | [] | no_license | v4nyl/dll-exports | 928355082725fbb6fcff47cd3ad83b7390c60c5a | 4ec04e0c8f713f6e9a61059d5d87abc5c7db16cf | refs/heads/main | 2023-03-30T13:49:47.617341 | 2021-04-10T20:01:34 | 2021-04-10T20:01:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 331 | cpp | #print comment(linker, "/export:DllCanUnloadNow=\"C:\\Windows\\SysWOW64\\SystemSettings.DataModel.dll\"")
#print comment(linker, "/export:DllGetActivationFactory=\"C:\\Windows\\SysWOW64\\SystemSettings.DataModel.dll\"")
#print comment(linker, "/export:DllGetClassObject=\"C:\\Windows\\SysWOW64\\SystemSettings.DataModel.dll\"")
| [
"magnus@stubman.eu"
] | magnus@stubman.eu |
03efe4fe65af0084d01d32518d026e9109581ad9 | b160b41bffbf0362119f5c16fb62f859b4c83c38 | /AgentCombat.cpp | 53df723e462c06f3d3bf50d2256d0523ed1995fe | [] | no_license | AaronCMcDermott/GPU-Sugarscape | 8de132a92378a6df9be911e16a5624353e70fe8d | 5a1719abb50b2812e57aa689ac71b82c4f8416d6 | refs/heads/master | 2016-09-13T17:10:51.944558 | 2016-04-15T08:17:41 | 2016-04-15T08:17:41 | 56,303,236 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,803 | cpp | // AgentCombat.cpp
// SugarScape
// Created by Joseph P Kehoe on 16/07/2015.
// Copyright (c) 2015 Joseph P Kehoe. All rights reserved.
#include "AgentCombat.h"
bool combatCompare(Location *a, Location *b)
{
return a->getReward()>b->getReward();
}
/**
* Constructor - passes World pointer to parent constructor
* @param s :Pointer to World
* @return none
* @exception none
*/
AgentCombat::AgentCombat(World *s)
:AgentMove(s)
{
//our work is done
}
/**
* Agent removes agent in location in group from world and takes resources
* It also removes links to agents killed by combat (lenders, borrowers, etc.)
* @param loc :Pointer to Location of the winning agent
* @param grp : Pointer to Group containing location of losing agent (or possibly an empty location)
* @see Combat Rule
* @return true if agent exists at loc else false
* @exception none
*/
bool AgentCombat::executeAction(Location *loc, group *grp)
{
if (loc->hasAgent()) {
Agent *winner = grp->getPrimeMover()->getAgent(); //must equal loc->getAgent()!
if (grp->getMembers().size()!=0)/*!< we are moving somewhere */
{
if (grp->getMembers()[0]->hasAgent()==false) {/*!< moving to empty location */
loc->getAgent()->incSugar(grp->getMembers()[0]->getSugar());/*!< eat sugar at destination */
grp->getMembers()[0]->setSugar(0);/*!< sugar at location is consumed */
}
else{
//std::cout <<"COMBAT!"<<std::endl;
//1. Update victorious agent resources
Agent *loser = grp->getMembers()[0]->getAgent();//only one member in group - the loser
winner->incSugar(grp->getMembers()[0]->getReward());//*WHAT IF WE ADD SPICE?*
grp->getMembers()[0]->setSugar(0);/*!< sugar at location is consumed */
//2. Kill vanquished agent
std::pair<int,int> currPosition=loser->getPosition();
if (loser!=sim->killAgent(currPosition))
{
std::cerr << "Delete of agent failed"<<std::endl;
}
}
//Move agent to new position
std::pair<int,int> currPosition=winner->getPosition();
sim->setAgent(currPosition, nullptr);//remove old location ptr to agent
winner->setPosition(grp->getMembers()[0]->getPosition());//set new position to new location
sim->setAgent(grp->getMembers()[0]->getPosition(),winner);//add ptr to agent at new location
}
else{/*!< we are staying put-not moving */
loc->getAgent()->incSugar(loc->getSugar());/*!< eat sugar at destination */
loc->setSugar(0);/*!< sugar at location is consumed */
}
for(auto ag:winner->getChildren())/*!< Remove any links to killed children */
{
if (ag->isKilled()) {
winner->removeChild(ag);
}
}
winner->removeKilledLoans();/*!< remove loans with killed agents */
winner->removeKilledFather();/*!< remove father link if he is killed */
winner->removeKilledMother();/*!< remove mother link if she is killed */
return true;
}else{
return false;/*!< no agent present so did nothing */
}
}
/**
* Picks the agent we want to attack if any, or otherwise an empty location to move to
* @param possibles : list containing al possible destinations
* @param me : the Agent making the move
* @see Combat Rule
* @return index of destination from list (std::vector)
* @exception none
*/
int AgentCombat::pickIndex(std::vector<Location*> possibles,Agent *me)
{//find a winner
//Find out if there is going to be retaliation
//1. get meanest opponent in list
int strongestEnemy=0;
for(auto loc:possibles){
if (loc->hasAgent()) {
if (strongestEnemy < loc->getAgent()->getReward()) {
strongestEnemy = loc->getAgent()->getReward();
}
}
}
//2. Sort list by desirability
std::sort(possibles.begin(),possibles.end(),combatCompare);
//offload to GPU, pcount,
// and run in parallel
// i,possibles.size() - read/write
#pragma omp target teams distribute parallel for\
map(to: k,pcount), map (tofrom:i,possibles.size())
for (int i = 0; i < possibles.size(); ++i) {
if (possibles[i]->hasAgent() == false) {
return i;//found index of empty space
} else {//has agent so check for combat
if (possibles[i]->getReward() + me->getWealth() > strongestEnemy) {
return i;
}
}
}
return -1;
}
/**
* Creates the group containing the vistim we are attacking or empty location we are moving to
* @param loc :pointer to our location
* @see Combat Rule
* @return pointer to group object
* @exception none
*/
group* AgentCombat::formGroup(Location *loc)
{
if (loc->hasAgent() && loc->isDone()==false) {/*!< Agent at this location */
group *ourChoice = nullptr;
Agent* theAgent=loc->getAgent();
std::vector<Location*> possibleLocations=sim->getCombatNeighbourhood(theAgent->getPosition(), theAgent->getVision());/*!< Find all possible destinations */
ourChoice = new group();
if (possibleLocations.size()!=0) {/*!< check to see if we can move anywhere */
int index=pickIndex(possibleLocations, theAgent);
if (index>-1) {//we have a winner -- form a group
ourChoice->push_back(possibleLocations[index]);
//sim->getLocation(possibleLocations[index]->getPosition()));
int rank=possibleLocations[index]->getPosition().first-theAgent->getPosition().first
+possibleLocations[index]->getPosition().second-theAgent->getPosition().second;
if (rank<0) rank =-rank;
ourChoice->setRank(rank);
ourChoice->setPrimeMover(loc);
if (possibleLocations[index]->hasAgent()) {
ourChoice->setActiveParticipants(2);/*!< have killed agent therefore two participants here */
}else{
ourChoice->setActiveParticipants(1);//one active participant in group - the agent moving
}
}
else{/*!< cannot find anywhere safe to move so stay here */
ourChoice->setRank(0);
ourChoice->setPrimeMover(loc);
ourChoice->setActiveParticipants(1);
}
}else{/*!< everywhere is occupied so stay here */
ourChoice->setRank(0);
ourChoice->setPrimeMover(loc);
ourChoice->setActiveParticipants(1);
}
return ourChoice;
}
return nullptr;/*!< No agent here do nothing */
} | [
"c00157704@itcarlow.ie"
] | c00157704@itcarlow.ie |
107bca0709d340b68c6f947dcd8655413b9f6cd3 | 0539572660ca24daabe44c26afc8d24ae73b9bf4 | /B_Strange_List.cpp | 0f8a33f76aefd33f043822146634d6d2ed1740a5 | [] | no_license | VanshRuhela/CodeForcesPractice | 0d91e971343f4b43807609cfff2afce4cc88d731 | 24f5fa1e515fe117606554450c245f5beacf8336 | refs/heads/master | 2023-05-28T14:59:20.280249 | 2021-06-03T07:06:57 | 2021-06-03T07:06:57 | 373,414,420 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,796 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
typedef long double ld;
#define P 1000000007
#define rep(i,n) for(int i=0;i<n;++i)
#define re(i,a,n) for(i=a;i<=n;++i)
#define repr(i,a,n) for(i=a;i>=n;--i)
#define pb push_back
#define mp make_pair
#define fi first
#define se second
#define ub(v,val) upper_bound(v.begin(),v.end(),val)
#define np(str) next_permutation(str.begin(),str.end())
#define lb(v,val) lower_bound(v.begin(),v.end(),val)
#define sortv(vec) sort(vec.begin(),vec.end())
#define rev(p) reverse(p.begin(),p.end());
#define mset(a,val) memset(a,val,sizeof(a));
ll MOD = 998244353;
double eps = 1e-12;
#define forn(i,e) for(ll i = 0; i < e; i++)
#define forsn(i,s,e) for(ll i = s; i < e; i++)
#define rforn(i,s) for(ll i = s; i >= 0; i--)
#define rforsn(i,s,e) for(ll i = s; i >= e; i--)
#define ln "\n"
#define dbg(x) cout<<#x<<" = "<<x<<ln
#define mp make_pair
#define pb push_back
#define fi first
#define se second
#define INF 2e18
#define fast_cin() ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL)
#define all(x) (x).begin(), (x).end()
#define sz(x) ((ll)(x).size())
void solve(){
int n;
ll x;
cin>>n >>x;
deque <pair<ll, ll>> v;
ll m;
rep(i, n){
cin>>m;
v.push_back({m, 1});
}
ll s = 0;
while(!v.empty()){
pair<ll, ll> p = v.front();
v.pop_front();
ll y = p.first, f = p.second;
s+=y*f;
if(y%x != 0) break;
v.push_back({ y/x , x*f });
}
while(!v.empty()){
pair<ll, ll> p = v.front();
v.pop_front();
ll y = p.first, f = p.second;
s+=y*f;
}
cout<<s<<ln;
}
int main()
{
fast_cin();
int t;
cin >> t;
for(int it=1;it<=t;it++) {
solve();
}
return 0;
} | [
"vansh_r@ch.iitr.ac.in"
] | vansh_r@ch.iitr.ac.in |
b25cab4f75758f18cfaa2c6ba0825a7937e7383f | 7e68c3e0e86d1a1327026d189a613297b769c411 | /WinDiff/TextView.cpp | 53b766532cd724794fd8b11f5b0225edcd192858 | [] | no_license | staticlibs/Big-Numbers | bc08092e36c7c640dcf43d863448cd066abaebed | adbfa38cc2e3b8ef706a3ac8bbd3e398f741baf3 | refs/heads/master | 2023-03-16T20:25:08.699789 | 2020-12-20T20:50:25 | 2020-12-20T20:50:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 44,358 | cpp | #include "stdafx.h"
#include "Mainfrm.h"
IMPLEMENT_DYNCREATE(TextView, CView)
BEGIN_MESSAGE_MAP(TextView, CView)
ON_WM_CREATE()
ON_WM_SIZE()
ON_WM_DESTROY()
// Standard printing commands
ON_COMMAND(ID_FILE_PRINT , OnFilePrint )
ON_COMMAND(ID_FILE_PRINT_DIRECT , OnFilePrint )
ON_COMMAND(ID_FILE_PRINT_PREVIEW, OnFilePrintPreview)
END_MESSAGE_MAP()
#define SELECTFONT(dc) (dc).SelectObject(&m_font)
TextView::TextView() {
init();
m_winSize = CSize(-1,-1);
m_caretSize = CSize(-1,-1);
m_arrowSize = CSize(-1,-1);
m_arrowDC.CreateCompatibleDC(nullptr);
m_workDC.CreateCompatibleDC( nullptr);
m_maxOffset.set(0,0);
}
void TextView::init() {
m_state.init();
m_lastCaretPos = getCaretPosition();
resetArrow();
m_anchor.reset();
m_lastAnchor.reset();
}
void TextView::Create(const CRect &r, CWnd *parent, Diff &diff) {
m_diff = &diff;
if(__super::Create(nullptr, nullptr, AFX_WS_DEFAULT_VIEW ,r, parent, 0) == -1) {
throwException(_T("TextView::Create failed"));
}
}
int TextView::OnCreate(LPCREATESTRUCT lpCreateStruct) {
if(__super::OnCreate(lpCreateStruct) == -1) {
return -1;
}
setFlagValue(VIEW_ISCREATED, true);
return 0;
}
void TextView::OnDestroy() {
__super::OnDestroy();
setFlagValue(VIEW_ISCREATED, false);
}
void TextView::OnDraw(CDC *pDC) {
SELECTFONT(m_workDC);
paint(&m_workDC);
pDC->BitBlt(0,0,m_workSize.cx, m_workSize.cy, &m_workDC, 0,0,SRCCOPY);
}
void TextView::OnInitialUpdate() {
__super::OnInitialUpdate();
setFont(getOptions().m_logFont, false);
m_state.init(getDiffView().getId());
bool idCollision = false;
if(hasPartner() && getId() == getPartner()->getId()) {
m_state.init(1 - getPartner()->getId());
idCollision = true;
}
setFlagValue(VIEW_ISACTIVE, getId() == 0);
if(idCollision) {
repaintAll();
} else {
refreshDoc();
}
setWindowCursor(this,IDC_IBEAM);
}
void TextView::OnSize(UINT nType, int cx, int cy) {
updateWindowSize(cx,cy);
}
#define ERASEONINVALIDATE false
void TextView::repaintAll() {
Invalidate(ERASEONINVALIDATE);
}
void TextView::savePositionState() {
if(m_diff->isEmpty()) {
return;
}
const DiffLine &dl = m_diff->getDiffLine(getCurrentLine());
int index0;
if((index0 = dl.getText(0).getIndex()) >= 0) {
m_savedPositionState.set(0, TextPosition(index0 , getLineOffset()), getCaretPosition(), getPreferredColumn());
} else {
m_savedPositionState.set(1, TextPosition(dl.getText(1).getIndex(), getLineOffset()), getCaretPosition(), getPreferredColumn());
}
}
void TextView::restorePositionState() {
const DiffLineArray &lines = m_diff->getDiffLines();
for(int i = 0; i < getLineCount(); i++) {
const DiffLine &dl = lines[i];
const int l = dl.getText(m_savedPositionState.m_id).getIndex();
if(l == m_savedPositionState.m_offset.m_line) {
setTopLine( i-m_savedPositionState.m_caret.y);
setLineOffset( m_savedPositionState.m_offset.m_column);
setCaretY( m_savedPositionState.m_caret.y);
setPreferredColumn(m_savedPositionState.m_preferredColumn);
break;
}
}
m_savedPositionState.reset();
}
void TextView::refreshDoc() {
m_diff = &(getDocument()->m_diff);
m_lineCount = m_diff->getLineCount();
if(getShow1000Separator()) {
m_margin = (int)format1000(getLineCount()).length() + 1;
} else {
m_margin = (int)format(_T("%d"), getLineCount()).length() + 1;
}
updateWindowSize();
clearDC();
getDiffView().setScrollRange(true);
getDiffView().updateTitle();
}
void TextView::refreshBoth() {
refreshDoc();
if(hasPartner()) {
getPartner()->refreshDoc();
}
if(!m_savedPositionState.isEmpty()) {
restorePositionState();
}
redrawBoth();
const String title = format(_T("Differences between %s and %s"),m_diff->getName(0).cstr(),m_diff->getName(1).cstr());
theApp.GetMainWnd()->SetWindowText(title.cstr());
}
#define SAVESTATE if(repaint) savePositionState()
#define REFRESHBOTH if(repaint) refreshBoth()
// ---------------------------------------- Set Option functions ------------------------------------
bool TextView::setIgnoreCase(bool newValue, bool repaint) {
SAVESTATE;
const bool changed = getDocument()->setIgnoreCase(newValue, repaint);
REFRESHBOTH;
return changed;
}
bool TextView::setIgnoreWhiteSpace(bool newValue, bool repaint) {
SAVESTATE;
const bool changed = getDocument()->setIgnoreWhiteSpace(newValue, repaint);
REFRESHBOTH;
return changed;
}
bool TextView::setIgnoreComments(bool newValue, bool repaint) {
SAVESTATE;
const bool changed = getDocument()->setIgnoreComments(newValue, repaint);
REFRESHBOTH;
return changed;
}
bool TextView::setIgnoreColumns(bool newValue, bool repaint) {
SAVESTATE;
bool changed;
if(newValue) {
changed = getDocument()->setFileFormat(&getOptions().m_fileFormat, repaint);
} else {
changed = getDocument()->setFileFormat(nullptr, repaint);
}
REFRESHBOTH;
return changed;
}
bool TextView::setIgnoreRegex(bool newValue, bool repaint) {
SAVESTATE;
bool changed;
if(newValue) {
changed = getDocument()->setRegexFilter(&getOptions().m_regexFilter, repaint);
} else {
changed = getDocument()->setRegexFilter(nullptr, repaint);
}
REFRESHBOTH;
return changed;
}
bool TextView::setStripComments(bool newValue, bool repaint) {
SAVESTATE;
const bool changed = getDocument()->setStripComments(newValue, repaint);
REFRESHBOTH;
return changed;
}
bool TextView::setIgnoreStrings(bool newValue, bool repaint) {
SAVESTATE;
const bool changed = getDocument()->setIgnoreStrings(newValue, repaint);
REFRESHBOTH;
return changed;
}
bool TextView::setViewWhiteSpace(bool newValue, bool repaint) {
SAVESTATE;
const bool changed = getDocument()->setViewWhiteSpace(newValue, repaint);
REFRESHBOTH;
return changed;
}
bool TextView::setTabSize(int newValue, bool repaint) {
SAVESTATE;
const bool changed = getDocument()->setTabSize(newValue, repaint);
REFRESHBOTH;
return changed;
}
static bool operator==(const LOGFONT &lf1, const LOGFONT &lf2) {
return (memcmp(&lf1, &lf2, offsetof(LOGFONT,lfFaceName)) == 0)
&& (_tcsicmp(lf1.lfFaceName, lf2.lfFaceName) == 0);
}
LOGFONT TextView::getLogFont() {
LOGFONT result;
if(m_font.m_hObject != nullptr) {
m_font.GetLogFont(&result);
} else {
memset(&result,0,sizeof(LOGFONT));
}
return result;
}
bool TextView::setFont(const LOGFONT &newValue, bool repaint) {
if(getLogFont() == newValue) {
return false;
}
SAVESTATE;
if(m_font.m_hObject) {
m_font.DeleteObject();
}
if(!m_font.CreateFontIndirect(&newValue)) {
throwLastErrorOnSysCallException(__TFUNCTION__, _T("CreateFontIndirect"));
}
getOptions().m_logFont = newValue;
if(hasPartner()) {
getPartner()->setFont(newValue, false);
}
REFRESHBOTH;
return true;
}
bool TextView::setShow1000Separator(bool newValue, bool repaint) {
if(getShow1000Separator() == newValue) {
return false;
}
SAVESTATE;
setFlagValue(SHOW_1000SEPARATOR, newValue);
getOptions().m_show1000Separator = newValue;
if(hasPartner()) {
getPartner()->setFlagValue(SHOW_1000SEPARATOR, newValue);
}
REFRESHBOTH;
return true;
}
bool TextView::setNameFontSizePct(int newValue, bool repaint) {
if(newValue == getDiffView().getNameFontSizePct()) {
return false;
}
SAVESTATE;
getDiffView().setNameFontSizePct(newValue);
getOptions().m_nameFontSizePct = newValue;
REFRESHBOTH;
return true;
}
bool TextView::setHighLightCompareEqual(bool newValue, bool repaint) {
if(getHighLightCompareEqual() == newValue) {
return false;
}
setFlagValue(HIGHLIGhT_COMPAREEQUAL, newValue);
if(hasPartner()) {
getPartner()->setFlagValue(HIGHLIGhT_COMPAREEQUAL, newValue);
}
REFRESHBOTH;
return true;
}
void TextView::setFlagValue(TextViewFlags id, bool value) {
if(value) {
m_viewFlags.add(id);
} else {
m_viewFlags.remove(id);
}
}
void TextView::setOptions(const Options &options) {
savePositionState();
bool recomp = false;
recomp |= setIgnoreCase( options.m_ignoreCase , false);
recomp |= setIgnoreWhiteSpace( options.m_ignoreWhiteSpace , false);
recomp |= setIgnoreComments( options.m_ignoreComments , false);
recomp |= setStripComments( options.m_stripComments , false);
recomp |= setIgnoreStrings( options.m_ignoreStrings , false);
recomp |= setIgnoreColumns( options.m_ignoreColumns , false);
recomp |= setIgnoreRegex( options.m_ignoreRegex , false);
bool refresh = recomp;
refresh |= setViewWhiteSpace( options.m_viewWhiteSpace , false);
refresh |= setTabSize( options.m_tabSize , false);
refresh |= setShow1000Separator( options.m_show1000Separator, false);
refresh |= setNameFontSizePct( options.m_nameFontSizePct , false);
refresh |= setFont( options.m_logFont , false);
if(recomp) {
getDocument()->recompare();
}
if(refresh) {
if(!recomp) {
getDocument()->refresh();
}
refreshBoth();
}
}
// ---------------------------------- paint functions ------------------------------------
void TextView::paint(CDC *pDC) {
const int topLine = getTopLine();
int y = 0;
clearDC(pDC);
for(int i = topLine; (i < getLineCount()) && (y <= m_winSize.cy); i++, y++) {
paintLineNumber(pDC, y);
paintTextLine(pDC, y);
}
if(y < m_winSize.cy) { // clear the rest
const int textL = m_characterSize.cx * m_margin;
const int textB = m_characterSize.cy * y;
const int w = m_workSize.cx - textL;
const int h = m_workSize.cy - textB;
pDC->FillSolidRect(0 ,textB, textL, h, LINENUMBERBACKGROUND);
pDC->FillSolidRect(textL,textB, w , h, WHITE );
/*
paintLineNumber( pDC, y, -1);
paintTextSegment(pDC, 0, y, m_winSize.cx+1, WHITE, WHITE, EMPTYSTRING);
*/
}
if(isActive()) {
displayCaret(pDC);
}
getDiffView().setScrollPos();
}
void TextView::clearDC(CDC *pDC) {
if(pDC) {
pDC->FillSolidRect(0,0,m_workSize.cx, m_workSize.cy,WHITE);
resetArrow();
} else {
CClientDC dc(this);
const CSize sz = getClientRect(this).Size();
dc.FillSolidRect(0,0,sz.cx,sz.cy,WHITE);
}
}
void TextView::repaintLines(CDC *pDC, int from, int to) {
SELECTFONT(*pDC);
for(int y = from; y <= to; y++) {
paintTextLine(pDC, y);
}
}
void TextView::unMarkSelectedText(CDC *pDC) {
if(m_anchor != m_lastAnchor) {
if(!m_lastAnchor.isEmpty()) {
repaintLines(pDC, 0,m_winSize.cy);
}
m_lastAnchor = m_anchor;
}
}
void TextView::markSelectedText(CDC *pDC) {
unMarkSelectedText(pDC);
if(!m_anchor.isEmpty()) {
if(m_lastCaretPos.y >= 0) {
const CPoint cp = getCaretPosition();
repaintLines(pDC,min(cp.y,m_lastCaretPos.y),max(cp.y,m_lastCaretPos.y));
}
}
}
// ------------------------------------ Arrow functions ---------------------------------
void TextView::paintArrow(CDC *pDC) {
if(m_state.m_caret.y == getArrowLine()) return;
if(hasArrow()) {
unpaintArrow(pDC);
} else {
TextView *partner = getPartner();
if(partner && partner->hasArrow()) {
CClientDC dc(partner);
partner->unpaintArrow(&dc);
}
}
m_arrowLine = m_state.m_caret.y;
const CPoint pos = getArrowPosition(getArrowLine());
saveBackground(pDC);
pDC->BitBlt(pos.x,pos.y, m_arrowSize.cx,m_arrowSize.cy, &m_arrowDC,0,0,SRCCOPY);
}
void TextView::unpaintArrow(CDC *pDC) {
if(!hasArrow()) return;
const CPoint pos = getArrowPosition(getArrowLine());
CBitmap *oldBitmap = m_arrowDC.SelectObject(&m_backgroundBitmap);
if(pDC) {
pDC->BitBlt(pos.x,pos.y, m_arrowSize.cx,m_arrowSize.cy, &m_arrowDC, 0, 0, SRCCOPY);
} else {
CClientDC dc(this);
dc.BitBlt(pos.x,pos.y, m_arrowSize.cx,m_arrowSize.cy, &m_arrowDC, 0, 0, SRCCOPY);
}
m_arrowDC.SelectObject(oldBitmap);
resetArrow();
}
void TextView::saveBackground(CDC *pDC) {
const CPoint pos = getArrowPosition(getArrowLine());
CBitmap *oldBitmap = m_arrowDC.SelectObject(&m_backgroundBitmap);
m_arrowDC.BitBlt(0,0, m_arrowSize.cx,m_arrowSize.cy, pDC, pos.x,pos.y, SRCCOPY);
m_arrowDC.SelectObject(oldBitmap);
}
CPoint TextView::getArrowPosition(int lineno) const {
const int x = m_characterSize.cx * m_margin - m_arrowSize.cx - m_characterSize.cx * 2 / 3;
const int y = m_characterSize.cy * lineno + max(m_characterSize.cy - m_arrowSize.cy,0)/2;
return CPoint(x,y);
}
void TextView::setArrowSize(const CSize &size) {
if(size == m_arrowSize) {
return;
}
resetArrow();
if(m_arrowBitmap.m_hObject) {
m_arrowDC.SelectObject((CBitmap*)nullptr);
m_arrowBitmap.DeleteObject();
m_backgroundBitmap.DeleteObject();
}
CBitmap rawBM;
rawBM.LoadBitmap(IDB_ARROW);
const CSize rawSize = getBitmapSize(rawBM);
m_arrowBitmap.CreateBitmap(size.cx, size.cy, 1, 32,nullptr);
m_arrowDC.SelectObject(&m_arrowBitmap);
CDC rawDC;
rawDC.CreateCompatibleDC(nullptr);
CBitmap *oldbm = rawDC.SelectObject(&rawBM);
SetStretchBltMode(m_arrowDC, COLORONCOLOR /*HALFTONE*/);
m_arrowDC.StretchBlt( 0,0,size.cx, size.cy, &rawDC, 0,0,rawSize.cx, rawSize.cy, SRCCOPY);
m_arrowSize = size;
m_backgroundBitmap.CreateBitmap(m_arrowSize.cx, m_arrowSize.cy, 1, 32,nullptr);
}
// ------------------------------------ Caret functions ---------------------------------
void TextView::setCaretSize(const CSize &size) {
m_caretSize = size;
}
void TextView::showCaret() {
int id = getId();
CPoint caret = getCaretPosition();
if((caret.x >= 0) && !isCaretVisible()) {
CPoint cp;
cp.x = (caret.x + m_margin) * m_characterSize.cx;
cp.y = caret.y * m_characterSize.cy;
if(!caretExist()) createCaret();
SetCaretPos(cp);
ShowCaret();
setFlagValue(CARET_VISIBLE, true);
}
}
void TextView::hideCaret() {
if(isCaretVisible()) {
HideCaret();
setFlagValue(CARET_VISIBLE, false);
}
}
void TextView::createCaret() {
if(!caretExist()) {
CreateSolidCaret(m_caretSize.cx, m_caretSize.cy);
setFlagValue(CARET_EXIST , true );
setFlagValue(CARET_VISIBLE, false);
}
}
void TextView::destroyCaret() {
if(caretExist()) {
DestroyCaret();
setFlagValue(CARET_EXIST , false);
setFlagValue(CARET_VISIBLE, false);
}
}
void TextView::displayCaret(CDC *pDC) {
m_state.m_caret.x = min(m_state.getPreferredCaretX(), getMaxCaretX());
TextView *partner = getPartner();
if(partner) {
const CPoint caret = getCaretPosition();
int newColumnOffset = partner->getLineOffset();
int xpos = getLineOffset() + max(caret.x, 0);
if(xpos < partner->getLineOffset()) {
newColumnOffset = xpos;
} else if(xpos >= partner->getRightOffset()) {
newColumnOffset = xpos - partner->m_winSize.cx;
}
if(newColumnOffset < 0) {
newColumnOffset = 0;
}
partner->setPreferredColumn(getPreferredColumn());
partner->m_state.m_caret.x = caret.x;
partner->setCaretY(caret.y);
const TextPosition newTopLeft(getTopLine(), newColumnOffset); // for partner
if(newTopLeft != partner->getTopLeft()) {
partner->setTopLeft(newTopLeft);
partner->repaintAll();
}
}
CClientDC dc(this);
if(pDC == nullptr) {
pDC = &dc;
}
markSelectedText(pDC);
CWinDiffSplitterWnd *splitter = (CWinDiffSplitterWnd*)getDiffView().GetParent();
splitter->setActivePanel(getId());
paintArrow(pDC);
m_lastCaretPos = getCaretPosition();
CMainFrame *frame = (CMainFrame*)(splitter->GetParent());
frame->ajourMenuItems();
}
// ----------------------------------- paint line function ---------------------------------------
static void setColor(CDC *pDC, const COLORREF &tc, const COLORREF &bc) {
pDC->SetBkColor(bc);
pDC->SetTextColor(tc);
}
void TextView::paintLineNumber(CDC *pDC, int y, int lineno) {
String tmp;
if(lineno < 0) {
tmp = format(_T("%*.*s"), m_margin, m_margin, EMPTYSTRING);
} else if(getShow1000Separator()) {
tmp = format(_T("%*s "), m_margin - 1, format1000(lineno+1).cstr());
} else {
tmp = format(_T("%*d "), m_margin - 1, lineno+1);
}
if(y == getArrowLine()) {
unpaintArrow(pDC);
}
setColor(pDC,BLACK,LINENUMBERBACKGROUND);
pDC->TextOut(0,y * m_characterSize.cy,tmp.cstr());
}
void TextView::paintLineNumber(CDC *pDC, int y) {
const int topLine = getTopLine();
if(topLine + y >= getLineCount()) {
return;
}
const DiffLine &df = m_diff->getDiffLine(topLine + y);
const int id = getId();
switch(df.getAttr()) {
case EQUALLINES :
case CHANGEDLINES :
paintLineNumber(pDC, y, df.getText(id).getIndex());
break;
case DELETEDLINES :
if(id == 1) {
paintLineNumber(pDC, y, -1);
} else {
paintLineNumber(pDC, y, df.getText(0).getIndex());
}
break;
case INSERTEDLINES:
if(id == 1) {
paintLineNumber(pDC, y, df.getText(1).getIndex());
} else {
paintLineNumber(pDC, y, -1);
}
break;
}
}
LineSegments TextView::getLineSegments(int l) const {
LineSegments result;
if(m_anchor.isEmpty()) {
result.m_segments = 0;
return result;
}
const TextPosition &topLeft = getTopLeft();
const int currentLine = getCurrentLine();
const int currentCol = getCurrentColumn();
#define ISBETWEEN(x,a,b) (((a)<=(x)) && ((x)<=(b)))
if(currentLine == m_anchor.m_line) {
if((l == currentLine) && (currentCol != m_anchor.m_column)) {
if(currentCol > m_anchor.m_column) {
result.m_c1 = m_anchor.m_column - topLeft.m_column;
result.m_c2 = currentCol - topLeft.m_column;
} else { // currentCol < m_anchor.m_column
result.m_c1 = currentCol - topLeft.m_column;
result.m_c2 = m_anchor.m_column - topLeft.m_column;
}
result.m_segments = ((result.m_c1>0 ) ? HAS_LEFTSEGMENT : 0)
| HAS_MIDDLESEGMENT
| ((result.m_c2<m_winSize.cx+1 ) ? HAS_RIGHTSEGMENT : 0);
} else {
result.m_segments = 0;
}
} else if(currentLine > m_anchor.m_line) {
if(ISBETWEEN(l, m_anchor.m_line, currentLine)) {
if(l == m_anchor.m_line) {
result.m_c1 = m_anchor.m_column - topLeft.m_column;
result.m_c2 = m_winSize.cx + 1;
result.m_segments = ((result.m_c1>0 ) ? HAS_LEFTSEGMENT : 0)
| ((result.m_c2>result.m_c1 ) ? HAS_MIDDLESEGMENT : 0);
// no RIGHTSEGMENT
} else if(l == currentLine) {
result.m_c1 = 0;
result.m_c2 = currentCol - topLeft.m_column;
result.m_segments = ((result.m_c2>0 ) ? HAS_MIDDLESEGMENT : 0)
| ((result.m_c2<m_winSize.cx+1 ) ? HAS_RIGHTSEGMENT : 0);
// no LEFTSEGMENT
} else { // mark whole line
result.m_c1 = 0;
result.m_c2 = m_winSize.cx + 1;
result.m_segments = HAS_MIDDLESEGMENT;
}
} else {
result.m_segments = 0;
}
} else { // currentLine < m_anchor.m_line
if(ISBETWEEN(l, currentLine, m_anchor.m_line)) {
if(l == currentLine) {
result.m_c1 = currentCol - topLeft.m_column;
result.m_c2 = m_winSize.cx + 1;
result.m_segments = ((result.m_c1>0 ) ? HAS_LEFTSEGMENT : 0)
| ((result.m_c2>result.m_c1 ) ? HAS_MIDDLESEGMENT : 0);
// no RIGHTSEGMENT
} else if(l == m_anchor.m_line) {
result.m_c1 = 0;
result.m_c2 = m_anchor.m_column - topLeft.m_column;
result.m_segments = ((result.m_c2>0 ) ? HAS_MIDDLESEGMENT : 0)
| ((result.m_c2<m_winSize.cx+1 ) ? HAS_RIGHTSEGMENT : 0);
// no LEFTSEGMENT
} else { // mark whole line
result.m_c1 = 0;
result.m_c2 = m_winSize.cx + 1;
result.m_segments = HAS_MIDDLESEGMENT;
}
} else {
result.m_segments = 0;
}
}
return result;
}
void TextView::paintTextSegment(CDC *pDC, int x, int y, int length, COLORREF tc, COLORREF bc, const TCHAR *s, int *textEndX) {
const TextPosition &topLeft = getTopLeft();
const int tx = m_characterSize.cx*(m_margin+x);
if(x + topLeft.m_column < (int)_tcsclen(s)) {
TCHAR tmp[4096];
_stprintf(tmp, _T("%-*.*s"), length, length, s + topLeft.m_column + x);
setColor(pDC, tc, bc);
pDC->TextOut(tx, y*m_characterSize.cy, tmp, length);
if(textEndX) *textEndX = tx + getTextExtent(*pDC, tmp).cx;
} else {
if(textEndX) *textEndX = tx;
}
}
void TextView::paintTextLine(CDC *pDC, int y, COLORREF tc, COLORREF bc, const TCHAR *s, const LineSegments &lineSeg) {
int length;
int textEnd;
COLORREF backgroundColorAfterText;
if(lineSeg.m_segments == 0) {
backgroundColorAfterText = bc;
length = m_winSize.cx + 1;
paintTextSegment(pDC, 0, y, length, tc, bc, s, &textEnd);
} else {
// pDC->MoveTo(m_characterSize.cx*m_margin, y*m_characterSize.cy);
// pDC->SetTextAlign(TA_LEFT | TA_UPDATECP);
backgroundColorAfterText = BLUE;
if(lineSeg.m_segments & HAS_LEFTSEGMENT) {
length = lineSeg.m_c1;
paintTextSegment(pDC, 0, y, length, tc, bc, s, (lineSeg.m_segments == HAS_LEFTSEGMENT) ? &textEnd : nullptr);
}
if(lineSeg.m_segments & HAS_MIDDLESEGMENT) {
const int left = max(0, lineSeg.m_c1);
length = max(0, lineSeg.m_c2 - left);
paintTextSegment(pDC, left, y, length, WHITE, BLUE, s, (lineSeg.m_segments & HAS_RIGHTSEGMENT) ? nullptr : &textEnd);
}
if(lineSeg.m_segments & HAS_RIGHTSEGMENT) {
const int left = max(0, lineSeg.m_c2);
length = max(0, m_winSize.cx + 1 - left);
paintTextSegment(pDC, left, y, length, tc, bc, s, &textEnd);
backgroundColorAfterText = bc;
}
// pDC->SetTextAlign(TA_LEFT | TA_NOUPDATECP);
}
const int width = m_workSize.cx - textEnd;
if(width > 0) {
pDC->FillSolidRect(textEnd, y*m_characterSize.cy, width, m_characterSize.cy, backgroundColorAfterText);
}
}
void TextView::paintTextLine(CDC *pDC, int y) {
const int line = getTopLine() + y;
if(line >= getLineCount()) {
return;
}
const DiffLine &df = m_diff->getDiffLine(line);
const int id = getId();
const LineSegments lineSeg = getLineSegments(line);
switch(df.getAttr()) {
case EQUALLINES :
if(getHighLightCompareEqual() && !df.linesAreEqual()) {
paintTextLine(pDC, y, BLACK, LIGHTGREY, df.getText(id).getString(), lineSeg);
} else {
paintTextLine(pDC, y, BLACK, WHITE , df.getText(id).getString(), lineSeg);
}
break;
case CHANGEDLINES :
paintTextLine( pDC, y, RED , GREY , df.getText(id).getString(), lineSeg);
break;
case DELETEDLINES :
if(id == 1) {
paintTextLine(pDC, y, GREY, GREY , EMPTYSTRING , lineSeg);
} else {
paintTextLine(pDC, y, BLUE, GREY , df.getText(id).getString(), lineSeg);
}
break;
case INSERTEDLINES:
if(id == 1) {
paintTextLine(pDC, y, GREEN,GREY , df.getText(id).getString(), lineSeg);
} else {
paintTextLine(pDC, y, GREY, GREY , EMPTYSTRING , lineSeg);
}
break;
}
}
// ----------------------------- String functions ------------------------------------
const TCHAR *TextView::getString(int index) const {
if(index < 0 || index >= m_diff->getLineCount()) {
return EMPTYSTRING;
}
return m_diff->getDiffLine(index).getText(getId()).getString();
}
const TCHAR *TextView::getCurrentString(int offset) const {
return getString(getCurrentLine() + offset);
}
int TextView::getFirstNonSpacePosition() const {
const TCHAR *str = getCurrentString();
for(const TCHAR *cp = str; *cp; cp++) {
if(!_istspace(*cp)) {
return (int)(cp - str);
}
}
return 0;
}
class OrigDiffFilter : public DiffFilter { // original doc-filtering but no lineFilter
private:
DiffFilter &m_f;
public:
OrigDiffFilter(DiffFilter &f) : m_f(f) {};
// no line filter
String lineFilter(const TCHAR *s) const {
return s;
}
// inherit original document-filtering
String docFilter( const TCHAR *s) const {
return m_f.docFilter(s);
}
bool hasLineFilter() const {
return false;
}
bool hasDocFilter() const {
return m_f.hasDocFilter();
}
DiffFilter *clone() const {
return new OrigDiffFilter(*this);
}
};
String TextView::getOrigString(int index) {
LineArray s;
OrigDiffFilter filter(getDocument()->m_filter);
m_diff->getDoc(getId()).getLines(filter,s);
return s[index];
}
String TextView::getCurrentOrigString(int offset) {
int index = getCurrentLine() + offset;
if(index >= m_diff->getLineCount() || index < 0) {
return EMPTYSTRING;
}
const DiffLine &dl = m_diff->getDiffLine(index);
const int l = dl.getText(getId()).getIndex();
return (l < 0) ? EMPTYSTRING : getOrigString(l);
}
static bool inline isWordLetter(_TUCHAR ch) {
return _istalpha(ch) || (ch == _T('_'));
}
String getWord(const String &str, UINT pos) {
if(pos >= str.length()) {
return EMPTYSTRING;
}
int start = pos, end = pos;
const _TUCHAR *s = (_TUCHAR*)str.cstr();
if(isWordLetter(s[pos])) {
while(start > 0 && isWordLetter(s[start-1])) {
start--;
}
while(isWordLetter(s[end+1])) {
end++;
}
} else if(_istdigit(s[pos])) {
while(start > 0 && _istdigit(s[start-1])) {
start--;
}
while(_istdigit(s[end+1])) {
end++;
}
} else if(s[pos] == _T('#')) {
while(start > 0 && s[start-1] == _T('#')) {
start--;
}
while(s[end+1] == _T('#')) {
end++;
}
} else if(_istspace(s[pos])) {
return EMPTYSTRING;
}
return substr(str, start, end-start+1);
}
String TextView::getCurrentWord() {
String line = getCurrentString();
return getWord(line, getCurrentColumn());
}
int TextView::getCurrentLineLength(int offset) {
return (int)_tcsclen(getCurrentString(offset));;
}
TCHAR TextView::getCurrentChar() {
const String &s = getCurrentString();
size_t x = getCurrentColumn();
if(x < s.length()) {
return s[x];
} else {
return 0;
}
}
int TextView::searchNextWordPos() {
_TUCHAR ch = getCurrentChar();
const String &s = getCurrentString();
size_t i = getCurrentColumn();
if(i >= s.length()) {
return (int)s.length();
}
if(isSpace(ch)) {
while(i < s.length() && isSpace(s[i])) {
i++;
}
} else if(isAlnum(ch)) {
while(i < s.length() && isAlnum((_TUCHAR)s[i])) {
i++;
}
} else if(_istcntrl(ch)) {
while(i < s.length() && _istcntrl((_TUCHAR)s[i])) {
i++;
}
} else if(_istpunct(ch)) {
while(i < s.length() && _istpunct((_TUCHAR)s[i])) {
i++;
}
} else if(i < s.length()) {
i++;
}
while(i < s.length() && isSpace(s[i])) {
i++;
}
return (int)i;
}
int TextView::searchPrevWordPos() {
const String &s = getCurrentString();
int i = getCurrentColumn();
if(i >= (int)s.length()) {
i = (int)s.length();
}
while(i > 0 && isSpace(s[i-1])) {
i--;
}
if(i == 0) {
return i;
}
const _TUCHAR ch = s[i-1];
if(isAlnum(ch)) {
while(i > 0 && isAlnum((_TUCHAR)s[i-1])) {
i--;
}
} else if(_istcntrl(ch)) {
while(i > 0 && _istcntrl((_TUCHAR)s[i-1])) {
i--;
}
} else if(_istpunct(ch)) {
while(i > 0 && _istpunct((_TUCHAR)s[i-1])) {
i--;
}
} else if(i > 0) {
i--;
}
return i;
}
// --------------------------------- Navigation function ------------------------------
void TextView::setTopLeft(const TextPosition &pos) {
setTopLine( pos.m_line);
setLineOffset(pos.m_column);
}
void TextView::handleAnchor() {
getDiffView().handleAnchor();
}
bool TextView::adjustLineOffset() {
const int cl = min(getPreferredColumn(), getCurrentLineLength());
if(cl < getLineOffset()) {
setLineOffset(cl-1);
return true;
} else if(cl > getRightOffset()) {
setLineOffset(cl - m_winSize.cx);
return true;
}
return false;
}
void TextView::home() {
handleAnchor();
const int firstNonSpace = getFirstNonSpacePosition();
if(getCurrentColumn() == firstNonSpace) {
if(firstNonSpace == 0) {
return;
}
setPreferredColumn(0);
} else {
setPreferredColumn(firstNonSpace);
}
if(adjustLineOffset()) {
repaintAll();
} else {
displayCaret();
}
}
void TextView::ctrlHome() {
handleAnchor();
if(getTopLeft() != TextPosition(0,0)) {
m_state.init();
repaintAll();
} else {
setPreferredColumn(0);
setCaretY(0);
displayCaret();
}
}
void TextView::end() {
handleAnchor();
setPreferredColumn(getCurrentLineLength());
if(getPreferredColumn() - m_winSize.cx > getLineOffset()) {
setLineOffset(getPreferredColumn() - m_winSize.cx);
repaintAll();
} else {
displayCaret();
}
}
void TextView::ctrlEnd() {
handleAnchor();
if(getTopLine() != getMaxTopLine()) {
setTopLeft(TextPosition(getMaxTopLine(), 0));
setPreferredColumn(0);
setCaretY(getMaxCaretY());
repaintAll();
} else {
setCaretY(getMaxCaretY());
displayCaret();
}
}
void TextView::lineUp() {
handleAnchor();
if(getCaretPosition().y > 0) {
setCaretY(getCaretPosition().y-1);
if(adjustLineOffset()) {
repaintAll();
} else {
displayCaret();
}
} else if(getTopLine() > 0) {
setTopLine(getTopLine()-1);
adjustLineOffset();
repaintAll();
}
}
void TextView::lineDown() {
handleAnchor();
if(getCaretPosition().y < getMaxCaretY()) {
setCaretY(getCaretPosition().y+1);
if(adjustLineOffset()) {
repaintAll();
} else {
displayCaret();
}
} else if(getTopLine() < getMaxTopLine()) {
setTopLine(getTopLine()+1);
adjustLineOffset();
repaintAll();
}
}
void TextView::pageUp() {
handleAnchor();
if(getTopLine() > 0) {
setTopLine(getTopLine() - m_winSize.cy);
adjustLineOffset();
repaintAll();
} else {
if(getCaretPosition().y > 0) {
setCaretY(0);
if(adjustLineOffset()) {
repaintAll();
} else {
displayCaret();
}
}
}
}
void TextView::pageDown() {
handleAnchor();
if(getTopLine() < getMaxTopLine()) {
setTopLine(getTopLine() + m_winSize.cy);
adjustLineOffset();
repaintAll();
} else {
if(getCaretPosition().y < getMaxCaretY()) {
setCaretY(getMaxCaretY());
if(adjustLineOffset()) {
repaintAll();
} else {
displayCaret();
}
}
}
}
void TextView::charLeft() {
handleAnchor();
const CPoint &caret = getCaretPosition();
if(caret.x > 0) {
setPreferredColumn(getCurrentColumn() - 1);
displayCaret();
} else if(getLineOffset() > 0) {
setLineOffset(getLineOffset()-1);
decrPreferredColumn();
repaintAll();
} else if(caret.y > 0 || getTopLine() > 0) {
setPreferredColumn(getCurrentLineLength(-1));
lineUp();
}
}
void TextView::charRight() {
handleAnchor();
const CPoint &caret = getCaretPosition();
if(getCurrentColumn() < getCurrentLineLength()) {
if(caret.x < m_winSize.cx) {
setPreferredColumn(getCurrentColumn() + 1);
displayCaret();
} else if(getLineOffset() < getMaxLineOffset()) {
setLineOffset(getLineOffset()+1);
incrPreferredColumn();
repaintAll();
}
} else if(getCurrentLine() < getLineCount()) {
setPreferredColumn(0);
lineDown();
}
}
void TextView::ctrlCharLeft() {
handleAnchor();
if(getCurrentColumn() == 0) {
if(getCurrentLine() == 0) {
return;
}
charLeft();
displayCaret();
}
setPreferredColumn(searchPrevWordPos());
if(getPreferredColumn() >= getLineOffset()) {
displayCaret();
} else {
setLineOffset(getPreferredColumn());
repaintAll();
}
}
void TextView::ctrlCharRight() {
handleAnchor();
if(getCurrentColumn() >= getCurrentLineLength()) {
if(getCurrentLine() == getLineCount()) {
return;
}
charRight();
displayCaret();
}
setPreferredColumn(searchNextWordPos());
if(getPreferredColumn() <= getRightOffset()) {
displayCaret();
} else if(getPreferredColumn() != getRightOffset()) {
setLineOffset(getPreferredColumn() - m_winSize.cx);
repaintAll();
}
}
void TextView::redrawBoth() {
TextView *partner = getPartner();
CDC *dc = GetDC();
CDC *pdc = partner ? partner->GetDC() : nullptr;
try {
if(!partner) {
OnDraw(dc);
} else if(isActive()) {
OnDraw(dc);
partner->OnDraw(pdc);
} else {
partner->OnDraw(pdc);
OnDraw(dc);
}
ReleaseDC(dc);
if(pdc) ReleaseDC(pdc);
} catch(...) {
ReleaseDC(dc);
if(pdc) ReleaseDC(pdc);
throw;
}
}
void TextView::setCaret(const MousePosition &p) {
setCaretY(p.y);
setPreferredColumn(minMax((int)p.x + getLineOffset(), 0, getCurrentLineLength()));
}
void TextView::scrollDown(int count) {
setTopLine(getTopLine() + count);
TextView *partner = getPartner();
if(partner) {
partner->setTopLine(getTopLine());
}
redrawBoth();
}
void TextView::scrollUp(int count) {
setTopLine(getTopLine() - count);
TextView *partner = getPartner();
if(partner) {
partner->setTopLine(getTopLine());
}
redrawBoth();
}
void TextView::scrollLeft(int count) {
setLineOffset(getLineOffset() - count);
TextView *partner = getPartner();
if(partner) {
partner->setLineOffset(getLineOffset());
}
redrawBoth();
}
void TextView::scrollRight(int count) {
setLineOffset(getLineOffset() + count);
TextView *partner = getPartner();
if(partner) {
partner->setLineOffset(getLineOffset());
}
redrawBoth();
}
int TextView::searchNextDiff() {
size_t pos = getCurrentLine();
const DiffLineArray &lines = m_diff->getDiffLines();
if(pos < lines.size()) {
if(lines[pos].getAttr() != EQUALLINES) {
for(pos++; pos < lines.size(); pos++) {
if(lines[pos].getAttr() == EQUALLINES) {
break;
}
}
}
}
size_t i;
for(i = pos; i < lines.size(); i++) {
if(lines[i].getAttr() != EQUALLINES) {
break;
}
}
if(i < lines.size()) {
return (int)i;
}
return -1;
}
int TextView::searchPrevDiff() {
int pos = getCurrentLine();
const DiffLineArray &lines = m_diff->getDiffLines();
if(pos > 0) {
if(lines[pos].getAttr() != EQUALLINES) {
for(pos--;pos >= 0; pos--) {
if(lines[pos].getAttr() == EQUALLINES) {
break;
}
}
}
}
int i;
for(i = pos; i >= 0; i--) {
if(lines[i].getAttr() != EQUALLINES) {
break;
}
}
if(i == 0) {
return i;
}
for(;i > 0; i--) {
if(lines[i].getAttr() == EQUALLINES) {
i++;
break;
}
}
return i;
}
void TextView::nextDiff() {
resetAnchor();
if(hasPartner()) {
getPartner()->resetAnchor();
}
const int line = searchNextDiff();
if(line < 0) {
return;
}
if(line < getBottomLine()) {
setCaretY(line - getTopLine());
setLineOffset(0);
setPreferredColumn(0);
repaintAll();
} else {
setTopLine(line - m_winSize.cy/2);
setCaretY(line - getTopLine());
setLineOffset(0);
setPreferredColumn(0);
repaintAll();
}
}
void TextView::prevDiff() {
resetAnchor();
if(hasPartner()) {
getPartner()->resetAnchor();
}
const int line = searchPrevDiff();
if(line < 0) {
return;
}
if(line >= getTopLine()) {
setCaretY(line - getTopLine());
setLineOffset(0);
setPreferredColumn(0);
repaintAll();
} else {
setTopLine(line - m_winSize.cy/2);
setCaretY(line - getTopLine());
setLineOffset(0);
setPreferredColumn(0);
repaintAll();
}
}
void TextView::gotoFoundPosition(const TextPositionPair &tp) {
m_anchor = tp.m_pos2;
m_lastAnchor.reset();
gotoPos(tp.m_pos1);
}
void TextView::gotoLine(UINT line) {
gotoPos(TextPosition(line, 0));
}
void TextView::gotoPos(const TextPosition &pos) {
bool repaint = false;
if((pos.m_line < getTopLine()) || (pos.m_line >= getBottomLine())) {
setTopLine(pos.m_line - m_winSize.cy/2);
repaint = true;
}
setCaretY(pos.m_line - getTopLine());
setPreferredColumn(pos.m_column);
const int textr = max(m_anchor.m_column, getPreferredColumn());
if(getPreferredColumn() < getLineOffset() || textr >= getRightOffset()) {
if(textr - getPreferredColumn() > m_winSize.cx) {
setLineOffset(getPreferredColumn());
} else {
setLineOffset(min(getPreferredColumn() - m_winSize.cx/2,textr - m_winSize.cx));
}
repaint = true;
}
if(repaint) {
TextView *partner = getPartner();
if(partner) {
partner->setLineOffset(getLineOffset());
}
redrawBoth();
} else {
displayCaret();
}
}
// -------------------------------------- misc ------------------------------------
CWinDiffView &TextView::getDiffView() {
return *((CWinDiffView*)GetParent());
}
TextView *TextView::getPartner() {
CWinDiffView *view = getDiffView().getPartner();
return (view == nullptr) ? nullptr : &view->m_textView;
}
CWinDiffDoc *TextView::getDocument() {
return getDiffView().GetDocument();
}
bool TextView::hasPartner() {
return getPartner() != nullptr;
}
int TextView::getMaxCaretX() {
const int cl = getCurrentLineLength();
if(cl > getRightOffset()) {
return m_winSize.cx;
} else {
return cl - getLineOffset();
}
}
int TextView::getMaxCaretY() {
if(getLineCount() > getBottomLine()) {
return m_winSize.cy - 1;
} else {
return getLineCount() - getTopLine() - 1;
}
}
void TextView::activatePartner() {
TextView *partner = getPartner();
if(partner == nullptr) {
return;
}
setActive(false);
partner->setActive(true);
}
void TextView::setActive(bool active) {
if(!isCreated()) return;
setFlagValue(VIEW_ISACTIVE, active);
if(active) {
displayCaret();
} else {
destroyCaret();
}
}
String TextView::getTextLines(const TextPositionPair &tp) {
int id = getId();
String res;
if(tp.m_pos1.m_line == tp.m_pos2.m_line) {
res = substr(getString(tp.m_pos1.m_line),tp.m_pos1.m_column,tp.m_pos2.m_column-tp.m_pos1.m_column);
} else {
res = getString(tp.m_pos1.m_line);
res = substr(res,tp.m_pos1.m_column,res.length());
int y;
for(y = tp.m_pos1.m_line + 1; y < tp.m_pos2.m_line; y++) {
res += String(_T("\r\n")) + getString(y);
}
if(y == tp.m_pos2.m_line) {
res += String(_T("\r\n")) + left(getString(y),tp.m_pos2.m_column);
}
}
return res;
}
String TextView::getSelectedText() {
if(m_anchor.isEmpty()) {
return EMPTYSTRING;
}
return getTextLines(getSelectedRange());
}
TextPositionPair TextView::getSelectedRange() const {
if(m_anchor.isEmpty()) {
return TextPositionPair();
} else {
const TextPosition cp = getCurrentPos();
return (cp <= m_anchor) ? TextPositionPair(cp, m_anchor) : TextPositionPair(m_anchor, cp);
}
}
bool TextView::hasSelection() const {
const TextPositionPair tp = getSelectedRange();
return !tp.isEmpty() && tp.m_pos1 != tp.m_pos2;
}
TextPosition TextView::getTextPosFromScreenPos(const CPoint &p) {
CRect rect;
GetWindowRect(&rect);
if(!rect.PtInRect(p)) {
return TextPosition();
}
MousePosition m = getCaretPosFromScreenPos(p);
const TextPosition &topLeft = getTopLeft();
return TextPosition(m.y + topLeft.m_line, m.x + topLeft.m_column);
}
MousePosition TextView::getCaretPosFromScreenPos(const CPoint &p) {
CRect rect;
GetWindowRect(&rect);
int cx = (p.x - rect.left) / m_characterSize.cx - m_margin;
int cy = (p.y - rect.top ) / m_characterSize.cy;
return MousePosition(CPoint(cx,cy));
}
int TextView::getProgressiveDistance(int distance) {
int sign = 1;
if(distance < 0) {
sign = -1;
distance = -distance;
}
if(distance < 20) {
distance = 1;
} else if(distance < 40) {
distance = 5;
} else if(distance < 60) {
distance = 10;
} else {
distance = 50;
}
return sign * distance;
}
MousePosition TextView::getNearestCaretPos(const CPoint &p) {
CRect rect;
GetWindowRect(&rect);
if(rect.PtInRect(p)) {
return getCaretPosFromScreenPos(p);
}
CPoint newP;
CPoint distance;
if(p.x < rect.left) {
distance.x = getProgressiveDistance(p.x - rect.left);
newP.x = rect.left;
} else if(p.x > rect.right-1) {
distance.x = getProgressiveDistance(p.x - rect.right);
newP.x = rect.right-1;
} else {
distance.x = 0;
newP.x = p.x;
}
if(p.y < rect.top) {
distance.y = getProgressiveDistance(p.y - rect.top);
newP.y = rect.top;
} else if(p.y > rect.bottom-1) {
distance.y = getProgressiveDistance(p.y - rect.bottom);
newP.y = rect.bottom-1;
} else {
distance.y = 0;
newP.y = p.y;
}
return MousePosition(getCaretPosFromScreenPos(newP),distance);
}
void TextView::dropAnchor() {
if(m_anchor.isEmpty()) {
setAnchor();
}
}
void TextView::resetAnchor() {
if(!m_anchor.isEmpty()) {
m_anchor.reset();
CClientDC dc(this);
unMarkSelectedText(&dc);
}
}
void TextView::selectAll() {
if(m_diff->isEmpty()) {
return;
}
ctrlEnd();
const DiffLine &df = m_diff->getDiffLines().last();
const int len = (int)_tcsclen(df.getText(getId()).getString());
m_anchor.set(getLineCount()-1, len);
gotoPos(TextPosition(0,0));
}
void TextView::createWorkBitmap(int w, int h) {
if(m_workBitmap.m_hObject != nullptr) {
m_workDC.SelectObject((CBitmap*)nullptr);
m_workBitmap.DeleteObject();
}
CClientDC screen(this);
m_workSize.cx = w; m_workSize.cy = h;
const int depth = screen.GetDeviceCaps(BITSPIXEL);
m_workBitmap.CreateBitmap(w,h,screen.GetDeviceCaps(PLANES),depth,nullptr);
m_workDC.SelectObject(&m_workBitmap);
clearDC(&m_workDC);
}
void TextView::updateWindowSize(int cx, int cy) {
CDC *pDC = GetDC();
SELECTFONT(*pDC);
// pDC->SetMapMode(MM_TEXT);
TEXTMETRIC tm;
pDC->GetTextMetrics(&tm);
ReleaseDC(pDC);
m_characterSize.cy = tm.tmHeight;
m_characterSize.cx = tm.tmAveCharWidth; // tmMaxCharWidth;
setCaretSize(CSize(max(2, m_characterSize.cy / 8), m_characterSize.cy));
CSize aSize;
aSize.cy = m_characterSize.cy * 4 / 5;
aSize.cx = aSize.cy * 80 / 96; // size of raw Arrowbitmap = (80,96)
setArrowSize(aSize);
m_winSize.cx = (cx-m_caretSize.cx) / m_characterSize.cx - m_margin; // -4 to make caret always visible
if(m_winSize.cx < 0) {
m_winSize.cx = 0;
}
m_winSize.cy = cy / m_characterSize.cy;
m_maxOffset.m_column = max(0, m_diff->getMaxLineLength() - m_winSize.cx);
m_maxOffset.m_line = max(0, getLineCount() - m_winSize.cy);
setTopLine(getTopLine());
setCaretY(getCaretPosition().y);
createWorkBitmap(cx, cy);
}
void TextView::updateWindowSize() {
const CSize sz = getClientRect(this).Size();
updateWindowSize(sz.cx, sz.cy);
}
bool TextView::attributeMatch(const FindParameters ¶m, int index) const {
if(param.m_diffOnly) {
return getLineAttribute(index) != EQUALLINES;
} else if(param.m_nonDiffOnly) {
return getLineAttribute(index) == EQUALLINES;
} else {
return true;
}
}
// --------------------------------- debug functions -----------------------------------
#if defined(_DEBUG)
String LineSegments ::toString() const {
if(m_segments) {
return format(_T("c1:%3d, c2:%3d, %s"), m_c1, m_c2, flagsToString(m_segments).cstr());
} else {
return _T("empty");
}
}
String LineSegments::flagsToString(unsigned char flags) { // static
String result;
const TCHAR *delim = nullptr;
#define ADDIFSET(f) { if(flags&HAS_##f) { if(delim) result += delim; else delim = _T(" | "); result += #f; } }
ADDIFSET( LEFTSEGMENT );
ADDIFSET( MIDDLESEGMENT );
ADDIFSET( RIGHTSEGMENT );
return result;
}
#undef ADDIFSET
String ViewFlags::toString() const {
String result;
const TCHAR *delim = nullptr;
#define ADDIFSET(f) { if(contains(f)) { if(delim) result += delim; else delim = _T(" | "); result += #f; } }
ADDIFSET( VIEW_ISCREATED );
ADDIFSET( VIEW_ISACTIVE );
ADDIFSET( CARET_EXIST );
ADDIFSET( CARET_VISIBLE );
ADDIFSET( SHOW_1000SEPARATOR );
ADDIFSET( HIGHLIGhT_COMPAREEQUAL );
return result;
}
#endif
| [
"jesper.gr.mikkelsen@gmail.com"
] | jesper.gr.mikkelsen@gmail.com |
d56fb3278adb49c515c945310f93209e7ad16c9a | 2b210288fb83c773c7a2afa4d874d35f6a000699 | /chromium-webcl/src/chrome/browser/prefs/browser_prefs.cc | 62c5bc7d2bd41e88a1e60abc8e585e1e1942ce32 | [
"BSD-3-Clause"
] | permissive | mychangle123/Chromium-WebCL | 3462ff60a6ef3144729763167be6308921e4195d | 2b25f42a0a239127ed39a159c377be58b3102b17 | HEAD | 2016-09-16T10:47:58.247722 | 2013-10-31T05:48:50 | 2013-10-31T05:48:50 | 14,553,669 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 19,233 | cc | // Copyright 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/prefs/browser_prefs.h"
#include "apps/prefs.h"
#include "base/prefs/pref_registry_simple.h"
#include "base/prefs/pref_service.h"
#include "chrome/browser/about_flags.h"
#include "chrome/browser/accessibility/invert_bubble_prefs.h"
#include "chrome/browser/background/background_mode_manager.h"
#include "chrome/browser/bookmarks/bookmark_prompt_prefs.h"
#include "chrome/browser/bookmarks/bookmark_utils.h"
#include "chrome/browser/browser_process_impl.h"
#include "chrome/browser/browser_shutdown.h"
#include "chrome/browser/chrome_content_browser_client.h"
#include "chrome/browser/component_updater/recovery_component_installer.h"
#include "chrome/browser/content_settings/host_content_settings_map.h"
#include "chrome/browser/custom_handlers/protocol_handler_registry.h"
#include "chrome/browser/devtools/devtools_window.h"
#include "chrome/browser/download/chrome_download_manager_delegate.h"
#include "chrome/browser/download/download_prefs.h"
#include "chrome/browser/extensions/api/commands/command_service.h"
#include "chrome/browser/extensions/api/tabs/tabs_api.h"
#include "chrome/browser/extensions/component_loader.h"
#include "chrome/browser/extensions/extension_prefs.h"
#include "chrome/browser/extensions/extension_web_ui.h"
#include "chrome/browser/external_protocol/external_protocol_handler.h"
#include "chrome/browser/first_run/first_run.h"
#include "chrome/browser/geolocation/geolocation_prefs.h"
#include "chrome/browser/google/google_url_tracker.h"
#include "chrome/browser/google/google_url_tracker_factory.h"
#include "chrome/browser/gpu/gl_string_manager.h"
#include "chrome/browser/gpu/gpu_mode_manager.h"
#include "chrome/browser/intranet_redirect_detector.h"
#include "chrome/browser/io_thread.h"
#include "chrome/browser/managed_mode/managed_mode.h"
#include "chrome/browser/managed_mode/managed_user_service.h"
#include "chrome/browser/media/media_capture_devices_dispatcher.h"
#include "chrome/browser/media/media_stream_devices_controller.h"
#include "chrome/browser/metrics/metrics_log.h"
#include "chrome/browser/metrics/metrics_service.h"
#include "chrome/browser/metrics/variations/variations_service.h"
#include "chrome/browser/net/http_server_properties_manager.h"
#include "chrome/browser/net/net_pref_observer.h"
#include "chrome/browser/net/predictor.h"
#include "chrome/browser/net/ssl_config_service_manager.h"
#include "chrome/browser/notifications/desktop_notification_service.h"
#include "chrome/browser/notifications/notification_prefs_manager.h"
#include "chrome/browser/password_manager/password_generation_manager.h"
#include "chrome/browser/password_manager/password_manager.h"
#include "chrome/browser/pepper_flash_settings_manager.h"
#include "chrome/browser/plugins/plugin_finder.h"
#include "chrome/browser/prefs/incognito_mode_prefs.h"
#include "chrome/browser/prefs/pref_service_syncable.h"
#include "chrome/browser/prefs/session_startup_pref.h"
#include "chrome/browser/printing/cloud_print/cloud_print_url.h"
#include "chrome/browser/printing/print_dialog_cloud.h"
#include "chrome/browser/profiles/chrome_version_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_impl.h"
#include "chrome/browser/profiles/profile_info_cache.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/renderer_host/pepper/device_id_fetcher.h"
#include "chrome/browser/renderer_host/web_cache_manager.h"
#include "chrome/browser/search/search.h"
#include "chrome/browser/search_engines/template_url_prepopulate_data.h"
#include "chrome/browser/signin/signin_manager_factory.h"
#include "chrome/browser/sync/invalidations/invalidator_storage.h"
#include "chrome/browser/sync/sync_prefs.h"
#include "chrome/browser/task_manager/task_manager.h"
#include "chrome/browser/translate/translate_prefs.h"
#include "chrome/browser/ui/alternate_error_tab_observer.h"
#include "chrome/browser/ui/app_list/app_list_service.h"
#include "chrome/browser/ui/autofill/autofill_dialog_controller_impl.h"
#include "chrome/browser/ui/browser_ui_prefs.h"
#include "chrome/browser/ui/network_profile_bubble.h"
#include "chrome/browser/ui/prefs/prefs_tab_helper.h"
#include "chrome/browser/ui/search_engines/keyword_editor_controller.h"
#include "chrome/browser/ui/startup/autolaunch_prompt.h"
#include "chrome/browser/ui/startup/default_browser_prompt.h"
#include "chrome/browser/ui/tabs/pinned_tab_codec.h"
#include "chrome/browser/ui/webui/extensions/extension_settings_handler.h"
#include "chrome/browser/ui/webui/flags_ui.h"
#include "chrome/browser/ui/webui/instant_ui.h"
#include "chrome/browser/ui/webui/ntp/new_tab_ui.h"
#include "chrome/browser/ui/webui/plugins_ui.h"
#include "chrome/browser/ui/webui/print_preview/sticky_settings.h"
#include "chrome/browser/ui/webui/sync_promo/sync_promo_ui.h"
#include "chrome/browser/ui/window_snapshot/window_snapshot.h"
#include "chrome/browser/upgrade_detector.h"
#include "chrome/browser/web_resource/promo_resource_service.h"
#include "chrome/common/pref_names.h"
#include "components/autofill/browser/autofill_manager.h"
#include "components/user_prefs/pref_registry_syncable.h"
#include "content/public/browser/render_process_host.h"
#if defined(ENABLE_CONFIGURATION_POLICY)
#include "chrome/browser/policy/browser_policy_connector.h"
#include "chrome/browser/policy/policy_statistics_collector.h"
#include "chrome/browser/policy/url_blacklist_manager.h"
#endif
#if defined(OS_MACOSX)
#include "chrome/browser/ui/cocoa/confirm_quit.h"
#endif
#if defined(TOOLKIT_VIEWS)
#include "chrome/browser/ui/browser_view_prefs.h"
#include "chrome/browser/ui/tabs/tab_strip_layout_type_prefs.h"
#endif
#if defined(TOOLKIT_GTK)
#include "chrome/browser/ui/gtk/browser_window_gtk.h"
#endif
#if defined(OS_CHROMEOS)
#include "chrome/browser/chromeos/app_mode/kiosk_app_manager.h"
#include "chrome/browser/chromeos/audio/audio_handler.h"
#include "chrome/browser/chromeos/audio/audio_pref_handler_impl.h"
#include "chrome/browser/chromeos/customization_document.h"
#include "chrome/browser/chromeos/display/display_preferences.h"
#include "chrome/browser/chromeos/login/login_utils.h"
#include "chrome/browser/chromeos/login/oauth2_login_manager.h"
#include "chrome/browser/chromeos/login/startup_utils.h"
#include "chrome/browser/chromeos/login/user_image_manager.h"
#include "chrome/browser/chromeos/login/user_manager.h"
#include "chrome/browser/chromeos/login/wallpaper_manager.h"
#include "chrome/browser/chromeos/policy/auto_enrollment_client.h"
#include "chrome/browser/chromeos/policy/device_cloud_policy_manager_chromeos.h"
#include "chrome/browser/chromeos/policy/device_status_collector.h"
#include "chrome/browser/chromeos/preferences.h"
#include "chrome/browser/chromeos/proxy_config_service_impl.h"
#include "chrome/browser/chromeos/settings/device_oauth2_token_service.h"
#include "chrome/browser/chromeos/settings/device_settings_cache.h"
#include "chrome/browser/chromeos/status/data_promo_notification.h"
#include "chrome/browser/chromeos/system/automatic_reboot_manager.h"
#include "chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api.h"
#else
#include "chrome/browser/extensions/default_apps.h"
#endif
#if defined(USE_ASH)
#include "chrome/browser/ui/ash/chrome_launcher_prefs.h"
#endif
#if !defined(OS_ANDROID)
#include "chrome/browser/chrome_to_mobile_service.h"
#endif
#if defined(OS_ANDROID)
#include "chrome/browser/ui/webui/ntp/android/promo_handler.h"
#endif
#if defined(ENABLE_PLUGIN_INSTALLATION)
#include "chrome/browser/plugins/plugins_resource_service.h"
#endif
namespace {
enum MigratedPreferences {
NO_PREFS = 0,
DNS_PREFS = 1 << 0,
WINDOWS_PREFS = 1 << 1,
GOOGLE_URL_TRACKER_PREFS = 1 << 2,
};
// A previous feature (see
// chrome/browser/protector/protected_prefs_watcher.cc in source
// control history) used this string as a prefix for various prefs it
// registered. We keep it here for now to clear out those old prefs in
// MigrateUserPrefs.
const char kBackupPref[] = "backup";
} // namespace
namespace chrome {
void RegisterLocalState(PrefRegistrySimple* registry) {
// Prefs in Local State.
registry->RegisterIntegerPref(prefs::kMultipleProfilePrefMigration, 0);
// Please keep this list alphabetized.
AppListService::RegisterPrefs(registry);
apps::RegisterPrefs(registry);
browser_shutdown::RegisterPrefs(registry);
BrowserProcessImpl::RegisterPrefs(registry);
RegisterScreenshotPrefs(registry);
ExternalProtocolHandler::RegisterPrefs(registry);
FlagsUI::RegisterPrefs(registry);
geolocation::RegisterPrefs(registry);
GLStringManager::RegisterPrefs(registry);
GpuModeManager::RegisterPrefs(registry);
IntranetRedirectDetector::RegisterPrefs(registry);
IOThread::RegisterPrefs(registry);
KeywordEditorController::RegisterPrefs(registry);
MetricsLog::RegisterPrefs(registry);
MetricsService::RegisterPrefs(registry);
PrefProxyConfigTrackerImpl::RegisterPrefs(registry);
ProfileInfoCache::RegisterPrefs(registry);
ProfileManager::RegisterPrefs(registry);
PromoResourceService::RegisterPrefs(registry);
RegisterPrefsForRecoveryComponent(registry);
SigninManagerFactory::RegisterPrefs(registry);
SSLConfigServiceManager::RegisterPrefs(registry);
UpgradeDetector::RegisterPrefs(registry);
WebCacheManager::RegisterPrefs(registry);
chrome_variations::VariationsService::RegisterPrefs(registry);
#if defined(ENABLE_PLUGINS)
PluginFinder::RegisterPrefs(registry);
#endif
#if defined(ENABLE_PLUGIN_INSTALLATION)
PluginsResourceService::RegisterPrefs(registry);
#endif
#if defined(ENABLE_CONFIGURATION_POLICY)
policy::BrowserPolicyConnector::RegisterPrefs(registry);
policy::PolicyStatisticsCollector::RegisterPrefs(registry);
#endif
#if defined(ENABLE_NOTIFICATIONS)
NotificationPrefsManager::RegisterPrefs(registry);
#endif
#if defined(ENABLE_TASK_MANAGER)
TaskManager::RegisterPrefs(registry);
#endif // defined(ENABLE_TASK_MANAGER)
#if defined(TOOLKIT_VIEWS)
RegisterBrowserViewPrefs(registry);
RegisterTabStripLayoutTypePrefs(registry);
#endif
#if !defined(OS_ANDROID)
BackgroundModeManager::RegisterPrefs(registry);
RegisterBrowserPrefs(registry);
RegisterDefaultBrowserPromptPrefs(registry);
ManagedMode::RegisterPrefs(registry);
#endif
#if defined(OS_CHROMEOS)
chromeos::AudioPrefHandlerImpl::RegisterPrefs(registry);
chromeos::DataPromoNotification::RegisterPrefs(registry);
chromeos::DeviceOAuth2TokenService::RegisterPrefs(registry);
chromeos::device_settings_cache::RegisterPrefs(registry);
chromeos::language_prefs::RegisterPrefs(registry);
chromeos::KioskAppManager::RegisterPrefs(registry);
chromeos::LoginUtils::RegisterPrefs(registry);
chromeos::Preferences::RegisterPrefs(registry);
chromeos::ProxyConfigServiceImpl::RegisterPrefs(registry);
chromeos::RegisterDisplayLocalStatePrefs(registry);
chromeos::ServicesCustomizationDocument::RegisterPrefs(registry);
chromeos::system::AutomaticRebootManager::RegisterPrefs(registry);
chromeos::UserImageManager::RegisterPrefs(registry);
chromeos::UserManager::RegisterPrefs(registry);
chromeos::WallpaperManager::RegisterPrefs(registry);
chromeos::StartupUtils::RegisterPrefs(registry);
policy::AutoEnrollmentClient::RegisterPrefs(registry);
policy::DeviceStatusCollector::RegisterPrefs(registry);
#endif
#if defined(OS_MACOSX)
confirm_quit::RegisterLocalState(registry);
#endif
}
void RegisterUserPrefs(PrefRegistrySyncable* registry) {
// User prefs. Please keep this list alphabetized.
AlternateErrorPageTabObserver::RegisterUserPrefs(registry);
autofill::AutofillDialogControllerImpl::RegisterUserPrefs(registry);
autofill::AutofillManager::RegisterUserPrefs(registry);
BookmarkPromptPrefs::RegisterUserPrefs(registry);
bookmark_utils::RegisterUserPrefs(registry);
browser_sync::SyncPrefs::RegisterUserPrefs(registry);
chrome::RegisterInstantUserPrefs(registry);
ChromeContentBrowserClient::RegisterUserPrefs(registry);
ChromeDownloadManagerDelegate::RegisterUserPrefs(registry);
ChromeVersionService::RegisterUserPrefs(registry);
chrome_browser_net::HttpServerPropertiesManager::RegisterUserPrefs(
registry);
chrome_browser_net::Predictor::RegisterUserPrefs(registry);
DownloadPrefs::RegisterUserPrefs(registry);
extensions::ComponentLoader::RegisterUserPrefs(registry);
extensions::ExtensionPrefs::RegisterUserPrefs(registry);
ExtensionWebUI::RegisterUserPrefs(registry);
first_run::RegisterUserPrefs(registry);
HostContentSettingsMap::RegisterUserPrefs(registry);
IncognitoModePrefs::RegisterUserPrefs(registry);
InstantUI::RegisterUserPrefs(registry);
browser_sync::InvalidatorStorage::RegisterUserPrefs(registry);
MediaCaptureDevicesDispatcher::RegisterUserPrefs(registry);
MediaStreamDevicesController::RegisterUserPrefs(registry);
NetPrefObserver::RegisterUserPrefs(registry);
NewTabUI::RegisterUserPrefs(registry);
PasswordGenerationManager::RegisterUserPrefs(registry);
PasswordManager::RegisterUserPrefs(registry);
PrefProxyConfigTrackerImpl::RegisterUserPrefs(registry);
PrefsTabHelper::RegisterUserPrefs(registry);
Profile::RegisterUserPrefs(registry);
ProfileImpl::RegisterUserPrefs(registry);
PromoResourceService::RegisterUserPrefs(registry);
ProtocolHandlerRegistry::RegisterUserPrefs(registry);
RegisterBrowserUserPrefs(registry);
SessionStartupPref::RegisterUserPrefs(registry);
TemplateURLPrepopulateData::RegisterUserPrefs(registry);
TranslatePrefs::RegisterUserPrefs(registry);
#if defined(ENABLE_CONFIGURATION_POLICY)
policy::BrowserPolicyConnector::RegisterUserPrefs(registry);
policy::URLBlacklistManager::RegisterUserPrefs(registry);
#endif
#if defined(ENABLE_MANAGED_USERS)
ManagedUserService::RegisterUserPrefs(registry);
#endif
#if defined(ENABLE_NOTIFICATIONS)
DesktopNotificationService::RegisterUserPrefs(registry);
#endif
#if defined(TOOLKIT_VIEWS)
RegisterInvertBubbleUserPrefs(registry);
#elif defined(TOOLKIT_GTK)
BrowserWindowGtk::RegisterUserPrefs(registry);
#endif
#if defined(OS_ANDROID)
PromoHandler::RegisterUserPrefs(registry);
#endif
#if defined(USE_ASH)
ash::RegisterChromeLauncherUserPrefs(registry);
#endif
#if !defined(OS_ANDROID)
TabsCaptureVisibleTabFunction::RegisterUserPrefs(registry);
ChromeToMobileService::RegisterUserPrefs(registry);
DeviceIDFetcher::RegisterUserPrefs(registry);
DevToolsWindow::RegisterUserPrefs(registry);
extensions::CommandService::RegisterUserPrefs(registry);
ExtensionSettingsHandler::RegisterUserPrefs(registry);
PepperFlashSettingsManager::RegisterUserPrefs(registry);
PinnedTabCodec::RegisterUserPrefs(registry);
PluginsUI::RegisterUserPrefs(registry);
CloudPrintURL::RegisterUserPrefs(registry);
print_dialog_cloud::RegisterUserPrefs(registry);
printing::StickySettings::RegisterUserPrefs(registry);
RegisterAutolaunchUserPrefs(registry);
SyncPromoUI::RegisterUserPrefs(registry);
#endif
#if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
default_apps::RegisterUserPrefs(registry);
#endif
#if defined(OS_CHROMEOS)
chromeos::OAuth2LoginManager::RegisterUserPrefs(registry);
chromeos::Preferences::RegisterUserPrefs(registry);
chromeos::ProxyConfigServiceImpl::RegisterUserPrefs(registry);
extensions::EnterprisePlatformKeysPrivateChallengeUserKeyFunction::
RegisterUserPrefs(registry);
FlagsUI::RegisterUserPrefs(registry);
#endif
#if defined(OS_WIN)
NetworkProfileBubble::RegisterUserPrefs(registry);
#endif
// Prefs registered only for migration (clearing or moving to a new
// key) go here.
registry->RegisterDictionaryPref(kBackupPref, new DictionaryValue(),
PrefRegistrySyncable::UNSYNCABLE_PREF);
}
void MigrateUserPrefs(Profile* profile) {
PrefService* prefs = profile->GetPrefs();
// Cleanup prefs from now-removed protector feature.
prefs->ClearPref(kBackupPref);
PrefsTabHelper::MigrateUserPrefs(prefs);
PromoResourceService::MigrateUserPrefs(prefs);
TranslatePrefs::MigrateUserPrefs(prefs);
}
void MigrateBrowserPrefs(Profile* profile, PrefService* local_state) {
// Copy pref values which have been migrated to user_prefs from local_state,
// or remove them from local_state outright, if copying is not required.
int current_version =
local_state->GetInteger(prefs::kMultipleProfilePrefMigration);
PrefRegistrySimple* registry = static_cast<PrefRegistrySimple*>(
local_state->DeprecatedGetPrefRegistry());
if (!(current_version & DNS_PREFS)) {
registry->RegisterListPref(prefs::kDnsStartupPrefetchList);
local_state->ClearPref(prefs::kDnsStartupPrefetchList);
registry->RegisterListPref(prefs::kDnsHostReferralList);
local_state->ClearPref(prefs::kDnsHostReferralList);
current_version |= DNS_PREFS;
local_state->SetInteger(prefs::kMultipleProfilePrefMigration,
current_version);
}
PrefService* user_prefs = profile->GetPrefs();
if (!(current_version & WINDOWS_PREFS)) {
registry->RegisterIntegerPref(prefs::kDevToolsHSplitLocation, -1);
if (local_state->HasPrefPath(prefs::kDevToolsHSplitLocation)) {
user_prefs->SetInteger(
prefs::kDevToolsHSplitLocation,
local_state->GetInteger(prefs::kDevToolsHSplitLocation));
}
local_state->ClearPref(prefs::kDevToolsHSplitLocation);
registry->RegisterDictionaryPref(prefs::kBrowserWindowPlacement);
if (local_state->HasPrefPath(prefs::kBrowserWindowPlacement)) {
const PrefService::Preference* pref =
local_state->FindPreference(prefs::kBrowserWindowPlacement);
DCHECK(pref);
user_prefs->Set(prefs::kBrowserWindowPlacement,
*(pref->GetValue()));
}
local_state->ClearPref(prefs::kBrowserWindowPlacement);
current_version |= WINDOWS_PREFS;
local_state->SetInteger(prefs::kMultipleProfilePrefMigration,
current_version);
}
if (!(current_version & GOOGLE_URL_TRACKER_PREFS)) {
GoogleURLTrackerFactory::GetInstance()->RegisterUserPrefsOnProfile(profile);
registry->RegisterStringPref(prefs::kLastKnownGoogleURL,
GoogleURLTracker::kDefaultGoogleHomepage);
if (local_state->HasPrefPath(prefs::kLastKnownGoogleURL)) {
user_prefs->SetString(prefs::kLastKnownGoogleURL,
local_state->GetString(prefs::kLastKnownGoogleURL));
}
local_state->ClearPref(prefs::kLastKnownGoogleURL);
registry->RegisterStringPref(prefs::kLastPromptedGoogleURL,
std::string());
if (local_state->HasPrefPath(prefs::kLastPromptedGoogleURL)) {
user_prefs->SetString(
prefs::kLastPromptedGoogleURL,
local_state->GetString(prefs::kLastPromptedGoogleURL));
}
local_state->ClearPref(prefs::kLastPromptedGoogleURL);
current_version |= GOOGLE_URL_TRACKER_PREFS;
local_state->SetInteger(prefs::kMultipleProfilePrefMigration,
current_version);
}
}
} // namespace chrome
| [
"ZhangPeiXuan.CN@Gmail.COM"
] | ZhangPeiXuan.CN@Gmail.COM |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.