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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
89e6c611a20c593f167394f259e1627d4fa2f538 | 76456c02e3e4ddf2ea713894bcee8b98f12a4b00 | /board-package-source/libraries/ArduboyFX/examples/chompies/chompies.ino | 6034578f252c86ee1d23e590d1e7fe6d256da8aa | [
"CC0-1.0"
]
| permissive | serisman/Arduboy-homemade-package | fcc836740fafdcf41feae2692378b968b9b9ba62 | 6acc22dfdae34487f8698e95c1a3ce936ddc8fbb | refs/heads/master | 2021-11-24T06:46:14.461716 | 2021-08-22T11:58:35 | 2021-08-22T11:58:35 | 148,209,248 | 0 | 0 | null | 2018-09-10T19:39:45 | 2018-09-10T19:39:44 | null | UTF-8 | C++ | false | false | 4,012 | ino | /* *****************************************************************************
* FX drawBitmap test v1.3 by Mr.Blinky Apr 2019-May 2021 licenced under CC0
* *****************************************************************************
*
* The map and whale images used in this example were made by 2bitcrook and are
* licenced under CC-BY-NC-SA licence.
* This test depend on the file fxdata.bin being uploaded to the external FX flash
* chip using the uploader-gui.py or flash-writer.py Python script in the
* development area. When using the flash writer script. Use the following command:
*
* python flash-writer.py -d fxdata.bin
*
* This example uses a 816 by 368 pixel image as background and a
* 107 x 69 image for masked sprite. Both can be moved around using the button combos
* below. This example also shows how you can make use of the different draw modes.
*
*
* A Invert the while sprite from black to white and vice versa
* B Show or hide the coordinates in the top left corner
* D-PAD move around the whale sprite
* D-PAD + A move around the whale sprite in single pixel steps
* D-PAD + B move around the background image
*
******************************************************************************/
#include <Arduboy2.h> // required to build for Arduboy
#include <ArduboyFX.h> // required to access the FX external flash
#include "fxdata.h" // this file contains all references to FX data
#define FRAME_RATE 120
Arduboy2 arduboy;
bool showposition = true;
uint8_t select,color;
int x [2];
int y [2];
void setup() {
arduboy.begin();
arduboy.setFrameRate(FRAME_RATE);
FX::disableOLED(); // OLED must be disabled before external flash is accessed. OLED display should only be enabled prior updating the display.
FX::begin(FX_DATA_PAGE); //external flash chip may be in power down mode so wake it up (Cathy bootloader puts chip into powerdown mode)
}
void loop() {
if (!arduboy.nextFrame()) return;
arduboy.pollButtons();
if (arduboy.justPressed(B_BUTTON)) showposition = !showposition;
if (arduboy.pressed(B_BUTTON)) select = 0;
else select = 1;
if (arduboy.justPressed(A_BUTTON)) color ^= dbmReverse;
if (arduboy.pressed(A_BUTTON))
{
if (arduboy.justPressed(UP_BUTTON)) y[select]--;
if (arduboy.justPressed(DOWN_BUTTON)) y[select]++;
if (arduboy.justPressed(LEFT_BUTTON)) x[select]--;
if (arduboy.justPressed(RIGHT_BUTTON)) x[select]++;
}
else
{
if (arduboy.pressed(UP_BUTTON)) y[select]--;
if (arduboy.pressed(DOWN_BUTTON)) y[select]++;
if (arduboy.pressed(LEFT_BUTTON)) x[select]--;
if (arduboy.pressed(RIGHT_BUTTON)) x[select]++;
}
FX::drawBitmap(x[0],y[0],mapGfx,0,dbmNormal);
FX::drawBitmap(x[1],y[1],whaleGfx,0,dbmMasked | color); // comment this line and uncomment one below to test the drawing modes
//FX::drawBitmap(x[1],y[1],whaleGfx,0,dbmMasked | dbmBlack); // black pixels as drawn solid. White pixels are transparent. Mask is ignored.
//FX::drawBitmap(x[1],y[1],whaleGfx,0,dbmMasked | dbmWhite); // white pixels are drawn solid. Black pixels are transparent. Mask is ignored.
//FX::drawBitmap(x[1],y[1],whaleGfx,0,dbmMasked | dbmInvert); // white pixels are xored together with background pixels. Mask is ignored.
//FX::drawBitmap(x[1],y[1],whaleGfx,0,dbmMasked | dbmReverse); // Inverts the image: white pixels are drawn as black, black pixels are drawn as white pixels. Mask is applied.
if (showposition)
{
arduboy.setCursor(0,0);
arduboy.print(x[select]);
arduboy.setCursor(0,8);
arduboy.print(y[select]);
}
FX::enableOLED(); // only enable OLED for updating the display
arduboy.display(CLEAR_BUFFER); // Using CLEAR_BUFFER will clear the display buffer after it is displayed
FX::disableOLED(); // disable display again so external flash can be accessed at any time
}
| [
"[email protected]"
]
| |
23651864bf4b5de9796ee5a5a703b26e5daeebfc | 1af49694004c6fbc31deada5618dae37255ce978 | /ash/assistant/assistant_notification_controller_impl.cc | f459b38a0a99fc3b5a5fc69a847e36458e4027b9 | [
"BSD-3-Clause"
]
| permissive | sadrulhc/chromium | 59682b173a00269ed036eee5ebfa317ba3a770cc | a4b950c23db47a0fdd63549cccf9ac8acd8e2c41 | refs/heads/master | 2023-02-02T07:59:20.295144 | 2020-12-01T21:32:32 | 2020-12-01T21:32:32 | 317,678,056 | 3 | 0 | BSD-3-Clause | 2020-12-01T21:56:26 | 2020-12-01T21:56:25 | null | UTF-8 | C++ | false | false | 8,298 | 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 "ash/assistant/assistant_notification_controller_impl.h"
#include <memory>
#include <utility>
#include "ash/assistant/assistant_controller_impl.h"
#include "ash/assistant/assistant_notification_expiry_monitor.h"
#include "ash/assistant/util/deep_link_util.h"
#include "ash/public/cpp/assistant/controller/assistant_controller.h"
#include "ash/public/cpp/notification_utils.h"
#include "ash/shell.h"
#include "ash/strings/grit/ash_strings.h"
#include "base/strings/utf_string_conversions.h"
#include "chromeos/services/assistant/public/cpp/assistant_notification.h"
#include "chromeos/ui/vector_icons/vector_icons.h"
#include "mojo/public/cpp/bindings/pending_receiver.h"
#include "mojo/public/cpp/bindings/receiver.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/message_center/message_center.h"
#include "ui/message_center/public/cpp/notification.h"
#include "url/gurl.h"
namespace ash {
namespace {
constexpr char kNotifierId[] = "assistant";
// Helpers ---------------------------------------------------------------------
std::unique_ptr<message_center::Notification> CreateSystemNotification(
const message_center::NotifierId& notifier_id,
const chromeos::assistant::AssistantNotification& notification) {
const base::string16 title = base::UTF8ToUTF16(notification.title);
const base::string16 message = base::UTF8ToUTF16(notification.message);
const base::string16 display_source =
l10n_util::GetStringUTF16(IDS_ASH_ASSISTANT_NOTIFICATION_DISPLAY_SOURCE);
message_center::RichNotificationData data;
for (const auto& button : notification.buttons)
data.buttons.emplace_back(base::UTF8ToUTF16(button.label));
std::unique_ptr<message_center::Notification> system_notification =
ash::CreateSystemNotification(
message_center::NOTIFICATION_TYPE_SIMPLE, notification.client_id,
title, message, display_source, GURL(), notifier_id, data,
/*delegate=*/nullptr, chromeos::kNotificationAssistantIcon,
message_center::SystemNotificationWarningLevel::NORMAL);
system_notification->set_renotify(notification.renotify);
system_notification->set_pinned(notification.is_pinned);
switch (notification.priority) {
case chromeos::assistant::AssistantNotificationPriority::kLow:
system_notification->set_priority(message_center::LOW_PRIORITY);
break;
case chromeos::assistant::AssistantNotificationPriority::kDefault:
system_notification->set_priority(message_center::DEFAULT_PRIORITY);
break;
case chromeos::assistant::AssistantNotificationPriority::kHigh:
system_notification->set_priority(message_center::HIGH_PRIORITY);
break;
}
return system_notification;
}
message_center::NotifierId GetNotifierId() {
return message_center::NotifierId(
message_center::NotifierType::SYSTEM_COMPONENT, kNotifierId);
}
bool IsValidActionUrl(const GURL& action_url) {
return action_url.is_valid() && (action_url.SchemeIsHTTPOrHTTPS() ||
assistant::util::IsDeepLinkUrl(action_url));
}
} // namespace
// AssistantNotificationControllerImpl
// ---------------------------------------------
AssistantNotificationControllerImpl::AssistantNotificationControllerImpl()
: expiry_monitor_(this), notifier_id_(GetNotifierId()) {
model_.AddObserver(this);
message_center::MessageCenter::Get()->AddObserver(this);
}
AssistantNotificationControllerImpl::~AssistantNotificationControllerImpl() {
message_center::MessageCenter::Get()->RemoveObserver(this);
model_.RemoveObserver(this);
}
void AssistantNotificationControllerImpl::SetAssistant(
chromeos::assistant::Assistant* assistant) {
assistant_ = assistant;
}
// AssistantNotificationController --------------------------------------
void AssistantNotificationControllerImpl::AddOrUpdateNotification(
AssistantNotification&& notification) {
model_.AddOrUpdateNotification(std::move(notification));
}
void AssistantNotificationControllerImpl::RemoveNotificationById(
const std::string& id,
bool from_server) {
model_.RemoveNotificationById(id, from_server);
}
void AssistantNotificationControllerImpl::RemoveNotificationByGroupingKey(
const std::string& grouping_key,
bool from_server) {
model_.RemoveNotificationsByGroupingKey(grouping_key, from_server);
}
void AssistantNotificationControllerImpl::RemoveAllNotifications(
bool from_server) {
model_.RemoveAllNotifications(from_server);
}
void AssistantNotificationControllerImpl::SetQuietMode(bool enabled) {
message_center::MessageCenter::Get()->SetQuietMode(enabled);
}
// AssistantNotificationModelObserver ------------------------------------------
void AssistantNotificationControllerImpl::OnNotificationAdded(
const AssistantNotification& notification) {
// Do not show system notifications if the setting is disabled.
if (!AssistantState::Get()->notification_enabled().value_or(true))
return;
message_center::MessageCenter::Get()->AddNotification(
CreateSystemNotification(notifier_id_, notification));
}
void AssistantNotificationControllerImpl::OnNotificationUpdated(
const AssistantNotification& notification) {
// Do not show system notifications if the setting is disabled.
if (!AssistantState::Get()->notification_enabled().value_or(true))
return;
message_center::MessageCenter::Get()->UpdateNotification(
notification.client_id,
CreateSystemNotification(notifier_id_, notification));
}
void AssistantNotificationControllerImpl::OnNotificationRemoved(
const AssistantNotification& notification,
bool from_server) {
// Remove the notification from the message center.
message_center::MessageCenter::Get()->RemoveNotification(
notification.client_id, /*by_user=*/false);
// Dismiss the notification on the server to sync across devices.
if (!from_server)
assistant_->DismissNotification(notification);
}
void AssistantNotificationControllerImpl::OnAllNotificationsRemoved(
bool from_server) {
message_center::MessageCenter::Get()->RemoveNotificationsForNotifierId(
notifier_id_);
}
// message_center::MessageCenterObserver ---------------------------------------
void AssistantNotificationControllerImpl::OnNotificationClicked(
const std::string& id,
const base::Optional<int>& button_index,
const base::Optional<base::string16>& reply) {
const AssistantNotification* notification = model_.GetNotificationById(id);
if (!notification)
return;
const auto& action_url =
button_index.has_value()
? notification->buttons[button_index.value()].action_url
: notification->action_url;
// Open the action url if it is valid.
if (IsValidActionUrl(action_url)) {
// NOTE: We copy construct a new GURL as our |notification| may be destroyed
// during the OpenUrl() sequence leaving |action_url| in a bad state.
AssistantController::Get()->OpenUrl(GURL(action_url));
const bool remove_notification =
button_index.has_value() ? notification->buttons[button_index.value()]
.remove_notification_on_click
: notification->remove_on_click;
if (remove_notification)
model_.RemoveNotificationById(id, /*from_server=*/false);
return;
}
if (!notification->from_server)
return;
// If the notification is from the server, we retrieve the notification
// payload using the following indexing scheme:
//
// Index: | [0] | [1] | [2] | ...
// -------------------------------------------------
// Action: | Top Level | Button 1 | Button 2 | ...
const int action_index = button_index.value_or(-1) + 1;
assistant_->RetrieveNotification(*notification, action_index);
}
void AssistantNotificationControllerImpl::OnNotificationRemoved(
const std::string& notification_id,
bool by_user) {
// Update our notification model to remain in sync w/ Message Center.
if (model_.GetNotificationById(notification_id))
model_.RemoveNotificationById(notification_id, /*from_server=*/false);
}
} // namespace ash
| [
"[email protected]"
]
| |
7413ebcbdb0d18e76dcc95fabfb43053cae8f6b5 | cd1e2e007fdc0d204f7ea9cd6f1dc49c9256f933 | /to_upper.cpp | 4c8b64fc47805cdd1e617b878279718feb1e72b0 | []
| no_license | Sid532001/c-c- | 956cd3d9e937524c36acd7bcc0f3f5913a6fcbb0 | 81fe0ed4fd684dab244f4cd6f6cdaa27f6de3657 | refs/heads/master | 2023-03-18T04:37:28.319741 | 2021-02-25T09:37:27 | 2021-02-25T09:37:27 | 342,187,214 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 569 | cpp | #include<bits/stdc++.h>
using namespace std;
int main()
{
char str[100];
int i=0;
cout<<"enter the string:";
cin>>str;
char str2[100];
while(str[i]!='\0')
{
if(str[i]>='a' && str[i]<='z')
{
str2[i]=str[i]-32;
}
else
{
str2[i]=str[i];
i++;
}
}
str2[i]='\0';
cout<<str2[i];
return 0;
}
// #include<bits/stdc++.h>
// using namespace std;
// int main()
// {
// string str;
// cin>>str;
// cout<<str.toLower();
// return 0;
// } | [
"[email protected]"
]
| |
5eea92c6c947a4a56198e12fe1ec8b404820ae55 | 870625f6c2c25c3bf56f946a2cc3d13dddcff3c2 | /gambling simulator.cpp | 8a145810aa9d96a3ec165d3b819b209b947b22b8 | []
| no_license | kazoopipes/Gambling-Simulator | 99bfe890c3086bf44db4866442a91f74cc2eee4f | d27228fd394c9dda0755182ce8c6845e548c3601 | refs/heads/main | 2023-04-19T07:07:40.788159 | 2021-04-28T23:19:05 | 2021-04-28T23:19:05 | 362,609,782 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,942 | cpp | #include <iostream>
#include <stdlib.h>
using namespace std;
//making the budget
int budget = rand() % 5000 + 3000;
//RGG loop
void RandomGambleGame(){
//game set up
cout << "---------------------------\n";
int WagerAmount;
cout << "Welcome to the random gamble game! \n";
cout << "how much will you wager?(decimals will break the game) \n";
cin >> WagerAmount;
//checking the money amount
if (WagerAmount <= 0) {
cout << "to little money \n";
RandomGambleGame();
} else if (WagerAmount > budget) {
cout << "not enough money \n";
RandomGambleGame();
} else {
//the game
int rggNum = rand() % 10 + 0;
int rggNumGuess;
cout << "whats your guess for the number? \n";
cin >> rggNumGuess;
//processing results
if (rggNumGuess == rggNum) {
int fBudget = WagerAmount + budget;
budget = fBudget;
cout << "WINNER!!! \n";
} else {
int fBudget = budget - WagerAmount;
budget = fBudget;
cout << "wrong! \n";
}
}
}
void Menu() {
//game set up
bool game = true;
while (game = true){
char GameChoice;
//game menu
cout << "this is your budget! \n";
cout << budget << "\n";
cout << "what would you like to do? \n";
cout << "---------------------------\n";
cout << "0 = random gamble game \n";
cout << "1 = exit (note: progress does NOT save yet!) \n";
cout << "---------------------------\n";
cin >> GameChoice;
//processing choice
if (GameChoice == '0') {
RandomGambleGame();
} else if (GameChoice == '1') {
return;
}
}
}
int main() {
cout << "---------------------------\n";
Menu();
}
| [
"[email protected]"
]
| |
9db49ecf45a906ec0e268ee5ab237304651a5971 | cd474b178fee82660ccf5eefc23dce3c821a2650 | /source/ui/scene/settingsScene.hpp | 2c2f08ebc758310c6978fb56a3c15f1b4412181d | [
"MIT"
]
| permissive | CamillePolice/Epitech-Bomberman | a01f5a86690ddfffa5ad65cd83fe77ba082353a4 | 8650071a6a21ba2e0606e4d8e38794de37bdf39f | refs/heads/master | 2020-06-03T22:16:11.172162 | 2016-06-10T06:44:32 | 2016-06-10T06:44:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 802 | hpp | /*
** settingsScene.hpp for UI in /home/escoba_j/Downloads/irrlicht-1.8.3/ui/scene
**
** Made by Joffrey Escobar
** Login <[email protected]>
**
** Started on Sun May 29 03:00:07 2016 Joffrey Escobar
*/
#ifndef SETTINGSSCENE_HPP
#define SETTINGSSCENE_HPP
#include <vector>
#include <string>
#include <utility>
#include "ASubLayout.hpp"
class settingsScene : public ASubLayout
{
public:
settingsScene(ui &ui);
~settingsScene(void);
void loadScene(void);
void updateRuntime(void);
void manageEvent(bbman::InputListener &listener);
void loadRessources(void);
void loadIA(void);
void loadSound(void);
std::vector<std::pair<std::string, int> > const getVolume(void) const;
int getIADifficulty(void) const;
private:
int _music;
int _effect;
int _iaLevel;
};
#endif
| [
"[email protected]"
]
| |
33d89795317ea238fdb8534219ccfef2acacc196 | d1956c4697a056cbb2baddd82c580ac79fbbc5c3 | /facade/dvd-player.hpp | fc3ac2a02caf8edba4e1d372bd3c849d09694eb5 | []
| no_license | iLoveUcdit/design-patterns | 36e98563bbb47e0663c269c0fd928d47b5537784 | 3b8e943aa6407877a435149240f73b562a5967cb | refs/heads/master | 2021-01-10T10:14:02.320889 | 2016-01-24T15:34:13 | 2016-01-24T15:34:13 | 45,346,299 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,791 | hpp | #ifndef _DVD_PLAYER_HPP_
#define _DVD_PLAYER_HPP_
#include <string>
#include <iostream>
class Amplifier;
class DvdPlayer {
public:
DvdPlayer(std::string description, Amplifier *amplifier) {
m_description = description;
m_amplifier = amplifier;
}
virtual ~DvdPlayer() {}
void on() {
std::cout << m_description << " on" << std::endl;
}
void off() {
std::cout << m_description << " off" << std::endl;
}
void eject() {
m_movie = "";
std::cout << m_description << " eject" << std::endl;
}
void play(std::string movie) {
m_movie = movie;
m_currentTrack = 0;
std::cout << m_description << " playing \"" << m_movie << "\"" << std::endl;
}
void play(int track) {
if (m_movie == "") {
std::cout << m_description << " can't play track " << track << " no dvd inserted" << std::endl;
} else {
m_currentTrack = track;
std::cout << m_description << " playing track " << m_currentTrack << " of \"" << m_movie << "\"" << std::endl;
}
}
void stop() {
m_currentTrack = 0;
std::cout << m_description << " stopped \"" << m_movie << "\"" << std::endl;
}
void pause() {
std::cout << m_description << " paused \"" << m_movie << "\"" << std::endl;
}
void setTwoChannelAudio() {
std::cout << m_description << " set two channel audio" << std::endl;
}
void setSurroundAudio() {
std::cout << m_description << " set surround audio" << std::endl;
}
std::string toString() {
return m_description;
}
private:
std::string m_description;
int m_currentTrack;
Amplifier *m_amplifier;
std::string m_movie;
};
#endif // _DVD_PLAYER_HPP_
| [
"[email protected]"
]
| |
e0026c27151f651acfe0e79fc1ac14576ed0a9a0 | 16eff5c8af3269edb003737a38766805809410c7 | /Jurassic Park/DinosaurPark.cpp | 1a9fc684839b6c4ed9834f3d9550457aa716032a | []
| no_license | TripppleG/FMI-OOP-Projects | 173cb0bfc23d2700283259842168780c021e46c2 | 43c998ad72312d2d647f073e58386c7b1b4be29a | refs/heads/master | 2022-09-22T04:37:04.363691 | 2020-05-31T14:03:57 | 2020-05-31T14:03:57 | 250,016,362 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,769 | cpp | #include "DinosaurPark.h"
#include <iomanip>
void DinosaurPark::Resize()
{
maxNumberOfCages *= 2;
Cage* temp = new Cage[maxNumberOfCages];
for (unsigned i = 0; i < numberOfCages; i++)
{
temp[i] = cages[i];
}
delete[]cages;
cages = temp;
}
void DinosaurPark::CopyFrom(const DinosaurPark& other)
{
numberOfCages = other.numberOfCages;
maxNumberOfCages = other.maxNumberOfCages;
staffCount = other.staffCount;
foodAvailable = other.foodAvailable;
foodRequired = other.foodRequired;
cages = new Cage[maxNumberOfCages];
for (unsigned i = 0; i < numberOfCages; i++)
{
cages[i] = other.cages[i];
}
}
void DinosaurPark::Free()
{
delete[]cages;
}
DinosaurPark::DinosaurPark()
{
numberOfCages = 3;
maxNumberOfCages = 4;
staffCount = numberOfCages;
cages = new Cage[maxNumberOfCages];
cages[0] = Cage(Size::Medium, Climate::Aerial);
cages[1] = Cage(Size::Medium, Climate::Aqueous);
cages[2] = Cage(Size::Large, Climate::Terrestrial);
foodAvailable = FoodStorage(10, 10, 10);
foodRequired = FoodStorage(0, 0, 0);
}
DinosaurPark::DinosaurPark(const DinosaurPark& other)
{
CopyFrom(other);
}
DinosaurPark& DinosaurPark::operator=(const DinosaurPark& other)
{
if (this != &other)
{
Free();
CopyFrom(other);
}
return *this;
}
DinosaurPark::~DinosaurPark()
{
Free();
}
std::ostream& operator<<(std::ostream& os, const DinosaurPark& park)
{
os << "Staff count: " << park.staffCount << std::endl;
os << "Number of cages: " << park.numberOfCages << std::endl;
os << "Park capacity for cages: " << park.maxNumberOfCages << std::endl;
os << "Food required to feed the dinosaurs:\n" << park.foodRequired << std::endl << std::endl;
os << "Food available:\n" << park.foodAvailable << std::endl << std::endl;
os << std::setfill('-') << std::setw(108) << "\n";
for (unsigned i = 0; i < park.numberOfCages; i++)
{
os << "Cage " << i + 1 << ":" << std::endl;
os << park.cages[i];
}
return os;
}
std::istream& operator>>(std::istream& is, DinosaurPark& park)
{
char* temp = new char[11];
is.ignore(13);
is.getline(temp, 11);
park.staffCount = atoi(temp);
is.ignore(17);
is.getline(temp, 11);
park.numberOfCages = atoi(temp);
is.ignore(25);
is.getline(temp, 11);
park.maxNumberOfCages = atoi(temp);
is.ignore(37);
is >> park.foodRequired;
is.ignore(17);
is >> park.foodAvailable;
is.ignore(110, '\n');
delete[] park.cages;
park.cages = new Cage[park.maxNumberOfCages];
for (unsigned i = 0; i < park.numberOfCages; i++)
{
is.ignore(8);
is >> park.cages[i];
}
return is;
}
void DinosaurPark::CreateCage(const Size size, const Climate climate)
{
const Cage temp(size, climate);
CreateCage(temp);
}
void DinosaurPark::CreateCage(const Cage& cage)
{
if (numberOfCages == maxNumberOfCages)
{
Resize();
}
cages[numberOfCages] = cage;
numberOfCages++;
staffCount++;
}
short DinosaurPark::AddDinosaur(const char* name, const Sex sex, const Era era, const char* species, const Category category)
{
const Dinosaur temp(name, sex, era, species, category);
return AddDinosaur(temp);
}
short DinosaurPark::AddDinosaur(const Dinosaur& dinosaur)
{
for (unsigned i = 0; i < numberOfCages; i++)
{
short result = cages[i].AddDinosaur(dinosaur);
if (result == -1)
{
return -1;
}
else if(result == 1)
{
if (dinosaur.GetFood() == Food::Fish)
{
foodRequired.fish++;
}
else if (dinosaur.GetFood() == Food::Grass)
{
foodRequired.grass++;
}
else
{
foodRequired.meat++;
}
return 1;
}
}
return 0;
}
bool DinosaurPark::RemoveDinosaur(const char* name, const Sex sex, const Era era, const char* species, const Category category)
{
const Dinosaur temp(name, sex, era, species, category);
return RemoveDinosaur(temp);
}
bool DinosaurPark::RemoveDinosaur(const Dinosaur& dinosaur)
{
for (unsigned i = 0; i < numberOfCages; i++)
{
if (cages[i].RemoveDinosaur(dinosaur))
{
return true;
}
}
return false;
}
void DinosaurPark::RefillStorage()
{
if (foodRequired.fish != 0)
{
foodAvailable.fish = 4 * foodRequired.fish;
}
if (foodRequired.grass != 0)
{
foodAvailable.grass = 4 * foodRequired.grass;
}
if (foodRequired.meat != 0)
{
foodAvailable.meat = 4 * foodRequired.meat;
}
}
void DinosaurPark::FeedTheDinosaurs()
{
foodAvailable -= foodRequired;
}
const Cage* DinosaurPark::GetCages() const
{
return cages;
}
const unsigned DinosaurPark::GetNumberOfCages() const
{
return numberOfCages;
}
const unsigned DinosaurPark::GetMaxNumberOfCages() const
{
return maxNumberOfCages;
}
const unsigned DinosaurPark::GetStaffCount() const
{
return staffCount;
}
const FoodStorage DinosaurPark::GetFoodRequired() const
{
return foodRequired;
}
const FoodStorage DinosaurPark::GetFoodAvailable() const
{
return foodAvailable;
} | [
"[email protected]"
]
| |
ba04493bb270329a5cbda8cdeee15558c49317b8 | 035be342c2ab4fd8225b1d663d91275d7a33dc89 | /LZEngine2010/DataStructures/LZLinkedList.h | 349e0e58431756ba076fd09be3c5ca7649edef5c | []
| no_license | Zanzes/LZEngine | 7f25fa2b53af804e04b094f7b91e176755126ac1 | 714c65bcc7d94935850950d3c813b07c4b7818d4 | refs/heads/master | 2021-01-24T17:49:19.301958 | 2017-12-22T19:20:54 | 2017-12-22T19:20:54 | 60,836,553 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 557 | h | #pragma once
#include "Node.h"
namespace LZSoft
{
namespace DataStructures
{
template <class T>
class __declspec(dllexport) LZLinkedList
{
public:
Node<T> *Head;
Node<T> *Tail;
int Count;
void Add(const T value);
void Remove(Node<T>* node);
void RemoveHead();
void RemoveTail();
void RemoveAt(const int index);
Node<T>* AtIndex(const int index);
LZLinkedList();
LZLinkedList(const LZLinkedList<T>& source);
LZLinkedList<T>& operator=(const LZLinkedList<T>& right);
};
#include "LZLinkedList.inl"
}
}
| [
"[email protected]"
]
| |
6fa0fdfaf27287c785b3bb56206dfd9ce67789ff | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/curl/gumtree/curl_repos_function_1462_curl-7.41.0.cpp | b2cb1f059ec7253dc08c5cf5b552fba5f3644965 | []
| 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 | 29,512 | cpp | static CURLMcode multi_runsingle(struct Curl_multi *multi,
struct timeval now,
struct SessionHandle *data)
{
struct Curl_message *msg = NULL;
bool connected;
bool async;
bool protocol_connect = FALSE;
bool dophase_done = FALSE;
bool done = FALSE;
CURLMcode rc;
CURLcode result = CURLE_OK;
struct SingleRequest *k;
long timeout_ms;
int control;
if(!GOOD_EASY_HANDLE(data))
return CURLM_BAD_EASY_HANDLE;
do {
bool disconnect_conn = FALSE;
rc = CURLM_OK;
/* Handle the case when the pipe breaks, i.e., the connection
we're using gets cleaned up and we're left with nothing. */
if(data->state.pipe_broke) {
infof(data, "Pipe broke: handle %p, url = %s\n",
(void *)data, data->state.path);
if(data->mstate < CURLM_STATE_COMPLETED) {
/* Head back to the CONNECT state */
multistate(data, CURLM_STATE_CONNECT);
rc = CURLM_CALL_MULTI_PERFORM;
result = CURLE_OK;
}
data->state.pipe_broke = FALSE;
data->easy_conn = NULL;
continue;
}
if(!data->easy_conn &&
data->mstate > CURLM_STATE_CONNECT &&
data->mstate < CURLM_STATE_DONE) {
/* In all these states, the code will blindly access 'data->easy_conn'
so this is precaution that it isn't NULL. And it silences static
analyzers. */
failf(data, "In state %d with no easy_conn, bail out!\n", data->mstate);
return CURLM_INTERNAL_ERROR;
}
if(data->easy_conn && data->mstate > CURLM_STATE_CONNECT &&
data->mstate < CURLM_STATE_COMPLETED)
/* Make sure we set the connection's current owner */
data->easy_conn->data = data;
if(data->easy_conn &&
(data->mstate >= CURLM_STATE_CONNECT) &&
(data->mstate < CURLM_STATE_COMPLETED)) {
/* we need to wait for the connect state as only then is the start time
stored, but we must not check already completed handles */
timeout_ms = Curl_timeleft(data, &now,
(data->mstate <= CURLM_STATE_WAITDO)?
TRUE:FALSE);
if(timeout_ms < 0) {
/* Handle timed out */
if(data->mstate == CURLM_STATE_WAITRESOLVE)
failf(data, "Resolving timed out after %ld milliseconds",
Curl_tvdiff(now, data->progress.t_startsingle));
else if(data->mstate == CURLM_STATE_WAITCONNECT)
failf(data, "Connection timed out after %ld milliseconds",
Curl_tvdiff(now, data->progress.t_startsingle));
else {
k = &data->req;
if(k->size != -1) {
failf(data, "Operation timed out after %ld milliseconds with %"
CURL_FORMAT_CURL_OFF_T " out of %"
CURL_FORMAT_CURL_OFF_T " bytes received",
Curl_tvdiff(k->now, data->progress.t_startsingle),
k->bytecount, k->size);
}
else {
failf(data, "Operation timed out after %ld milliseconds with %"
CURL_FORMAT_CURL_OFF_T " bytes received",
Curl_tvdiff(now, data->progress.t_startsingle),
k->bytecount);
}
}
/* Force connection closed if the connection has indeed been used */
if(data->mstate > CURLM_STATE_DO) {
connclose(data->easy_conn, "Disconnected with pending data");
disconnect_conn = TRUE;
}
result = CURLE_OPERATION_TIMEDOUT;
/* Skip the statemachine and go directly to error handling section. */
goto statemachine_end;
}
}
switch(data->mstate) {
case CURLM_STATE_INIT:
/* init this transfer. */
result=Curl_pretransfer(data);
if(!result) {
/* after init, go CONNECT */
multistate(data, CURLM_STATE_CONNECT);
Curl_pgrsTime(data, TIMER_STARTOP);
rc = CURLM_CALL_MULTI_PERFORM;
}
break;
case CURLM_STATE_CONNECT_PEND:
/* We will stay here until there is a connection available. Then
we try again in the CURLM_STATE_CONNECT state. */
break;
case CURLM_STATE_CONNECT:
/* Connect. We want to get a connection identifier filled in. */
Curl_pgrsTime(data, TIMER_STARTSINGLE);
result = Curl_connect(data, &data->easy_conn,
&async, &protocol_connect);
if(CURLE_NO_CONNECTION_AVAILABLE == result) {
/* There was no connection available. We will go to the pending
state and wait for an available connection. */
multistate(data, CURLM_STATE_CONNECT_PEND);
/* add this handle to the list of connect-pending handles */
if(!Curl_llist_insert_next(multi->pending, multi->pending->tail, data))
result = CURLE_OUT_OF_MEMORY;
else
result = CURLE_OK;
break;
}
if(!result) {
/* Add this handle to the send or pend pipeline */
result = Curl_add_handle_to_pipeline(data, data->easy_conn);
if(result)
disconnect_conn = TRUE;
else {
if(async)
/* We're now waiting for an asynchronous name lookup */
multistate(data, CURLM_STATE_WAITRESOLVE);
else {
/* after the connect has been sent off, go WAITCONNECT unless the
protocol connect is already done and we can go directly to
WAITDO or DO! */
rc = CURLM_CALL_MULTI_PERFORM;
if(protocol_connect)
multistate(data, multi->pipelining_enabled?
CURLM_STATE_WAITDO:CURLM_STATE_DO);
else {
#ifndef CURL_DISABLE_HTTP
if(data->easy_conn->tunnel_state[FIRSTSOCKET] == TUNNEL_CONNECT)
multistate(data, CURLM_STATE_WAITPROXYCONNECT);
else
#endif
multistate(data, CURLM_STATE_WAITCONNECT);
}
}
}
}
break;
case CURLM_STATE_WAITRESOLVE:
/* awaiting an asynch name resolve to complete */
{
struct Curl_dns_entry *dns = NULL;
struct connectdata *conn = data->easy_conn;
/* check if we have the name resolved by now */
if(data->share)
Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
dns = Curl_fetch_addr(conn, conn->host.name, (int)conn->port);
if(dns) {
dns->inuse++; /* we use it! */
#ifdef CURLRES_ASYNCH
conn->async.dns = dns;
conn->async.done = TRUE;
#endif
result = CURLE_OK;
infof(data, "Hostname was found in DNS cache\n");
}
if(data->share)
Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
if(!dns)
result = Curl_resolver_is_resolved(data->easy_conn, &dns);
/* Update sockets here, because the socket(s) may have been
closed and the application thus needs to be told, even if it
is likely that the same socket(s) will again be used further
down. If the name has not yet been resolved, it is likely
that new sockets have been opened in an attempt to contact
another resolver. */
singlesocket(multi, data);
if(dns) {
/* Perform the next step in the connection phase, and then move on
to the WAITCONNECT state */
result = Curl_async_resolved(data->easy_conn, &protocol_connect);
if(result)
/* if Curl_async_resolved() returns failure, the connection struct
is already freed and gone */
data->easy_conn = NULL; /* no more connection */
else {
/* call again please so that we get the next socket setup */
rc = CURLM_CALL_MULTI_PERFORM;
if(protocol_connect)
multistate(data, multi->pipelining_enabled?
CURLM_STATE_WAITDO:CURLM_STATE_DO);
else {
#ifndef CURL_DISABLE_HTTP
if(data->easy_conn->tunnel_state[FIRSTSOCKET] == TUNNEL_CONNECT)
multistate(data, CURLM_STATE_WAITPROXYCONNECT);
else
#endif
multistate(data, CURLM_STATE_WAITCONNECT);
}
}
}
if(result) {
/* failure detected */
disconnect_conn = TRUE;
break;
}
}
break;
#ifndef CURL_DISABLE_HTTP
case CURLM_STATE_WAITPROXYCONNECT:
/* this is HTTP-specific, but sending CONNECT to a proxy is HTTP... */
result = Curl_http_connect(data->easy_conn, &protocol_connect);
if(data->easy_conn->bits.proxy_connect_closed) {
/* connect back to proxy again */
result = CURLE_OK;
rc = CURLM_CALL_MULTI_PERFORM;
multistate(data, CURLM_STATE_CONNECT);
}
else if(!result) {
if(data->easy_conn->tunnel_state[FIRSTSOCKET] == TUNNEL_COMPLETE)
multistate(data, CURLM_STATE_WAITCONNECT);
}
break;
#endif
case CURLM_STATE_WAITCONNECT:
/* awaiting a completion of an asynch connect */
result = Curl_is_connected(data->easy_conn,
FIRSTSOCKET,
&connected);
if(connected) {
if(!result)
/* if everything is still fine we do the protocol-specific connect
setup */
result = Curl_protocol_connect(data->easy_conn,
&protocol_connect);
}
if(data->easy_conn->bits.proxy_connect_closed) {
/* connect back to proxy again since it was closed in a proxy CONNECT
setup */
result = CURLE_OK;
rc = CURLM_CALL_MULTI_PERFORM;
multistate(data, CURLM_STATE_CONNECT);
break;
}
else if(result) {
/* failure detected */
/* Just break, the cleaning up is handled all in one place */
disconnect_conn = TRUE;
break;
}
if(connected) {
if(!protocol_connect) {
/* We have a TCP connection, but 'protocol_connect' may be false
and then we continue to 'STATE_PROTOCONNECT'. If protocol
connect is TRUE, we move on to STATE_DO.
BUT if we are using a proxy we must change to WAITPROXYCONNECT
*/
#ifndef CURL_DISABLE_HTTP
if(data->easy_conn->tunnel_state[FIRSTSOCKET] == TUNNEL_CONNECT)
multistate(data, CURLM_STATE_WAITPROXYCONNECT);
else
#endif
multistate(data, CURLM_STATE_PROTOCONNECT);
}
else
/* after the connect has completed, go WAITDO or DO */
multistate(data, multi->pipelining_enabled?
CURLM_STATE_WAITDO:CURLM_STATE_DO);
rc = CURLM_CALL_MULTI_PERFORM;
}
break;
case CURLM_STATE_PROTOCONNECT:
/* protocol-specific connect phase */
result = Curl_protocol_connecting(data->easy_conn, &protocol_connect);
if(!result && protocol_connect) {
/* after the connect has completed, go WAITDO or DO */
multistate(data, multi->pipelining_enabled?
CURLM_STATE_WAITDO:CURLM_STATE_DO);
rc = CURLM_CALL_MULTI_PERFORM;
}
else if(result) {
/* failure detected */
Curl_posttransfer(data);
Curl_done(&data->easy_conn, result, TRUE);
disconnect_conn = TRUE;
}
break;
case CURLM_STATE_WAITDO:
/* Wait for our turn to DO when we're pipelining requests */
#ifdef DEBUGBUILD
infof(data, "WAITDO: Conn %ld send pipe %zu inuse %s athead %s\n",
data->easy_conn->connection_id,
data->easy_conn->send_pipe->size,
data->easy_conn->writechannel_inuse?"TRUE":"FALSE",
isHandleAtHead(data,
data->easy_conn->send_pipe)?"TRUE":"FALSE");
#endif
if(!data->easy_conn->writechannel_inuse &&
isHandleAtHead(data,
data->easy_conn->send_pipe)) {
/* Grab the channel */
data->easy_conn->writechannel_inuse = TRUE;
multistate(data, CURLM_STATE_DO);
rc = CURLM_CALL_MULTI_PERFORM;
}
break;
case CURLM_STATE_DO:
if(data->set.connect_only) {
/* keep connection open for application to use the socket */
connkeep(data->easy_conn, "CONNECT_ONLY");
multistate(data, CURLM_STATE_DONE);
result = CURLE_OK;
rc = CURLM_CALL_MULTI_PERFORM;
}
else {
/* Perform the protocol's DO action */
result = Curl_do(&data->easy_conn, &dophase_done);
/* When Curl_do() returns failure, data->easy_conn might be NULL! */
if(!result) {
if(!dophase_done) {
/* some steps needed for wildcard matching */
if(data->set.wildcardmatch) {
struct WildcardData *wc = &data->wildcard;
if(wc->state == CURLWC_DONE || wc->state == CURLWC_SKIP) {
/* skip some states if it is important */
Curl_done(&data->easy_conn, CURLE_OK, FALSE);
multistate(data, CURLM_STATE_DONE);
rc = CURLM_CALL_MULTI_PERFORM;
break;
}
}
/* DO was not completed in one function call, we must continue
DOING... */
multistate(data, CURLM_STATE_DOING);
rc = CURLM_OK;
}
/* after DO, go DO_DONE... or DO_MORE */
else if(data->easy_conn->bits.do_more) {
/* we're supposed to do more, but we need to sit down, relax
and wait a little while first */
multistate(data, CURLM_STATE_DO_MORE);
rc = CURLM_OK;
}
else {
/* we're done with the DO, now DO_DONE */
multistate(data, CURLM_STATE_DO_DONE);
rc = CURLM_CALL_MULTI_PERFORM;
}
}
else if((CURLE_SEND_ERROR == result) &&
data->easy_conn->bits.reuse) {
/*
* In this situation, a connection that we were trying to use
* may have unexpectedly died. If possible, send the connection
* back to the CONNECT phase so we can try again.
*/
char *newurl = NULL;
followtype follow=FOLLOW_NONE;
CURLcode drc;
bool retry = FALSE;
drc = Curl_retry_request(data->easy_conn, &newurl);
if(drc) {
/* a failure here pretty much implies an out of memory */
result = drc;
disconnect_conn = TRUE;
}
else
retry = (newurl)?TRUE:FALSE;
Curl_posttransfer(data);
drc = Curl_done(&data->easy_conn, result, FALSE);
/* When set to retry the connection, we must to go back to
* the CONNECT state */
if(retry) {
if(!drc || (drc == CURLE_SEND_ERROR)) {
follow = FOLLOW_RETRY;
drc = Curl_follow(data, newurl, follow);
if(!drc) {
multistate(data, CURLM_STATE_CONNECT);
rc = CURLM_CALL_MULTI_PERFORM;
result = CURLE_OK;
}
else {
/* Follow failed */
result = drc;
free(newurl);
}
}
else {
/* done didn't return OK or SEND_ERROR */
result = drc;
free(newurl);
}
}
else {
/* Have error handler disconnect conn if we can't retry */
disconnect_conn = TRUE;
free(newurl);
}
}
else {
/* failure detected */
Curl_posttransfer(data);
if(data->easy_conn)
Curl_done(&data->easy_conn, result, FALSE);
disconnect_conn = TRUE;
}
}
break;
case CURLM_STATE_DOING:
/* we continue DOING until the DO phase is complete */
result = Curl_protocol_doing(data->easy_conn,
&dophase_done);
if(!result) {
if(dophase_done) {
/* after DO, go DO_DONE or DO_MORE */
multistate(data, data->easy_conn->bits.do_more?
CURLM_STATE_DO_MORE:
CURLM_STATE_DO_DONE);
rc = CURLM_CALL_MULTI_PERFORM;
} /* dophase_done */
}
else {
/* failure detected */
Curl_posttransfer(data);
Curl_done(&data->easy_conn, result, FALSE);
disconnect_conn = TRUE;
}
break;
case CURLM_STATE_DO_MORE:
/*
* When we are connected, DO MORE and then go DO_DONE
*/
result = Curl_do_more(data->easy_conn, &control);
/* No need to remove this handle from the send pipeline here since that
is done in Curl_done() */
if(!result) {
if(control) {
/* if positive, advance to DO_DONE
if negative, go back to DOING */
multistate(data, control==1?
CURLM_STATE_DO_DONE:
CURLM_STATE_DOING);
rc = CURLM_CALL_MULTI_PERFORM;
}
else
/* stay in DO_MORE */
rc = CURLM_OK;
}
else {
/* failure detected */
Curl_posttransfer(data);
Curl_done(&data->easy_conn, result, FALSE);
disconnect_conn = TRUE;
}
break;
case CURLM_STATE_DO_DONE:
/* Move ourselves from the send to recv pipeline */
Curl_move_handle_from_send_to_recv_pipe(data, data->easy_conn);
/* Check if we can move pending requests to send pipe */
Curl_multi_process_pending_handles(multi);
/* Only perform the transfer if there's a good socket to work with.
Having both BAD is a signal to skip immediately to DONE */
if((data->easy_conn->sockfd != CURL_SOCKET_BAD) ||
(data->easy_conn->writesockfd != CURL_SOCKET_BAD))
multistate(data, CURLM_STATE_WAITPERFORM);
else
multistate(data, CURLM_STATE_DONE);
rc = CURLM_CALL_MULTI_PERFORM;
break;
case CURLM_STATE_WAITPERFORM:
/* Wait for our turn to PERFORM */
if(!data->easy_conn->readchannel_inuse &&
isHandleAtHead(data,
data->easy_conn->recv_pipe)) {
/* Grab the channel */
data->easy_conn->readchannel_inuse = TRUE;
multistate(data, CURLM_STATE_PERFORM);
rc = CURLM_CALL_MULTI_PERFORM;
}
#ifdef DEBUGBUILD
else {
infof(data, "WAITPERFORM: Conn %ld recv pipe %zu inuse %s athead %s\n",
data->easy_conn->connection_id,
data->easy_conn->recv_pipe->size,
data->easy_conn->readchannel_inuse?"TRUE":"FALSE",
isHandleAtHead(data,
data->easy_conn->recv_pipe)?"TRUE":"FALSE");
}
#endif
break;
case CURLM_STATE_TOOFAST: /* limit-rate exceeded in either direction */
/* if both rates are within spec, resume transfer */
if(Curl_pgrsUpdate(data->easy_conn))
result = CURLE_ABORTED_BY_CALLBACK;
else
result = Curl_speedcheck(data, now);
if(( (data->set.max_send_speed == 0) ||
(data->progress.ulspeed < data->set.max_send_speed )) &&
( (data->set.max_recv_speed == 0) ||
(data->progress.dlspeed < data->set.max_recv_speed)))
multistate(data, CURLM_STATE_PERFORM);
break;
case CURLM_STATE_PERFORM:
{
char *newurl = NULL;
bool retry = FALSE;
/* check if over send speed */
if((data->set.max_send_speed > 0) &&
(data->progress.ulspeed > data->set.max_send_speed)) {
int buffersize;
multistate(data, CURLM_STATE_TOOFAST);
/* calculate upload rate-limitation timeout. */
buffersize = (int)(data->set.buffer_size ?
data->set.buffer_size : BUFSIZE);
timeout_ms = Curl_sleep_time(data->set.max_send_speed,
data->progress.ulspeed, buffersize);
Curl_expire_latest(data, timeout_ms);
break;
}
/* check if over recv speed */
if((data->set.max_recv_speed > 0) &&
(data->progress.dlspeed > data->set.max_recv_speed)) {
int buffersize;
multistate(data, CURLM_STATE_TOOFAST);
/* Calculate download rate-limitation timeout. */
buffersize = (int)(data->set.buffer_size ?
data->set.buffer_size : BUFSIZE);
timeout_ms = Curl_sleep_time(data->set.max_recv_speed,
data->progress.dlspeed, buffersize);
Curl_expire_latest(data, timeout_ms);
break;
}
/* read/write data if it is ready to do so */
result = Curl_readwrite(data->easy_conn, &done);
k = &data->req;
if(!(k->keepon & KEEP_RECV)) {
/* We're done receiving */
data->easy_conn->readchannel_inuse = FALSE;
}
if(!(k->keepon & KEEP_SEND)) {
/* We're done sending */
data->easy_conn->writechannel_inuse = FALSE;
}
if(done || (result == CURLE_RECV_ERROR)) {
/* If CURLE_RECV_ERROR happens early enough, we assume it was a race
* condition and the server closed the re-used connection exactly when
* we wanted to use it, so figure out if that is indeed the case.
*/
CURLcode ret = Curl_retry_request(data->easy_conn, &newurl);
if(!ret)
retry = (newurl)?TRUE:FALSE;
if(retry) {
/* if we are to retry, set the result to OK and consider the
request as done */
result = CURLE_OK;
done = TRUE;
}
}
if(result) {
/*
* The transfer phase returned error, we mark the connection to get
* closed to prevent being re-used. This is because we can't possibly
* know if the connection is in a good shape or not now. Unless it is
* a protocol which uses two "channels" like FTP, as then the error
* happened in the data connection.
*/
if(!(data->easy_conn->handler->flags & PROTOPT_DUAL))
connclose(data->easy_conn, "Transfer returned error");
Curl_posttransfer(data);
Curl_done(&data->easy_conn, result, FALSE);
}
else if(done) {
followtype follow=FOLLOW_NONE;
/* call this even if the readwrite function returned error */
Curl_posttransfer(data);
/* we're no longer receiving */
Curl_removeHandleFromPipeline(data, data->easy_conn->recv_pipe);
/* expire the new receiving pipeline head */
if(data->easy_conn->recv_pipe->head)
Curl_expire_latest(data->easy_conn->recv_pipe->head->ptr, 1);
/* Check if we can move pending requests to send pipe */
Curl_multi_process_pending_handles(multi);
/* When we follow redirects or is set to retry the connection, we must
to go back to the CONNECT state */
if(data->req.newurl || retry) {
if(!retry) {
/* if the URL is a follow-location and not just a retried request
then figure out the URL here */
if(newurl)
free(newurl);
newurl = data->req.newurl;
data->req.newurl = NULL;
follow = FOLLOW_REDIR;
}
else
follow = FOLLOW_RETRY;
result = Curl_done(&data->easy_conn, CURLE_OK, FALSE);
if(!result) {
result = Curl_follow(data, newurl, follow);
if(!result) {
multistate(data, CURLM_STATE_CONNECT);
rc = CURLM_CALL_MULTI_PERFORM;
newurl = NULL; /* handed over the memory ownership to
Curl_follow(), make sure we don't free() it
here */
}
}
}
else {
/* after the transfer is done, go DONE */
/* but first check to see if we got a location info even though we're
not following redirects */
if(data->req.location) {
if(newurl)
free(newurl);
newurl = data->req.location;
data->req.location = NULL;
result = Curl_follow(data, newurl, FOLLOW_FAKE);
if(!result)
newurl = NULL; /* allocation was handed over Curl_follow() */
else
disconnect_conn = TRUE;
}
multistate(data, CURLM_STATE_DONE);
rc = CURLM_CALL_MULTI_PERFORM;
}
}
if(newurl)
free(newurl);
break;
}
case CURLM_STATE_DONE:
/* this state is highly transient, so run another loop after this */
rc = CURLM_CALL_MULTI_PERFORM;
if(data->easy_conn) {
CURLcode res;
/* Remove ourselves from the receive pipeline, if we are there. */
Curl_removeHandleFromPipeline(data, data->easy_conn->recv_pipe);
/* Check if we can move pending requests to send pipe */
Curl_multi_process_pending_handles(multi);
/* post-transfer command */
res = Curl_done(&data->easy_conn, result, FALSE);
/* allow a previously set error code take precedence */
if(!result)
result = res;
/*
* If there are other handles on the pipeline, Curl_done won't set
* easy_conn to NULL. In such a case, curl_multi_remove_handle() can
* access free'd data, if the connection is free'd and the handle
* removed before we perform the processing in CURLM_STATE_COMPLETED
*/
if(data->easy_conn)
data->easy_conn = NULL;
}
if(data->set.wildcardmatch) {
if(data->wildcard.state != CURLWC_DONE) {
/* if a wildcard is set and we are not ending -> lets start again
with CURLM_STATE_INIT */
multistate(data, CURLM_STATE_INIT);
break;
}
}
/* after we have DONE what we're supposed to do, go COMPLETED, and
it doesn't matter what the Curl_done() returned! */
multistate(data, CURLM_STATE_COMPLETED);
break;
case CURLM_STATE_COMPLETED:
/* this is a completed transfer, it is likely to still be connected */
/* This node should be delinked from the list now and we should post
an information message that we are complete. */
/* Important: reset the conn pointer so that we don't point to memory
that could be freed anytime */
data->easy_conn = NULL;
Curl_expire(data, 0); /* stop all timers */
break;
case CURLM_STATE_MSGSENT:
data->result = result;
return CURLM_OK; /* do nothing */
default:
return CURLM_INTERNAL_ERROR;
}
statemachine_end:
if(data->mstate < CURLM_STATE_COMPLETED) {
if(result) {
/*
* If an error was returned, and we aren't in completed state now,
* then we go to completed and consider this transfer aborted.
*/
/* NOTE: no attempt to disconnect connections must be made
in the case blocks above - cleanup happens only here */
data->state.pipe_broke = FALSE;
if(data->easy_conn) {
/* if this has a connection, unsubscribe from the pipelines */
data->easy_conn->writechannel_inuse = FALSE;
data->easy_conn->readchannel_inuse = FALSE;
Curl_removeHandleFromPipeline(data, data->easy_conn->send_pipe);
Curl_removeHandleFromPipeline(data, data->easy_conn->recv_pipe);
/* Check if we can move pending requests to send pipe */
Curl_multi_process_pending_handles(multi);
if(disconnect_conn) {
/* Don't attempt to send data over a connection that timed out */
bool dead_connection = result == CURLE_OPERATION_TIMEDOUT;
/* disconnect properly */
Curl_disconnect(data->easy_conn, dead_connection);
/* This is where we make sure that the easy_conn pointer is reset.
We don't have to do this in every case block above where a
failure is detected */
data->easy_conn = NULL;
}
}
else if(data->mstate == CURLM_STATE_CONNECT) {
/* Curl_connect() failed */
(void)Curl_posttransfer(data);
}
multistate(data, CURLM_STATE_COMPLETED);
}
/* if there's still a connection to use, call the progress function */
else if(data->easy_conn && Curl_pgrsUpdate(data->easy_conn)) {
/* aborted due to progress callback return code must close the
connection */
result = CURLE_ABORTED_BY_CALLBACK;
connclose(data->easy_conn, "Aborted by callback");
/* if not yet in DONE state, go there, otherwise COMPLETED */
multistate(data, (data->mstate < CURLM_STATE_DONE)?
CURLM_STATE_DONE: CURLM_STATE_COMPLETED);
rc = CURLM_CALL_MULTI_PERFORM;
}
}
if(CURLM_STATE_COMPLETED == data->mstate) {
/* now fill in the Curl_message with this info */
msg = &data->msg;
msg->extmsg.msg = CURLMSG_DONE;
msg->extmsg.easy_handle = data;
msg->extmsg.data.result = result;
rc = multi_addmsg(multi, msg);
multistate(data, CURLM_STATE_MSGSENT);
}
} while(rc == CURLM_CALL_MULTI_PERFORM);
data->result = result;
return rc;
} | [
"[email protected]"
]
| |
0137eb2ba53cc9f03c935a734d34d203439750e1 | 10bea6de3a5a661c7ef8745fd5993322ced929b1 | /src/states_screens/grand_prix_cutscene.cpp | 6a53d417a698da2ee522e5fc829564a1b51b6617 | []
| no_license | javascript3d/csdnblog | 6fb3f389b94ddc4523c606169f024b3899a813e1 | 3c5dd37bfd1850ed9a6738db6a65838e4ea60486 | refs/heads/master | 2021-07-17T12:26:12.598439 | 2017-10-20T14:06:43 | 2017-10-20T14:06:43 | 106,515,460 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,400 | cpp | // SuperTuxKart - a fun racing game with go-kart
// Copyright (C) 2014-2015 konstin
//
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#include "guiengine/scalable_font.hpp"
#include "guiengine/widgets/button_widget.hpp"
#include "modes/cutscene_world.hpp"
#include "race/grand_prix_data.hpp"
#include "race/grand_prix_manager.hpp"
#include "race/race_manager.hpp"
#include "states_screens/grand_prix_cutscene.hpp"
#include "tracks/track_manager.hpp"
#include <string>
#include <vector>
typedef GUIEngine::ButtonWidget Button;
/** A Button to save the GP if it was a random GP */
void GrandPrixCutscene::saveGPButton()
{
if (race_manager->getGrandPrix().getId() != GrandPrixData::getRandomGPID())
getWidget<Button>("save")->setVisible(false);
} // saveGPButton
// ----------------------------------------------------------------------------
/** \brief Creates a new GP with the same content as the current and saves it
* The GP that the race_manager provides can't be used because we need some
* functions and settings that the GP manager only gives us through
* createNewGP(). */
void GrandPrixCutscene::onNewGPWithName(const irr::core::stringw& name)
{
// create a new GP with the correct filename and a unique id
GrandPrixData* gp = grand_prix_manager->createNewGP(name);
const GrandPrixData current_gp = race_manager->getGrandPrix();
std::vector<std::string> tracks = current_gp.getTrackNames();
std::vector<int> laps = current_gp.getLaps();
std::vector<bool> reverse = current_gp.getReverse();
for (unsigned int i = 0; i < laps.size(); i++)
gp->addTrack(track_manager->getTrack(tracks[i]), laps[i], reverse[i]);
gp->writeToFile();
// Avoid double-save which can have bad side-effects
getWidget<Button>("save")->setVisible(false);
} // onNewGPWithName
// ----------------------------------------------------------------------------
void GrandPrixCutscene::eventCallback(GUIEngine::Widget* widget,
const std::string& name,
const int playerID)
{
if (name == "continue")
{
((CutsceneWorld*)World::getWorld())->abortCutscene();
}
else if (name == "save")
{
new EnterGPNameDialog(this, 0.5f, 0.4f);
}
} // eventCallback
// ----------------------------------------------------------------------------
bool GrandPrixCutscene::onEscapePressed()
{
((CutsceneWorld*)World::getWorld())->abortCutscene();
return false;
} // onEscapePressed
// ----------------------------------------------------------------------------
void GrandPrixCutscene::tearDown()
{
Screen::tearDown();
} // tearDown
| [
"[email protected]"
]
| |
62ad9e11ecc77d78828ad8a4d7563a8e19863a96 | fd595e2acd15d029141eeb53bd9095712a87b4d8 | /Desktop-Application/APP/include/DataBase/DataBase.h | 739256ec92f75f4f48c09cf42f4088f0b9f4e53c | [
"Apache-2.0"
]
| permissive | shalaga44/Contacts-Manage | 05b7ce4bcdcb34cac90aa4a61675a3f4b5a300b5 | fbe09ea563a384f542ecf079976fa1e432735d14 | refs/heads/main | 2023-02-15T11:14:33.221790 | 2021-01-07T00:01:40 | 2021-01-07T00:01:40 | 324,120,390 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,627 | h | //
// Created by shalaga44 on 1/5/21.
//
#ifndef DESKTOP_APPLICATION_DATABASE_H
#define DESKTOP_APPLICATION_DATABASE_H
#include <sqlite3.h>
#include <Models/ContactField/ContactField.h>
#include <Models/Contact/Contact.h>
#include <Utils/StringUtils/StringUtils.h>
#include <iostream>
#include <exception>
#include <utility>
#include <vector>
#include <string>
class Database {
private:
inline static const string DATABASE_CONTACT_TABLE_NAME = "Contact";
sqlite3 *DB = nullptr;
int status = 0;
inline static vector<Contact> contacts;
void createContactTable();
void addContactToDatabase(Contact contact);
void checkDataBaseIsOpen();
public:
explicit Database(const char *databasePath);
~Database();
void addContact(const Contact& contact);
vector<Contact> search(string searchText);
void remove(int index);
void edit(int index, ContactField field, string value);
Contact contactAt(int index);
vector<Contact> getAllContacts();
vector<Contact> getContactPage(int pageIndex, int PAGE_SIZE);
class DatabaseException : public exception {
public:
const char *msg;
explicit DatabaseException(const char *msg) {
this->msg = msg;
}
explicit DatabaseException( const char *text, const char *msg) {
this->msg = (string(text) +": "+ string(msg)).c_str();
}
~DatabaseException() noexcept override {
delete msg;
}
const char *what() const noexcept override {
return msg;
}
};
};
#endif //DESKTOP_APPLICATION_DATABASE_H
| [
"[email protected]"
]
| |
bf342b16130c7df45c08ffc2b7431565bddbf17a | 181614e93acb01d427bb57f8d52a0e5b40035a03 | /carpet_cleaning_service.cc | 194a91a6df87961ab95e1dd7e0f773a172a1ba31 | []
| no_license | automaticaddison/FirstEverCPPPrograms | 39e54aafce1678f15210d4e122f87539fb38f138 | a29622b68e95d40b1cf2ab5a7616af34f14ce734 | refs/heads/master | 2020-03-22T08:48:30.661119 | 2018-07-18T10:42:12 | 2018-07-18T10:42:12 | 139,792,208 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,189 | cc | /******************************************************************************
* @file carpet_cleaning_service.cc
* @author Addison Sears-Collins
* @date 7/14/2018
* @version 1.0
*
* @brief Provides a cost estimate for large and small rooms
*
* Purpose: This program prompts the user for the number of small and large
* rooms they would like cleaned and provides an estimate.
*****************************************************************************/
// Include iostream library to support the console input and output
#include <iostream>
// Use the standard namespace to avoid naming conflicts
using namespace std;
// The main method that drives the program
int main() {
cout << "Hello, welcome to Addison's Carpet Cleaning Service" << endl;
int small_rooms{0};
cout << "\nHow many small rooms would you like cleaned?" << endl;
cin >> small_rooms;
int large_rooms{0};
cout << "\nHow many large rooms would you like cleaned?" << endl;
cin >> large_rooms;
const double price_per_small_room {25.0};
const double price_per_large_room {35.0};
const double sales_tax {0.06};
const int estimate_expiry {30};
cout << "\nEstimate for carpet cleaning service" << endl;
cout << "Number of small rooms: " << small_rooms << endl;
cout << "Number of large rooms: " << large_rooms << endl;
cout << "Price per small room: $" << price_per_small_room << endl;
cout << "Price per large room: $" << price_per_large_room << endl;
cout << "Cost : $"
<< (price_per_small_room * small_rooms) +
(price_per_large_room * large_rooms)
<< endl;
cout << "Tax : $"
<< ((price_per_small_room * small_rooms) +
(price_per_large_room * large_rooms)) * sales_tax
<< endl;
cout << "====================================" << endl;
cout << "Total estimate : $"
<< ((price_per_small_room * small_rooms) +
(price_per_large_room * large_rooms)) +
((price_per_small_room * small_rooms) +
(price_per_large_room * large_rooms)) * sales_tax
<< endl;
cout << "This estimate is valid for " << estimate_expiry << " days" << endl;
cout << endl;
// Exit the program
return 0;
} | [
"[email protected]"
]
| |
fedf82866489d4862802f5a35767055ff38f3831 | 77e48af28c80985b2ade7952d4eb60fc07876949 | /include/xap/core/buffer/fetcher.h | 1a2616002077a6c44014ae8cc61e9f31c6f93da2 | [
"BSD-3-Clause"
]
| permissive | xaudioproject/xapcppcore-bufferutilities | a5f63cf7c19b9d054746e1c55b2502bb3147336d | d9c4d3062ce19f2655836be1b518a1ddfdabb6fb | refs/heads/master | 2023-06-02T19:09:56.698537 | 2021-06-10T12:12:20 | 2021-06-10T12:12:20 | 377,350,584 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,387 | h | //
// Copyright 2019 - 2021 The XOrange Studio. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE.md file.
//
#ifndef XAP_CORE_BUFFER_FETCHER_H__
#define XAP_CORE_BUFFER_FETCHER_H__
//
// Imports.
//
#include <memory>
#include <stdint.h>
#include <xap/core/buffer/buffer.h>
#include <xap/core/buffer/error.h>
namespace xap {
namespace core {
namespace buffer {
//
// Classes.
//
class BufferFetcher {
public:
//
// Constructor & destructor.
//
/**
* Cosntruct the object.
*
* @param buffer
* The buffer which would be fetched.
*/
BufferFetcher(const Buffer &buffer);
/**
* Construct (Copy) the object.
*
* @param src
* The source fetcher.
*/
BufferFetcher(const BufferFetcher &src) noexcept;
/**
* Destruct the object.
*/
~BufferFetcher() noexcept;
//
// Public operators.
//
/**
* Operator '='.
*
* @param src
* The source fetcher.
* @return
* The destination fetcher.
*/
BufferFetcher& operator=(const BufferFetcher& src) noexcept;
//
// Public methods.
//
/**
* Check whether the fetcher is ended.
*
* @return
* True if so.
*/
bool is_end() const noexcept;
/**
* Reset the fetcher. Move the cursor to the begin position.
*/
void reset() noexcept;
/**
* Fetch one byte.
*
* @throw BufferException
* Raised if the buffer fetcher was ended.
* @return
* The byte.
*/
uint8_t fetch();
/**
* Fetch bytes to buffer.
*
* @note
* Nothing would be done if destination size is zero.
* @throw BufferException
* Riased if the buffer fetcher was ended (XAPCORE_BUF_ERROR_OVERFLOW).
* @param destination
* The destination buffer.
* @return
* The number of bytes fetched.
*/
size_t fetch_to(Buffer &destination);
/**
* Fetch bytes to buffer.
*
* @note
* Nothing would be done if destination size is zero.
* @throw BufferException
* Raised if the buffer fetcher was ended (XAPCORE_BUF_ERROR_OVERFLOW).
* @param destination
* The destination buffer.
* @param destination_offset
* The offset of destination buffer.
* @return
* The number of bytes fetched.
*/
size_t fetch_to(Buffer &destination, const size_t destination_offset);
/**
* Fetch all bytes in buffer.
*
* @note
* Return zero-size buffer if fetcher is ended.
* @return
* The destination buffer.
*/
Buffer fetch_all();
/**
* Fetch bytes in buffer.
*
* @throw BufferException
* Parameter 'count' was out of range (XAPCORE_BUF_ERROR_OVERFLOW).
* @param count
* The count of bytes would be fetched.
* @return
* The destination count.
*/
Buffer fetch_bytes(const size_t count);
/**
* Skip bytes.
*
* @note
* Nothing would be done if 'count' = 0U.
* @throw BufferException
* Raised if parameter 'buffer' was out of range
* (XAPCORE_BUF_ERROR_OVERFLOW).
* @param count
* The count of bytes would be skiped.
*/
void skip(const size_t count);
/**
* Get the remaining size.
*
* @return
* The remaining size.
*/
size_t get_remaining_size() const noexcept;
/**
* Replace (reset) the fetch with another new buffer.
*
* @param new_buffer
* The buffer.
*/
void replace(const Buffer &new_buffer);
private:
//
// Private functions.
//
/**
* Expected fetcher was not ended.
*
* @throw BufferException
* Raised if not (XAPCORE_BUF_ERROR_OVERFLOW).
*/
void assert_not_eof();
//
// Members.
//
size_t m_cursor;
Buffer *m_buffer;
size_t m_buffer_length;
std::shared_ptr<Buffer> m_buffer_shared_pointer;
};
} // namespace buffer
} // namespace core
} // namespace xap
#endif // #ifndef XAP_CORE_BUFFER_FETCHER_H__ | [
"[email protected]"
]
| |
b1d90b6e745a22da4ed59a7c19a5ffdcb93a0e4c | 2ebe33d98157ef3088dc4e04c0a2dc5af0746103 | /src/noguiapp/main.cpp | a4f7e3619b60bfc26992f03eebf699560c982318 | []
| no_license | Acvaxoort/lucimalir | ee434f7627ed8386ac42d4c73a3dc275a130e4e5 | 78b748b8880fecdc803e1968583d957098442cec | refs/heads/master | 2022-11-16T15:03:10.893047 | 2020-06-27T18:26:28 | 2020-06-27T18:26:28 | 275,415,673 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,289 | cpp | #include <iostream>
#include <cstring>
#include <set>
#include <vector>
#include <core/Core.h>
#include "luaapi/LuaStateWrapper.h"
const char* HELP_STRING =
R"(Usage: lucimalir [options] [filename1 filename2 ...]
If no filename is present, it will open an interactive shell.
Options:
-h: display help
-i: open interactive mode after processing files
)";
bool process_options(const char* arg, std::set<char>& options) {
if (arg[0] != '-') {
return false;
}
int len = strlen(arg);
for (int i = 1; i < len; ++i) {
options.insert(arg[i]);
}
return true;
}
#define LUCIMALIR_VERSION "0.1"
int main(int argc, const char** argv) {
// fixes console output on CLion in debug configurations
#ifdef CLION_OUTPUT_DEBUG_FIX
setbuf(stdout, nullptr);
setbuf(stderr, nullptr);
#endif
try {
LuaStateWrapper lua_state(&std::cout, &std::cin, &std::cerr);
std::vector<std::string> filenames;
std::set<char> options;
for (int i = 1; i < argc; ++i) {
if (!process_options(argv[i], options)) {
filenames.emplace_back(argv[i]);
}
}
bool error = false;
for (auto& f : filenames) {
try {
lua_state.doFile(f.c_str());
} catch (std::exception& e) {
std::cerr << "Error while processing " << f << "\n" << e.what();
error = true;
break;
}
}
if (options.count('h')) {
std::cout << HELP_STRING;
return 0;
}
if ((filenames.empty() || options.count('i')) && !error) {
std::string input;
std::cout << "LUa Complex Interactive Mandelbrot-LIke fractal Renderer v"
<< LUCIMALIR_VERSION
<< "\nType \"help\" for help, \"exit\" to exit the program, \"reset\" to reset the lua state\n";
while (std::cin.good()) {
std::cout << "> ";
std::cout.flush();
std::getline(std::cin, input);
if (input == "exit") {
break;
} else if (input == "reset") {
lua_state.reset();
} else {
lua_state.doString(input);
}
}
}
auto& core = Core::getInstance();
core.awaitCompletion();
core.shutDown();
return error ? 1 : 0;
} catch (std::exception& e) {
std::cerr << "Fatal exception:\n" << e.what();
return 1;
}
}
| [
"[email protected]"
]
| |
e8595f3923dec1d96d01df13d21f76ea3935852b | 1ca1510d694d7435c16053088035644d6b13b4f2 | /outdoor_amr_ros2/marti_common/swri_roscpp/include/swri_roscpp/topic_service_client.h | ab0cabb84522331478d89505569af141f65a4e83 | []
| no_license | yangkang411/outdoor_amr_ros2 | 2b9c7049947b82eb512ebd7cb2671e3c653eb771 | c849a5b897fd8ed939d9b002b58cc24ddea69005 | refs/heads/main | 2023-06-16T09:37:13.738949 | 2021-07-13T13:48:36 | 2021-07-13T13:52:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,967 | h | // *****************************************************************************
//
// Copyright (c) 2018, Southwest Research Institute® (SwRI®)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of Southwest Research Institute® (SwRI®) 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 SOUTHWEST RESEARCH INSTITUTE 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.
//
// *****************************************************************************
#ifndef SWRI_ROSCPP_TOPIC_SERVICE_CLIENT_H_
#define SWRI_ROSCPP_TOPIC_SERVICE_CLIENT_H_
#include <rclcpp/rclcpp.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/uuid/random_generator.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <map>
namespace swri
{
template<class MReq, class MRes>
class TopicServiceClientRaw
{
private:
typedef
boost::mutex request_lock_;
std::shared_ptr<rclcpp::Subscription<MRes> > response_sub_;
std::shared_ptr<rclcpp::Publisher<MReq> > request_pub_;
std::shared_ptr<MRes> response_;
rclcpp::Duration timeout_;
std::string name_;
std::string service_name_;
int sequence_;
public:
TopicServiceClientRaw() :
timeout_(std::chrono::duration<float>(4.0)),
sequence_(0),
node_(nullptr)
{
}
void initialize(rclcpp::Node &nh,
const std::string &service,
const std::string &client_name = "")
{
node_ = &nh;
//Converts using string stream instead of to_string so non C++ 11 nodes won't fail
boost::uuids::random_generator gen;
boost::uuids::uuid u = gen();
std::string random_str = boost::uuids::to_string(u);
name_ = client_name.length() ? client_name : (nh.get_name() + random_str);
service_name_ = service;
request_pub_ = nh.create_publisher<MReq>(service + "/request", 10);
response_sub_ = nh.create_subscription<MRes>(service + "/response",
10, std::bind(&TopicServiceClientRaw<MReq, MRes>::response_callback, this, std::placeholders::_1));
}
bool call(MReq& request, MRes& response)
{
boost::mutex::scoped_lock scoped_lock(request_lock_);
// block for response
request.srv_header.stamp = node_->now();
request.srv_header.sequence = sequence_;
request.srv_header.sender = name_;
// Wait until we get a subscriber and publisher
while (request_pub_->get_subscription_count() == 0 || response_sub_->get_publisher_count() == 0)
{
rclcpp::sleep_for(std::chrono::milliseconds(2));
rclcpp::spin_some(node_->shared_from_this());
if (node_->now() - request.srv_header.stamp > timeout_)
{
RCLCPP_ERROR(node_->get_logger(), "Topic service timeout exceeded");
return false;
}
}
response_.reset();
request_pub_->publish(request);
// Wait until we get a response
while (!response_ && node_->now() - request.srv_header.stamp < timeout_)
{
rclcpp::sleep_for(std::chrono::milliseconds(2));
rclcpp::spin_some(node_->shared_from_this());
}
sequence_++;
if (response_)
{
response = *response_;
response_.reset();
return response.srv_header.result;
}
return false;
}
std::string getService()
{
return service_name_;
}
bool exists()
{
return request_pub_->get_subscription_count() > 0 && response_sub_->get_publisher_count() > 0;
}
// The service server can output a console log message when the
// service is called if desired.
void setLogCalls(bool enable);
bool logCalls() const;
private:
void response_callback(const std::shared_ptr<MRes> message)
{
RCLCPP_DEBUG(node_->get_logger(), "Got response for %s with sequence %i",
message->srv_header.sender.c_str(), message->srv_header.sequence);
if (message->srv_header.sender != name_)
{
RCLCPP_DEBUG(node_->get_logger(), "Got response from another client, ignoring..");
return;
}
if (message->srv_header.sequence != sequence_)
{
RCLCPP_WARN(node_->get_logger(), "Got wrong sequence number, ignoring..");
RCLCPP_DEBUG(node_->get_logger(), "message seq:%i vs current seq: %i", message->srv_header.sequence, sequence_);
return;
}
response_ = message;
}
rclcpp::Node* node_;
}; // class TopicServiceClientRaw
template<class MReq>
class TopicServiceClient: public TopicServiceClientRaw<typename MReq:: Request, typename MReq:: Response>
{
public:
bool call(MReq& req)
{
return TopicServiceClientRaw<typename MReq:: Request, typename MReq:: Response>::call(req.request, req.response);
}
}; // class TopicServiceClient
} // namespace swri
#endif // SWRI_ROSCPP_TOPIC_SERVICE_SERVER_H_
| [
"[email protected]"
]
| |
6d6382dc73f2ee09ad0b7f29c868485bfabb4161 | 126f3a35085c55d9090373fe4f7dbf836664402a | /lru-cache.cc | ff66714644ef3849040095c756fa19e0a8dbc65f | []
| no_license | XiangmingWang/leetcode_review | 0ff5f5b67323464d8ea8ccdb6be2e4660c42b2b0 | 8c955cad8eb37a4130617142196f311c3cf72186 | refs/heads/master | 2021-05-04T07:48:33.091400 | 2016-12-19T15:30:58 | 2016-12-19T15:30:58 | 70,694,204 | 0 | 0 | null | 2016-10-24T03:20:04 | 2016-10-12T11:42:05 | C++ | UTF-8 | C++ | false | false | 1,357 | cc | //https://leetcode.com/problems/lru-cache/
#include <iostream>
#include <list>
#include <utility>
#include <unordered_map>
using namespace std;
class LRUCache{
public:
LRUCache(int capacity) : capacity_(capacity) {}
int get(int key) {
auto iter = lru_map_.find(key);
if (iter == lru_map_.end()) return -1;
lru_list_.splice(lru_list_.begin(), lru_list_, iter->second);
return iter->second->second;
}
void set(int key, int value) {
auto iter = lru_map_.find(key);
if (iter != lru_map_.end()) {
iter->second->second = value;
lru_list_.splice(lru_list_.begin(), lru_list_, iter->second);
return;
}
if (capacity_ == lru_map_.size()) {
auto list_iter = lru_list_.end();
--list_iter;
lru_map_.erase(list_iter->first);
list_iter->first = key;
list_iter->second = value;
lru_list_.splice(lru_list_.begin(), lru_list_, list_iter);
} else {
lru_list_.push_front(make_pair(key, value));
}
lru_map_[key] = lru_list_.begin();
}
private:
size_t capacity_;
unordered_map<int, list<pair<int, int>>::iterator> lru_map_;
list<pair<int, int>> lru_list_;
};
int main() {
LRUCache cache(3);
int v[] = {1,2,3,4,5,6,7};
for (auto i : v) {
cache.set(i, i);
}
}
| [
"[email protected]"
]
| |
ead1fe339a56adf79a4354b2c5118faa0d723f36 | dd83262926063813e0a7c5d941ea623ec07100eb | /orbit_src/Exports/SavegameWriter.hpp | 5528522ea6ca6a9020b95edf528427663f505ea0 | []
| no_license | ReHamster/UPlayEmulator | b4089cd2a5887a38c7775ac4d765d631303b54ca | d3278e57a9ca90f14a2832dad5db11e11f26131a | refs/heads/master | 2023-06-29T07:16:03.915747 | 2021-08-01T19:42:23 | 2021-08-01T19:42:23 | 391,418,847 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,971 | hpp | #pragma once
#include "pch.h"
#include "Macro.hpp"
#include "Helpers/Saves.hpp"
#include "Utils/Singleton.hpp"
#include "Objects/OrbitConfig.hpp"
#include "Interfaces/ISavegameWriteListener.hpp"
// ReSharper disable CppInconsistentNaming
// ReSharper disable CppMemberFunctionMayBeConst
// ReSharper disable CppMemberFunctionMayBeStatic
// ReSharper disable CppParameterMayBeConst
namespace mg::orbitclient
{
using namespace std;
using namespace UbiorbitapiR2Loader;
using std::filesystem::path;
namespace fs = std::filesystem;
class UPLAY_CPP_API SavegameWriter
{
path FilePath{};
path NamePath{};
unsigned int SaveId;
public:
SavegameWriter(const path &filePath, const path &namePath, unsigned int saveId);
void Close(bool arg);
void Write(unsigned int requestId, ISavegameWriteListener *savegameWriteListenerCallBack, void *buff,
unsigned int numberOfBytes);
bool SetName(unsigned short *name);
void BackupSave(const string &backupPath);
};
} // namespace mg::orbitclient
//------------------------------------------------------------------------------
inline mg::orbitclient::SavegameWriter::SavegameWriter(const path &filePath, const path &namePath,
unsigned int saveId)
{
FilePath = filePath;
NamePath = namePath;
SaveId = saveId;
}
//------------------------------------------------------------------------------
inline void mg::orbitclient::SavegameWriter::BackupSave(const string &backupPath)
{
// ReSharper disable CppRedundantQualifier
if (!fs::exists(backupPath))
{
fs::create_directories(backupPath);
}
const auto backupFile = date::format("%m-%d-%Y %I-%M-%S UTC", chrono::system_clock::now());
const auto backupFilePath = path(backupPath) / path(
fmt::format("{}_{}.{}", SaveId, backupFile, SAVE_BACKUP_EXTENSION));
const auto backupFileNamePath = path(backupPath) / path(
fmt::format("{}_{}.{}", SaveId, backupFile, SAVE_NAME_EXTENSION));
fs::copy(FilePath, backupFilePath);
fs::copy(NamePath, backupFileNamePath);
// ReSharper restore CppRedundantQualifier
}
//------------------------------------------------------------------------------
inline void mg::orbitclient::SavegameWriter::Close(bool arg)
{
LOGD << "__CALL__";
}
//------------------------------------------------------------------------------
inline void mg::orbitclient::SavegameWriter::Write(unsigned int requestId,
ISavegameWriteListener *savegameWriteListenerCallBack, void *buff,
unsigned int numberOfBytes)
{
LOGD << fmt::format("RequestId: {} SavegameWriteListenerCallBack: {} Buff: {} NumberOfBytes: {}", requestId,
reinterpret_cast<void *>(&savegameWriteListenerCallBack), buff, numberOfBytes);
const auto callBack = reinterpret_cast<ISavegameWriteListener::CallBackPtrType>(**savegameWriteListenerCallBack->CallBackPtr);
if (callBack == nullptr)
{
return;
}
const auto &backup = Singleton<OrbitConfig>::Instance().Get().Orbit.Saves.Backup;
const auto savesPath = FilePath.parent_path();
// ReSharper disable CppRedundantQualifier
fs::create_directories(savesPath);
if (backup.Active && fs::exists(FilePath) && fs::exists(NamePath))
{
BackupSave(backup.Path);
}
// ReSharper restore CppRedundantQualifier
const auto bytesCount = WriteSave(FilePath, buff, numberOfBytes);
callBack(savegameWriteListenerCallBack, requestId, bytesCount);
}
//------------------------------------------------------------------------------
inline bool mg::orbitclient::SavegameWriter::SetName(unsigned short *name)
{
//LOGD << fmt::format("Name: {}", reinterpret_cast<wchar_t *>(name));
const auto nameString = ST::string(wstring(reinterpret_cast<wchar_t *>(name)));
WriteSaveName(NamePath, nameString.to_std_string());
return true;
}
// ReSharper restore CppInconsistentNaming
// ReSharper restore CppMemberFunctionMayBeConst
// ReSharper restore CppMemberFunctionMayBeStatic
// ReSharper restore CppParameterMayBeConst
| [
"[email protected]"
]
| |
901f989db145ab46bb25b29dc880215862fd7c5c | 9d952971cc5f7e20bdce5837adad46a5e26f6e60 | /2年次チーム制作/ソースファイル/source/MovieControllobj.h | d24c0c536078f9334a75a6817d7875e514210efb | []
| no_license | weimingtom/Game_SparklingWaterGun | c4b426b3f874a6b6d3528d0d1a711df0e5bd8f08 | 3fbface15f27f547964edc6c5d794b455ad37ea5 | refs/heads/master | 2021-01-20T10:32:07.167091 | 2016-04-01T15:59:50 | 2016-04-01T15:59:50 | null | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 851 | h | #ifndef __MOVIE_CONTROLL_OBJ_H__
#define __MOVIE_CONTROLL_OBJ_H__
#include "ControllObject.h"
#include "CODBOForwardDecl.h"
//***************************************************************
// ムービー用コントロールオブジェクト
//***************************************************************
class MovieControllobj :public ControllObject
{
public:
MovieControllobj(
ENTITY_ID myId,
int team_type,
TeamData* tData
);
~MovieControllobj();
private:
public:
Vector3 GetBodyCenter(){ return m_base_param.pos; }
void Controll();
void Update(TeamData& teamdata);
void Render(ControllObject& viewowner, TeamData& teamdata){}
void Render_ShadowMap(ControllObject& viewowner, TeamData& teamdata){}
void RenderUI(ControllObject& viewowner, TeamData& teamdata);
bool HandleMessage(LPGameMessage msg);
};
#endif | [
"[email protected]"
]
| |
315ea0a432c15f32a47f55b8509ba041c9168ff5 | eab1807e5f09e31a5cacc0ba1275eead24cea76e | /Martin/Qt/SiTTuGAs/Extras/bob_digital_pf1.cpp | 82b705e358691c6dea322d0d1f2fd4ffe24d099d | []
| no_license | mbravod/aeros | 8af48c0e3d1d9055195236915c951ddd730d219c | 239ba1fae4ab7a8f01aa58df4dfe627ac3f9e731 | refs/heads/master | 2016-09-05T12:40:15.205595 | 2014-01-09T21:29:49 | 2014-01-09T21:29:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 542 | cpp | #include "bob_digital_pf1.h"
#include "ui_bob_digital_pf1.h"
BOB_DIGITAL_PF1::BOB_DIGITAL_PF1(QWidget *parent) :
QWidget(parent),
ui(new Ui::BOB_DIGITAL_PF1)
{
ui->setupUi(this);
connect(ui->pushButton,SIGNAL(clicked()),this,SLOT(cerrar()));
}
BOB_DIGITAL_PF1::~BOB_DIGITAL_PF1()
{
delete ui;
}
void BOB_DIGITAL_PF1::cerrar()
{
this->close();
emit (cerrarVentana(false));
}
void BOB_DIGITAL_PF1::mousePressEvent(QMouseEvent *e)
{
if(e->button() == Qt::LeftButton){
emit (clicked(true));
}
}
| [
"[email protected]"
]
| |
ec9be9590537637e430b20d3bf48e360e27ac878 | d4ba636068fc2ffbb45f313012103afb9080c4e3 | /NuGenDimension/NuGenDimension/NuGenDimension/Dialogs/GetDialogs/SelectPointDlg.cpp | cbb45d606c7a7eec0fda81a121469890973833cb | []
| no_license | SHAREVIEW/GenXSource | 785ae187531e757860748a2e49d9b6a175c97402 | 5e5fe1d5816560ac41a117210fd40a314536f7a4 | refs/heads/master | 2020-07-20T22:05:24.794801 | 2019-09-06T05:00:39 | 2019-09-06T05:00:39 | 206,716,265 | 0 | 0 | null | 2019-09-06T05:00:12 | 2019-09-06T05:00:12 | null | WINDOWS-1251 | C++ | false | false | 5,498 | cpp | // SelectPointDlg.cpp : implementation file
//
#include "stdafx.h"
#include "..//..//NuGenDimension.h"
#include "SelectPointDlg.h"
#include ".\selectpointdlg.h"
// CSelectPointDlg dialog
IMPLEMENT_DYNAMIC(CSelectPointDlg, CDialog)
CSelectPointDlg::CSelectPointDlg(CWnd* pParent /*=NULL*/)
: CDialog(CSelectPointDlg::IDD, pParent)
{
m_enable_history = NULL;
m_was_diasabled = false;
}
CSelectPointDlg::~CSelectPointDlg()
{
m_points.clear();
if (m_enable_history)
delete[] m_enable_history;
}
void CSelectPointDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Control(pDX, IDC_SELECT_POINT_LIST, m_list);
}
BEGIN_MESSAGE_MAP(CSelectPointDlg, CDialog)
ON_WM_SIZE()
ON_NOTIFY(LVN_GETDISPINFO, IDC_SELECT_POINT_LIST, OnLvnGetdispinfoSelectPointList)
ON_NOTIFY(NM_CLICK, IDC_SELECT_POINT_LIST, OnNMClickSelectPointList)
ON_WM_ERASEBKGND()
ON_BN_CLICKED(IDC_SELECT_POINT_FINISH_BUTTON, OnBnClickedSelectPointFinishButton)
END_MESSAGE_MAP()
IBaseInterfaceOfGetDialogs::DLG_TYPE CSelectPointDlg::GetType()
{
return IBaseInterfaceOfGetDialogs::SELECT_POINT_DLG;
}
CWnd* CSelectPointDlg::GetWindow()
{
return this;
}
void CSelectPointDlg::EnableControls(bool enbl)
{
if (m_enable_history==NULL)
m_enable_history = new bool[2];
if (enbl)
{
GetDlgItem(IDC_SELECT_POINT_LIST)->EnableWindow(m_enable_history[0]);
GetDlgItem(IDC_SELECT_POINT_FINISH_BUTTON)->EnableWindow(m_enable_history[1]);
m_was_diasabled = false;
}
else
{
if (!m_was_diasabled)
{
m_enable_history[0] = GetDlgItem(IDC_SELECT_POINT_LIST)->IsWindowEnabled()!=0;
m_enable_history[1] = GetDlgItem(IDC_SELECT_POINT_FINISH_BUTTON)->IsWindowEnabled()!=0;
}
GetDlgItem(IDC_SELECT_POINT_LIST)->EnableWindow(FALSE);
GetDlgItem(IDC_SELECT_POINT_FINISH_BUTTON)->EnableWindow(FALSE);
m_was_diasabled = true;
}
Invalidate();
}
void CSelectPointDlg::AddPoint(double xP,double yP,double zP)
{
PNTS tmpS;
tmpS.pX = xP;
tmpS.pY = yP;
tmpS.pZ = zP;
tmpS.pStr.Format("X=%f Y=%f Z=%f",xP,yP,zP);
m_points.push_back(tmpS);
m_list.SetItemCount(m_points.size());
}
void CSelectPointDlg::RemoveAllPoints()
{
m_list.DeleteAllItems();
m_points.clear();
m_list.SetItemCount(0);
}
void CSelectPointDlg::SetCurrentPoint(unsigned int ind)
{
if (ind>=m_points.size())
return;
m_list.SetItemState(ind, LVNI_SELECTED, LVNI_SELECTED);
}
unsigned int CSelectPointDlg::GetCurrentPoint()
{
POSITION pos = m_list.GetFirstSelectedItemPosition();
return m_list.GetNextSelectedItem(pos);
}
// CSelectPointDlg message handlers
void CSelectPointDlg::OnCancel()
{
// TODO: Add your specialized code here and/or call the base class
//CDialog::OnCancel();
}
void CSelectPointDlg::OnOK()
{
// TODO: Add your specialized code here and/or call the base class
//CDialog::OnOK();
}
BOOL CSelectPointDlg::OnInitDialog()
{
CDialog::OnInitDialog();
//m_list.SubclassDlgItem(IDC_SELECT_POINT_LIST, this);
m_list.InsertColumn(0,"");
CRect rct;
m_list.GetWindowRect(rct);
m_list.SetColumnWidth(0,rct.Width());
// Разрешаем использовать иконки состояния
//m_list.SendMessage( LVM_SETCALLBACKMASK , LVIS_STATEIMAGEMASK , 0);
// Выделение во всю строку, рисование сетки
m_list.SetExtendedStyle(LVS_EX_GRIDLINES|LVS_EX_FULLROWSELECT);
m_list.SetMultiSelectMode(false);
//m_list.ModifyStyle(WS_BORDER,0, 0);
//m_list.ModifyStyleEx(WS_EX_CLIENTEDGE,WS_EX_TRANSPARENT,SWP_DRAWFRAME|SWP_FRAMECHANGED);
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
void CSelectPointDlg::OnSize(UINT nType, int cx, int cy)
{
__super::OnSize(nType, cx, cy);
if (::IsWindow(m_list.m_hWnd))
{
CRect rrr;
m_list.GetWindowRect(rrr);
ScreenToClient(rrr);
m_list.MoveWindow(rrr.left,rrr.top,
cx-2*rrr.left,rrr.Height());
m_list.GetWindowRect(rrr);
m_list.SetColumnWidth(0,rrr.Width()-5);
}
}
void CSelectPointDlg::OnLvnGetdispinfoSelectPointList(NMHDR *pNMHDR, LRESULT *pResult)
{
LV_DISPINFO* pDispInfo = (LV_DISPINFO*)pNMHDR;
LV_ITEM* pItem= &(pDispInfo)->item;
DWORD n = pItem->iItem;
if (n<0 || n>=m_points.size())
return;
if (pItem->mask & LVIF_TEXT) // требуется текст элемента?
{ //strcpy( pItem->pszText, m_points[n].pStr); #OBSOLETE RISK
strcpy_s(pItem->pszText, 255, m_points[n].pStr);
}
/*if (pItem->mask & LVIF_IMAGE) // требуются картинки?
{
pItem->iImage = pDoc->GetImage(n);
pItem->state = pDoc->GetStateImage(n);
}*/
*pResult = 0;
}
void CSelectPointDlg::OnNMClickSelectPointList(NMHDR *pNMHDR, LRESULT *pResult)
{
NMITEMACTIVATE* nm=(NMITEMACTIVATE*)pNMHDR;
int s = nm->iItem;
int d=nm->iSubItem;
if (global_commander)
global_commander->SendCommanderMessage(ICommander::CM_UPDATE_COMMAND_PANEL,NULL);
}
BOOL CSelectPointDlg::OnEraseBkgnd(CDC* pDC)
{
// TODO: Add your message handler code here and/or call default
return TRUE;//__super::OnEraseBkgnd(pDC);
}
void CSelectPointDlg::OnBnClickedSelectPointFinishButton()
{
if(global_commander)
{
MSG ms;
ms.message = WM_KEYDOWN;
ms.wParam=VK_RETURN;
global_commander->PreTranslateMessage(&ms);
}
else
{
ASSERT(0);
}
}
| [
"[email protected]"
]
| |
a4d6179427026cd17cea6cea0f55f9a30a7b8d6c | 612325535126eaddebc230d8c27af095c8e5cc2f | /src/net/cert/cert_verify_proc_unittest.cc | 667bc7784d90ae469fd6f09a2a01fcdac3a049eb | [
"BSD-3-Clause"
]
| permissive | TrellixVulnTeam/proto-quic_1V94 | 1a3a03ac7a08a494b3d4e9857b24bb8f2c2cd673 | feee14d96ee95313f236e0f0e3ff7719246c84f7 | refs/heads/master | 2023-04-01T14:36:53.888576 | 2019-10-17T02:23:04 | 2019-10-17T02:23:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 99,758 | cc | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/cert/cert_verify_proc.h"
#include <vector>
#include "base/callback_helpers.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/logging.h"
#include "base/macros.h"
#include "base/sha1.h"
#include "base/strings/string_number_conversions.h"
#include "base/test/histogram_tester.h"
#include "base/test/scoped_feature_list.h"
#include "build/build_config.h"
#include "crypto/sha2.h"
#include "net/base/net_errors.h"
#include "net/cert/asn1_util.h"
#include "net/cert/cert_status_flags.h"
#include "net/cert/cert_verifier.h"
#include "net/cert/cert_verify_proc_builtin.h"
#include "net/cert/cert_verify_result.h"
#include "net/cert/crl_set.h"
#include "net/cert/crl_set_storage.h"
#include "net/cert/internal/signature_algorithm.h"
#include "net/cert/test_root_certs.h"
#include "net/cert/x509_certificate.h"
#include "net/der/input.h"
#include "net/der/parser.h"
#include "net/test/cert_test_util.h"
#include "net/test/gtest_util.h"
#include "net/test/test_certificate_data.h"
#include "net/test/test_data_directory.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#if defined(OS_ANDROID)
#include "base/android/build_info.h"
#endif
#if defined(OS_MACOSX) && !defined(OS_IOS)
#include "base/mac/mac_util.h"
#endif
#if defined(OS_WIN)
#include "base/win/windows_version.h"
#endif
// TODO(crbug.com/649017): Add tests that only certificates with
// serverAuth are accepted.
using net::test::IsError;
using net::test::IsOk;
using base::HexEncode;
namespace net {
namespace {
const char kTLSFeatureExtensionHistogram[] =
"Net.Certificate.TLSFeatureExtensionWithPrivateRoot";
const char kTLSFeatureExtensionOCSPHistogram[] =
"Net.Certificate.TLSFeatureExtensionWithPrivateRootHasOCSP";
// Mock CertVerifyProc that sets the CertVerifyResult to a given value for
// all certificates that are Verify()'d
class MockCertVerifyProc : public CertVerifyProc {
public:
explicit MockCertVerifyProc(const CertVerifyResult& result)
: result_(result) {}
// CertVerifyProc implementation:
bool SupportsAdditionalTrustAnchors() const override { return false; }
bool SupportsOCSPStapling() const override { return false; }
protected:
~MockCertVerifyProc() override {}
private:
int VerifyInternal(X509Certificate* cert,
const std::string& hostname,
const std::string& ocsp_response,
int flags,
CRLSet* crl_set,
const CertificateList& additional_trust_anchors,
CertVerifyResult* verify_result) override;
const CertVerifyResult result_;
DISALLOW_COPY_AND_ASSIGN(MockCertVerifyProc);
};
int MockCertVerifyProc::VerifyInternal(
X509Certificate* cert,
const std::string& hostname,
const std::string& ocsp_response,
int flags,
CRLSet* crl_set,
const CertificateList& additional_trust_anchors,
CertVerifyResult* verify_result) {
*verify_result = result_;
verify_result->verified_cert = cert;
return OK;
}
// This enum identifies a concrete implemenation of CertVerifyProc.
//
// The type is erased by CertVerifyProc::CreateDefault(), however
// needs to be known for some of the test expectations.
enum CertVerifyProcType {
CERT_VERIFY_PROC_NSS,
CERT_VERIFY_PROC_ANDROID,
CERT_VERIFY_PROC_IOS,
CERT_VERIFY_PROC_MAC,
CERT_VERIFY_PROC_WIN,
CERT_VERIFY_PROC_BUILTIN,
};
// Returns the CertVerifyProcType corresponding to what
// CertVerifyProc::CreateDefault() returns. This needs to be kept in sync with
// CreateDefault().
CertVerifyProcType GetDefaultCertVerifyProcType() {
#if defined(USE_NSS_CERTS)
return CERT_VERIFY_PROC_NSS;
#elif defined(OS_ANDROID)
return CERT_VERIFY_PROC_ANDROID;
#elif defined(OS_IOS)
return CERT_VERIFY_PROC_IOS;
#elif defined(OS_MACOSX)
return CERT_VERIFY_PROC_MAC;
#elif defined(OS_WIN)
return CERT_VERIFY_PROC_WIN;
#else
// Will fail to compile.
#endif
}
// Whether the test is running within the iphone simulator.
const bool kTargetIsIphoneSimulator =
#if TARGET_IPHONE_SIMULATOR
true;
#else
false;
#endif
// Returns a textual description of the CertVerifyProc implementation
// that is being tested, used to give better names to parameterized
// tests.
std::string VerifyProcTypeToName(
const testing::TestParamInfo<CertVerifyProcType>& params) {
switch (params.param) {
case CERT_VERIFY_PROC_NSS:
return "CertVerifyProcNSS";
case CERT_VERIFY_PROC_ANDROID:
return "CertVerifyProcAndroid";
case CERT_VERIFY_PROC_IOS:
return "CertVerifyProcIOS";
case CERT_VERIFY_PROC_MAC:
return "CertVerifyProcMac";
case CERT_VERIFY_PROC_WIN:
return "CertVerifyProcWin";
case CERT_VERIFY_PROC_BUILTIN:
return "CertVerifyProcBuiltin";
}
return nullptr;
}
// The set of all CertVerifyProcTypes that tests should be
// parameterized on.
const std::vector<CertVerifyProcType> kAllCertVerifiers = {
GetDefaultCertVerifyProcType()
// TODO(crbug.com/649017): Enable this everywhere. Right now this is
// gated on having CertVerifyProcBuiltin understand the roots added
// via TestRootCerts.
#if defined(USE_NSS_CERTS)
,
CERT_VERIFY_PROC_BUILTIN
#endif
};
} // namespace
// This fixture is for tests that apply to concrete implementations of
// CertVerifyProc. It will be run for all of the concrete CertVerifyProc types.
//
// It is called "Internal" as it tests the internal methods like
// "VerifyInternal()".
class CertVerifyProcInternalTest
: public testing::TestWithParam<CertVerifyProcType> {
protected:
void SetUp() override {
CertVerifyProcType type = verify_proc_type();
if (type == CERT_VERIFY_PROC_BUILTIN) {
verify_proc_ = CreateCertVerifyProcBuiltin();
} else if (type == GetDefaultCertVerifyProcType()) {
verify_proc_ = CertVerifyProc::CreateDefault();
} else {
ADD_FAILURE() << "Unhandled CertVerifyProcType";
}
}
int Verify(X509Certificate* cert,
const std::string& hostname,
int flags,
CRLSet* crl_set,
const CertificateList& additional_trust_anchors,
CertVerifyResult* verify_result) {
return verify_proc_->Verify(cert, hostname, std::string(), flags, crl_set,
additional_trust_anchors, verify_result);
}
CertVerifyProcType verify_proc_type() const { return GetParam(); }
bool SupportsAdditionalTrustAnchors() const {
return verify_proc_->SupportsAdditionalTrustAnchors();
}
bool SupportsReturningVerifiedChain() const {
#if defined(OS_ANDROID)
// Before API level 17, Android does not expose the APIs necessary to get at
// the verified certificate chain.
if (verify_proc_type() == CERT_VERIFY_PROC_ANDROID &&
base::android::BuildInfo::GetInstance()->sdk_int() < 17)
return false;
#endif
return true;
}
bool SupportsDetectingKnownRoots() const {
#if defined(OS_ANDROID)
// Before API level 17, Android does not expose the APIs necessary to get at
// the verified certificate chain and detect known roots.
if (verify_proc_type() == CERT_VERIFY_PROC_ANDROID)
return base::android::BuildInfo::GetInstance()->sdk_int() >= 17;
#endif
// iOS does not expose the APIs necessary to get the known system roots.
if (verify_proc_type() == CERT_VERIFY_PROC_IOS)
return false;
return true;
}
bool WeakKeysAreInvalid() const {
#if defined(OS_MACOSX) && !defined(OS_IOS)
// Starting with Mac OS 10.12, certs with weak keys are treated as
// (recoverable) invalid certificate errors.
if (verify_proc_type() == CERT_VERIFY_PROC_MAC &&
base::mac::IsAtLeastOS10_12()) {
return true;
}
#endif
return false;
}
bool SupportsCRLSet() const {
// TODO(crbug.com/649017): Return true for CERT_VERIFY_PROC_BUILTIN.
return verify_proc_type() == CERT_VERIFY_PROC_NSS ||
verify_proc_type() == CERT_VERIFY_PROC_WIN ||
verify_proc_type() == CERT_VERIFY_PROC_MAC;
}
bool SupportsCRLSetsInPathBuilding() const {
// TODO(crbug.com/649017): Return true for CERT_VERIFY_PROC_BUILTIN.
return verify_proc_type() == CERT_VERIFY_PROC_WIN ||
verify_proc_type() == CERT_VERIFY_PROC_NSS;
}
bool SupportsEV() const {
// TODO(crbug.com/649017): CertVerifyProcBuiltin does not support EV.
// TODO(crbug.com/117478): Android and iOS do not support EV.
return verify_proc_type() == CERT_VERIFY_PROC_NSS ||
verify_proc_type() == CERT_VERIFY_PROC_WIN ||
verify_proc_type() == CERT_VERIFY_PROC_MAC;
}
CertVerifyProc* verify_proc() const { return verify_proc_.get(); }
private:
scoped_refptr<CertVerifyProc> verify_proc_;
};
INSTANTIATE_TEST_CASE_P(,
CertVerifyProcInternalTest,
testing::ValuesIn(kAllCertVerifiers),
VerifyProcTypeToName);
// TODO(rsleevi): Reenable this test once comodo.chaim.pem is no longer
// expired, http://crbug.com/502818
TEST_P(CertVerifyProcInternalTest, DISABLED_EVVerification) {
if (!SupportsEV()) {
LOG(INFO) << "Skipping test as EV verification is not yet supported";
return;
}
scoped_refptr<X509Certificate> comodo_chain = CreateCertificateChainFromFile(
GetTestCertsDirectory(), "comodo.chain.pem",
X509Certificate::FORMAT_PEM_CERT_SEQUENCE);
ASSERT_TRUE(comodo_chain);
ASSERT_EQ(2U, comodo_chain->GetIntermediateCertificates().size());
scoped_refptr<CRLSet> crl_set(CRLSet::ForTesting(false, NULL, ""));
CertVerifyResult verify_result;
int flags = CertVerifier::VERIFY_EV_CERT;
int error = Verify(comodo_chain.get(), "comodo.com", flags, crl_set.get(),
CertificateList(), &verify_result);
EXPECT_THAT(error, IsOk());
EXPECT_TRUE(verify_result.cert_status & CERT_STATUS_IS_EV);
}
// Tests that a certificate is recognized as EV, when the valid EV policy OID
// for the trust anchor is the second candidate EV oid in the target
// certificate. This is a regression test for crbug.com/705285.
TEST_P(CertVerifyProcInternalTest, EVVerificationMultipleOID) {
if (!SupportsEV()) {
LOG(INFO) << "Skipping test as EV verification is not yet supported";
return;
}
// TODO(eroman): Update this test to use a synthetic certificate, so the test
// does not break in the future. The certificate chain in question expires on
// Dec 22 23:59:59 2018 GMT 2018, at which point this test will start failing.
if (base::Time::Now() >
base::Time::UnixEpoch() + base::TimeDelta::FromSeconds(1545523199)) {
FAIL() << "This test uses a certificate chain which is now expired. Please "
"disable and file a bug.";
return;
}
scoped_refptr<X509Certificate> chain = CreateCertificateChainFromFile(
GetTestCertsDirectory(), "trustcenter.websecurity.symantec.com.pem",
X509Certificate::FORMAT_PEM_CERT_SEQUENCE);
ASSERT_TRUE(chain);
scoped_refptr<CRLSet> crl_set(CRLSet::ForTesting(false, NULL, ""));
CertVerifyResult verify_result;
int flags = CertVerifier::VERIFY_EV_CERT;
int error = Verify(chain.get(), "trustcenter.websecurity.symantec.com", flags,
crl_set.get(), CertificateList(), &verify_result);
EXPECT_THAT(error, IsOk());
EXPECT_TRUE(verify_result.cert_status & CERT_STATUS_IS_EV);
}
// TODO(crbug.com/605457): the test expectation was incorrect on some
// configurations, so disable the test until it is fixed (better to have
// a bug to track a failing test than a false sense of security due to
// false positive).
TEST_P(CertVerifyProcInternalTest, DISABLED_PaypalNullCertParsing) {
// A certificate for www.paypal.com with a NULL byte in the common name.
// From http://www.gossamer-threads.com/lists/fulldisc/full-disclosure/70363
SHA256HashValue paypal_null_fingerprint = {{0x00}};
scoped_refptr<X509Certificate> paypal_null_cert(
X509Certificate::CreateFromBytes(
reinterpret_cast<const char*>(paypal_null_der),
sizeof(paypal_null_der)));
ASSERT_NE(static_cast<X509Certificate*>(NULL), paypal_null_cert.get());
EXPECT_EQ(paypal_null_fingerprint, X509Certificate::CalculateFingerprint256(
paypal_null_cert->os_cert_handle()));
int flags = 0;
CertVerifyResult verify_result;
int error = Verify(paypal_null_cert.get(), "www.paypal.com", flags, NULL,
CertificateList(), &verify_result);
if (verify_proc_type() == CERT_VERIFY_PROC_NSS ||
verify_proc_type() == CERT_VERIFY_PROC_ANDROID) {
EXPECT_THAT(error, IsError(ERR_CERT_COMMON_NAME_INVALID));
} else if (verify_proc_type() == CERT_VERIFY_PROC_IOS &&
kTargetIsIphoneSimulator) {
// iOS returns a ERR_CERT_INVALID error on the simulator, while returning
// ERR_CERT_AUTHORITY_INVALID on the real device.
EXPECT_THAT(error, IsError(ERR_CERT_INVALID));
} else {
// TOOD(bulach): investigate why macosx and win aren't returning
// ERR_CERT_INVALID or ERR_CERT_COMMON_NAME_INVALID.
EXPECT_THAT(error, IsError(ERR_CERT_AUTHORITY_INVALID));
}
// Either the system crypto library should correctly report a certificate
// name mismatch, or our certificate blacklist should cause us to report an
// invalid certificate.
if (verify_proc_type() == CERT_VERIFY_PROC_NSS ||
verify_proc_type() == CERT_VERIFY_PROC_WIN) {
EXPECT_TRUE(verify_result.cert_status &
(CERT_STATUS_COMMON_NAME_INVALID | CERT_STATUS_INVALID));
}
// TODO(crbug.com/649017): What expectations to use for the other verifiers?
}
#if BUILDFLAG(USE_BYTE_CERTS)
// Tests the case where the target certificate is accepted by
// X509CertificateBytes, but has errors that should cause verification to fail.
TEST_P(CertVerifyProcInternalTest, InvalidTarget) {
base::FilePath certs_dir =
GetTestNetDataDirectory().AppendASCII("parse_certificate_unittest");
scoped_refptr<X509Certificate> bad_cert =
ImportCertFromFile(certs_dir, "extensions_data_after_sequence.pem");
ASSERT_TRUE(bad_cert);
scoped_refptr<X509Certificate> ok_cert(
ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem"));
ASSERT_TRUE(ok_cert);
scoped_refptr<X509Certificate> cert_with_bad_target(
X509Certificate::CreateFromHandle(bad_cert->os_cert_handle(),
{ok_cert->os_cert_handle()}));
ASSERT_TRUE(cert_with_bad_target);
EXPECT_EQ(1U, cert_with_bad_target->GetIntermediateCertificates().size());
int flags = 0;
CertVerifyResult verify_result;
int error = Verify(cert_with_bad_target.get(), "127.0.0.1", flags, NULL,
CertificateList(), &verify_result);
EXPECT_TRUE(verify_result.cert_status & CERT_STATUS_INVALID);
EXPECT_THAT(error, IsError(ERR_CERT_INVALID));
}
// Tests the case where an intermediate certificate is accepted by
// X509CertificateBytes, but has errors that should cause verification to fail.
TEST_P(CertVerifyProcInternalTest, InvalidIntermediate) {
base::FilePath certs_dir =
GetTestNetDataDirectory().AppendASCII("parse_certificate_unittest");
scoped_refptr<X509Certificate> bad_cert =
ImportCertFromFile(certs_dir, "extensions_data_after_sequence.pem");
ASSERT_TRUE(bad_cert);
scoped_refptr<X509Certificate> ok_cert(
ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem"));
ASSERT_TRUE(ok_cert);
scoped_refptr<X509Certificate> cert_with_bad_intermediate(
X509Certificate::CreateFromHandle(ok_cert->os_cert_handle(),
{bad_cert->os_cert_handle()}));
ASSERT_TRUE(cert_with_bad_intermediate);
EXPECT_EQ(1U,
cert_with_bad_intermediate->GetIntermediateCertificates().size());
int flags = 0;
CertVerifyResult verify_result;
int error = Verify(cert_with_bad_intermediate.get(), "127.0.0.1", flags, NULL,
CertificateList(), &verify_result);
EXPECT_TRUE(verify_result.cert_status & CERT_STATUS_INVALID);
EXPECT_THAT(error, IsError(ERR_CERT_INVALID));
}
#endif // BUILDFLAG(USE_BYTE_CERTS)
// A regression test for http://crbug.com/31497.
TEST_P(CertVerifyProcInternalTest, IntermediateCARequireExplicitPolicy) {
if (verify_proc_type() == CERT_VERIFY_PROC_ANDROID) {
// Disabled on Android, as the Android verification libraries require an
// explicit policy to be specified, even when anyPolicy is permitted.
LOG(INFO) << "Skipping test on Android";
return;
}
base::FilePath certs_dir = GetTestCertsDirectory();
CertificateList certs = CreateCertificateListFromFile(
certs_dir, "explicit-policy-chain.pem", X509Certificate::FORMAT_AUTO);
ASSERT_EQ(3U, certs.size());
X509Certificate::OSCertHandles intermediates;
intermediates.push_back(certs[1]->os_cert_handle());
scoped_refptr<X509Certificate> cert = X509Certificate::CreateFromHandle(
certs[0]->os_cert_handle(), intermediates);
ASSERT_TRUE(cert.get());
ScopedTestRoot scoped_root(certs[2].get());
int flags = 0;
CertVerifyResult verify_result;
int error = Verify(cert.get(), "policy_test.example", flags, NULL,
CertificateList(), &verify_result);
EXPECT_THAT(error, IsOk());
EXPECT_EQ(0u, verify_result.cert_status);
}
TEST_P(CertVerifyProcInternalTest, RejectExpiredCert) {
base::FilePath certs_dir = GetTestCertsDirectory();
// Load root_ca_cert.pem into the test root store.
ScopedTestRoot test_root(
ImportCertFromFile(certs_dir, "root_ca_cert.pem").get());
scoped_refptr<X509Certificate> cert = CreateCertificateChainFromFile(
certs_dir, "expired_cert.pem", X509Certificate::FORMAT_AUTO);
ASSERT_TRUE(cert);
ASSERT_EQ(0U, cert->GetIntermediateCertificates().size());
int flags = 0;
CertVerifyResult verify_result;
int error = Verify(cert.get(), "127.0.0.1", flags, NULL, CertificateList(),
&verify_result);
EXPECT_THAT(error, IsError(ERR_CERT_DATE_INVALID));
EXPECT_TRUE(verify_result.cert_status & CERT_STATUS_DATE_INVALID);
}
// Currently, only RSA and DSA keys are checked for weakness, and our example
// weak size is 768. These could change in the future.
//
// Note that this means there may be false negatives: keys for other
// algorithms and which are weak will pass this test.
static bool IsWeakKeyType(const std::string& key_type) {
size_t pos = key_type.find("-");
std::string size = key_type.substr(0, pos);
std::string type = key_type.substr(pos + 1);
if (type == "rsa" || type == "dsa")
return size == "768";
return false;
}
TEST_P(CertVerifyProcInternalTest, RejectWeakKeys) {
base::FilePath certs_dir = GetTestCertsDirectory();
typedef std::vector<std::string> Strings;
Strings key_types;
// generate-weak-test-chains.sh currently has:
// key_types="768-rsa 1024-rsa 2048-rsa prime256v1-ecdsa"
// We must use the same key types here. The filenames generated look like:
// 2048-rsa-ee-by-768-rsa-intermediate.pem
key_types.push_back("768-rsa");
key_types.push_back("1024-rsa");
key_types.push_back("2048-rsa");
key_types.push_back("prime256v1-ecdsa");
// Add the root that signed the intermediates for this test.
scoped_refptr<X509Certificate> root_cert =
ImportCertFromFile(certs_dir, "2048-rsa-root.pem");
ASSERT_NE(static_cast<X509Certificate*>(NULL), root_cert.get());
ScopedTestRoot scoped_root(root_cert.get());
// Now test each chain.
for (Strings::const_iterator ee_type = key_types.begin();
ee_type != key_types.end(); ++ee_type) {
for (Strings::const_iterator signer_type = key_types.begin();
signer_type != key_types.end(); ++signer_type) {
std::string basename =
*ee_type + "-ee-by-" + *signer_type + "-intermediate.pem";
SCOPED_TRACE(basename);
scoped_refptr<X509Certificate> ee_cert =
ImportCertFromFile(certs_dir, basename);
ASSERT_NE(static_cast<X509Certificate*>(NULL), ee_cert.get());
basename = *signer_type + "-intermediate.pem";
scoped_refptr<X509Certificate> intermediate =
ImportCertFromFile(certs_dir, basename);
ASSERT_NE(static_cast<X509Certificate*>(NULL), intermediate.get());
X509Certificate::OSCertHandles intermediates;
intermediates.push_back(intermediate->os_cert_handle());
scoped_refptr<X509Certificate> cert_chain =
X509Certificate::CreateFromHandle(ee_cert->os_cert_handle(),
intermediates);
ASSERT_TRUE(cert_chain);
CertVerifyResult verify_result;
int error = Verify(cert_chain.get(), "127.0.0.1", 0, NULL,
CertificateList(), &verify_result);
if (IsWeakKeyType(*ee_type) || IsWeakKeyType(*signer_type)) {
EXPECT_NE(OK, error);
EXPECT_EQ(CERT_STATUS_WEAK_KEY,
verify_result.cert_status & CERT_STATUS_WEAK_KEY);
EXPECT_EQ(WeakKeysAreInvalid() ? CERT_STATUS_INVALID : 0,
verify_result.cert_status & CERT_STATUS_INVALID);
} else {
EXPECT_THAT(error, IsOk());
EXPECT_EQ(0U, verify_result.cert_status & CERT_STATUS_WEAK_KEY);
}
}
}
}
// Regression test for http://crbug.com/108514.
TEST_P(CertVerifyProcInternalTest, ExtraneousMD5RootCert) {
if (!SupportsReturningVerifiedChain()) {
LOG(INFO) << "Skipping this test in this platform.";
return;
}
if (verify_proc_type() == CERT_VERIFY_PROC_MAC) {
// Disabled on OS X - Security.framework doesn't ignore superflous
// certificates provided by servers.
// TODO(eroman): Is this still needed?
LOG(INFO) << "Skipping this test as Security.framework doesn't ignore "
"superflous certificates provided by servers.";
return;
}
base::FilePath certs_dir = GetTestCertsDirectory();
scoped_refptr<X509Certificate> server_cert =
ImportCertFromFile(certs_dir, "cross-signed-leaf.pem");
ASSERT_NE(static_cast<X509Certificate*>(NULL), server_cert.get());
scoped_refptr<X509Certificate> extra_cert =
ImportCertFromFile(certs_dir, "cross-signed-root-md5.pem");
ASSERT_NE(static_cast<X509Certificate*>(NULL), extra_cert.get());
scoped_refptr<X509Certificate> root_cert =
ImportCertFromFile(certs_dir, "cross-signed-root-sha256.pem");
ASSERT_NE(static_cast<X509Certificate*>(NULL), root_cert.get());
ScopedTestRoot scoped_root(root_cert.get());
X509Certificate::OSCertHandles intermediates;
intermediates.push_back(extra_cert->os_cert_handle());
scoped_refptr<X509Certificate> cert_chain = X509Certificate::CreateFromHandle(
server_cert->os_cert_handle(), intermediates);
ASSERT_TRUE(cert_chain);
CertVerifyResult verify_result;
int flags = 0;
int error = Verify(cert_chain.get(), "127.0.0.1", flags, NULL,
CertificateList(), &verify_result);
EXPECT_THAT(error, IsOk());
// The extra MD5 root should be discarded
ASSERT_TRUE(verify_result.verified_cert.get());
ASSERT_EQ(1u,
verify_result.verified_cert->GetIntermediateCertificates().size());
EXPECT_TRUE(X509Certificate::IsSameOSCert(
verify_result.verified_cert->GetIntermediateCertificates().front(),
root_cert->os_cert_handle()));
EXPECT_FALSE(verify_result.has_md5);
}
// Test for bug 94673.
TEST_P(CertVerifyProcInternalTest, GoogleDigiNotarTest) {
base::FilePath certs_dir = GetTestCertsDirectory();
scoped_refptr<X509Certificate> server_cert =
ImportCertFromFile(certs_dir, "google_diginotar.pem");
ASSERT_NE(static_cast<X509Certificate*>(NULL), server_cert.get());
scoped_refptr<X509Certificate> intermediate_cert =
ImportCertFromFile(certs_dir, "diginotar_public_ca_2025.pem");
ASSERT_NE(static_cast<X509Certificate*>(NULL), intermediate_cert.get());
X509Certificate::OSCertHandles intermediates;
intermediates.push_back(intermediate_cert->os_cert_handle());
scoped_refptr<X509Certificate> cert_chain = X509Certificate::CreateFromHandle(
server_cert->os_cert_handle(), intermediates);
ASSERT_TRUE(cert_chain);
CertVerifyResult verify_result;
int flags = CertVerifier::VERIFY_REV_CHECKING_ENABLED;
int error = Verify(cert_chain.get(), "mail.google.com", flags, NULL,
CertificateList(), &verify_result);
EXPECT_NE(OK, error);
// Now turn off revocation checking. Certificate verification should still
// fail.
flags = 0;
error = Verify(cert_chain.get(), "mail.google.com", flags, NULL,
CertificateList(), &verify_result);
EXPECT_NE(OK, error);
}
// Ensures the CertVerifyProc blacklist remains in sorted order, so that it
// can be binary-searched.
TEST(CertVerifyProcTest, BlacklistIsSorted) {
// Defines kBlacklistedSPKIs.
#include "net/cert/cert_verify_proc_blacklist.inc"
for (size_t i = 0; i < arraysize(kBlacklistedSPKIs) - 1; ++i) {
EXPECT_GT(0, memcmp(kBlacklistedSPKIs[i], kBlacklistedSPKIs[i + 1],
crypto::kSHA256Length))
<< " at index " << i;
}
}
TEST(CertVerifyProcTest, DigiNotarCerts) {
static const char* const kDigiNotarFilenames[] = {
"diginotar_root_ca.pem", "diginotar_cyber_ca.pem",
"diginotar_services_1024_ca.pem", "diginotar_pkioverheid.pem",
"diginotar_pkioverheid_g2.pem", NULL,
};
base::FilePath certs_dir = GetTestCertsDirectory();
for (size_t i = 0; kDigiNotarFilenames[i]; i++) {
scoped_refptr<X509Certificate> diginotar_cert =
ImportCertFromFile(certs_dir, kDigiNotarFilenames[i]);
std::string der_bytes;
ASSERT_TRUE(X509Certificate::GetDEREncoded(diginotar_cert->os_cert_handle(),
&der_bytes));
base::StringPiece spki;
ASSERT_TRUE(asn1::ExtractSPKIFromDERCert(der_bytes, &spki));
std::string spki_sha256 = crypto::SHA256HashString(spki.as_string());
HashValueVector public_keys;
HashValue hash(HASH_VALUE_SHA256);
ASSERT_EQ(hash.size(), spki_sha256.size());
memcpy(hash.data(), spki_sha256.data(), spki_sha256.size());
public_keys.push_back(hash);
EXPECT_TRUE(CertVerifyProc::IsPublicKeyBlacklisted(public_keys))
<< "Public key not blocked for " << kDigiNotarFilenames[i];
}
}
TEST_P(CertVerifyProcInternalTest, NameConstraintsOk) {
CertificateList ca_cert_list =
CreateCertificateListFromFile(GetTestCertsDirectory(), "root_ca_cert.pem",
X509Certificate::FORMAT_AUTO);
ASSERT_EQ(1U, ca_cert_list.size());
ScopedTestRoot test_root(ca_cert_list[0].get());
scoped_refptr<X509Certificate> leaf = CreateCertificateChainFromFile(
GetTestCertsDirectory(), "name_constraint_good.pem",
X509Certificate::FORMAT_AUTO);
ASSERT_TRUE(leaf);
ASSERT_EQ(0U, leaf->GetIntermediateCertificates().size());
int flags = 0;
CertVerifyResult verify_result;
int error = Verify(leaf.get(), "test.example.com", flags, NULL,
CertificateList(), &verify_result);
EXPECT_THAT(error, IsOk());
EXPECT_EQ(0U, verify_result.cert_status);
error = Verify(leaf.get(), "foo.test2.example.com", flags, NULL,
CertificateList(), &verify_result);
EXPECT_THAT(error, IsOk());
EXPECT_EQ(0U, verify_result.cert_status);
}
// This fixture is for testing the verification of a certificate chain which
// has some sort of mismatched signature algorithm (i.e.
// Certificate.signatureAlgorithm and TBSCertificate.algorithm are different).
class CertVerifyProcInspectSignatureAlgorithmsTest : public ::testing::Test {
protected:
// In the test setup, SHA384 is given special treatment as an unknown
// algorithm.
static constexpr DigestAlgorithm kUnknownDigestAlgorithm =
DigestAlgorithm::Sha384;
struct CertParams {
// Certificate.signatureAlgorithm
DigestAlgorithm cert_algorithm;
// TBSCertificate.algorithm
DigestAlgorithm tbs_algorithm;
};
// On some platforms trying to import a certificate with mismatched signature
// will fail. Consequently the rest of the tests can't be performed.
WARN_UNUSED_RESULT bool SupportsImportingMismatchedAlgorithms() const {
#if defined(OS_IOS)
LOG(INFO) << "Skipping test on iOS because certs with mismatched "
"algorithms cannot be imported";
return false;
#elif defined(OS_MACOSX)
if (base::mac::IsAtLeastOS10_12()) {
LOG(INFO) << "Skipping test on macOS >= 10.12 because certs with "
"mismatched algorithms cannot be imported";
return false;
}
return true;
#else
return true;
#endif
}
// Shorthand for VerifyChain() where only the leaf's parameters need
// to be specified.
WARN_UNUSED_RESULT int VerifyLeaf(const CertParams& leaf_params) {
return VerifyChain({// Target
leaf_params,
// Root
{DigestAlgorithm::Sha256, DigestAlgorithm::Sha256}});
}
// Shorthand for VerifyChain() where only the intermediate's parameters need
// to be specified.
WARN_UNUSED_RESULT int VerifyIntermediate(
const CertParams& intermediate_params) {
return VerifyChain({// Target
{DigestAlgorithm::Sha256, DigestAlgorithm::Sha256},
// Intermediate
intermediate_params,
// Root
{DigestAlgorithm::Sha256, DigestAlgorithm::Sha256}});
}
// Shorthand for VerifyChain() where only the root's parameters need to be
// specified.
WARN_UNUSED_RESULT int VerifyRoot(const CertParams& root_params) {
return VerifyChain({// Target
{DigestAlgorithm::Sha256, DigestAlgorithm::Sha256},
// Intermediate
{DigestAlgorithm::Sha256, DigestAlgorithm::Sha256},
// Root
root_params});
}
// Manufactures a certificate chain where each certificate has the indicated
// signature algorithms, and then returns the result of verifying this chain.
//
// TODO(eroman): Instead of building certificates at runtime, move their
// generation to external scripts.
WARN_UNUSED_RESULT int VerifyChain(
const std::vector<CertParams>& chain_params) {
auto chain = CreateChain(chain_params);
if (!chain) {
ADD_FAILURE() << "Failed creating certificate chain";
return ERR_UNEXPECTED;
}
int flags = 0;
CertVerifyResult dummy_result;
CertVerifyResult verify_result;
scoped_refptr<CertVerifyProc> verify_proc =
new MockCertVerifyProc(dummy_result);
return verify_proc->Verify(chain.get(), "test.example.com", std::string(),
flags, NULL, CertificateList(), &verify_result);
}
private:
// Overwrites the AlgorithmIdentifier pointed to by |algorithm_sequence| with
// |algorithm|. Note this violates the constness of StringPiece.
WARN_UNUSED_RESULT static bool SetAlgorithmSequence(
DigestAlgorithm algorithm,
base::StringPiece* algorithm_sequence) {
// This string of bytes is the full SEQUENCE for an AlgorithmIdentifier.
std::vector<uint8_t> replacement_sequence;
switch (algorithm) {
case DigestAlgorithm::Sha1:
// sha1WithRSAEncryption
replacement_sequence = {0x30, 0x0D, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86,
0xf7, 0x0d, 0x01, 0x01, 0x05, 0x05, 0x00};
break;
case DigestAlgorithm::Sha256:
// sha256WithRSAEncryption
replacement_sequence = {0x30, 0x0D, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86,
0xf7, 0x0d, 0x01, 0x01, 0x0b, 0x05, 0x00};
break;
case kUnknownDigestAlgorithm:
// This shouldn't be anything meaningful (modified numbers at random).
replacement_sequence = {0x30, 0x0D, 0x06, 0x09, 0x8a, 0x87, 0x18, 0x46,
0xd7, 0x0d, 0x01, 0x01, 0x0b, 0x05, 0x00};
break;
default:
ADD_FAILURE() << "Unsupported digest algorithm";
return false;
}
// For this simple replacement to work (without modifying any
// other sequence lengths) the original algorithm and replacement
// algorithm must have the same encoded length.
if (algorithm_sequence->size() != replacement_sequence.size()) {
ADD_FAILURE() << "AlgorithmIdentifier must have length "
<< replacement_sequence.size();
return false;
}
memcpy(const_cast<char*>(algorithm_sequence->data()),
replacement_sequence.data(), replacement_sequence.size());
return true;
}
// Locate the serial number bytes.
WARN_UNUSED_RESULT static bool ExtractSerialNumberFromDERCert(
base::StringPiece der_cert,
base::StringPiece* serial_value) {
der::Parser parser((der::Input(der_cert)));
der::Parser certificate;
if (!parser.ReadSequence(&certificate))
return false;
der::Parser tbs_certificate;
if (!certificate.ReadSequence(&tbs_certificate))
return false;
bool unused;
if (!tbs_certificate.SkipOptionalTag(
der::kTagConstructed | der::kTagContextSpecific | 0, &unused)) {
return false;
}
// serialNumber
der::Input serial_value_der;
if (!tbs_certificate.ReadTag(der::kInteger, &serial_value_der))
return false;
*serial_value = serial_value_der.AsStringPiece();
return true;
}
// Creates a certificate (based on some base certificate file) using the
// specified signature algorithms.
static scoped_refptr<X509Certificate> CreateCertificate(
const CertParams& params) {
// Dosn't really matter which base certificate is used, so long as it is
// valid and uses a signature AlgorithmIdentifier with the same encoded
// length as sha1WithRSASignature.
const char* kLeafFilename = "name_constraint_good.pem";
auto cert = CreateCertificateChainFromFile(
GetTestCertsDirectory(), kLeafFilename, X509Certificate::FORMAT_AUTO);
if (!cert) {
ADD_FAILURE() << "Failed to load certificate: " << kLeafFilename;
return nullptr;
}
// Start with the DER bytes of a valid certificate. This will be the basis
// for building a modified certificate.
std::string cert_der;
if (!X509Certificate::GetDEREncoded(cert->os_cert_handle(), &cert_der)) {
ADD_FAILURE() << "Failed getting DER bytes";
return nullptr;
}
// Parse the certificate and identify the locations of interest within
// |cert_der|.
base::StringPiece cert_algorithm_sequence;
base::StringPiece tbs_algorithm_sequence;
if (!asn1::ExtractSignatureAlgorithmsFromDERCert(
cert_der, &cert_algorithm_sequence, &tbs_algorithm_sequence)) {
ADD_FAILURE() << "Failed parsing certificate algorithms";
return nullptr;
}
base::StringPiece serial_value;
if (!ExtractSerialNumberFromDERCert(cert_der, &serial_value)) {
ADD_FAILURE() << "Failed parsing certificate serial number";
return nullptr;
}
// Give each certificate a unique serial number based on its content (which
// in turn is a function of |params|, otherwise importing it may fail.
// Upper bound for last entry in DigestAlgorithm
const int kNumDigestAlgorithms = 15;
*const_cast<char*>(serial_value.data()) +=
static_cast<int>(params.tbs_algorithm) * kNumDigestAlgorithms +
static_cast<int>(params.cert_algorithm);
// Change the signature AlgorithmIdentifiers.
if (!SetAlgorithmSequence(params.cert_algorithm,
&cert_algorithm_sequence) ||
!SetAlgorithmSequence(params.tbs_algorithm, &tbs_algorithm_sequence)) {
return nullptr;
}
// NOTE: The signature is NOT recomputed over TBSCertificate -- for these
// tests it isn't needed.
return X509Certificate::CreateFromBytes(cert_der.data(), cert_der.size());
}
static scoped_refptr<X509Certificate> CreateChain(
const std::vector<CertParams>& params) {
// Manufacture a chain with the given combinations of signature algorithms.
// This chain isn't actually a valid chain, but it is good enough for
// testing the base CertVerifyProc.
CertificateList certs;
for (const auto& cert_params : params) {
certs.push_back(CreateCertificate(cert_params));
if (!certs.back())
return nullptr;
}
X509Certificate::OSCertHandles intermediates;
for (size_t i = 1; i < certs.size(); ++i)
intermediates.push_back(certs[i]->os_cert_handle());
return X509Certificate::CreateFromHandle(certs[0]->os_cert_handle(),
intermediates);
}
};
// This is a control test to make sure that the test helper
// VerifyLeaf() works as expected. There is no actual mismatch in the
// algorithms used here.
//
// Certificate.signatureAlgorithm: sha1WithRSASignature
// TBSCertificate.algorithm: sha1WithRSAEncryption
TEST_F(CertVerifyProcInspectSignatureAlgorithmsTest, LeafSha1Sha1) {
int rv = VerifyLeaf({DigestAlgorithm::Sha1, DigestAlgorithm::Sha1});
ASSERT_THAT(rv, IsError(ERR_CERT_WEAK_SIGNATURE_ALGORITHM));
}
// This is a control test to make sure that the test helper
// VerifyLeaf() works as expected. There is no actual mismatch in the
// algorithms used here.
//
// Certificate.signatureAlgorithm: sha256WithRSASignature
// TBSCertificate.algorithm: sha256WithRSAEncryption
TEST_F(CertVerifyProcInspectSignatureAlgorithmsTest, LeafSha256Sha256) {
int rv = VerifyLeaf({DigestAlgorithm::Sha256, DigestAlgorithm::Sha256});
ASSERT_THAT(rv, IsOk());
}
// Mismatched signature algorithms in the leaf certificate.
//
// Certificate.signatureAlgorithm: sha1WithRSASignature
// TBSCertificate.algorithm: sha256WithRSAEncryption
TEST_F(CertVerifyProcInspectSignatureAlgorithmsTest, LeafSha1Sha256) {
if (!SupportsImportingMismatchedAlgorithms())
return;
int rv = VerifyLeaf({DigestAlgorithm::Sha1, DigestAlgorithm::Sha256});
ASSERT_THAT(rv, IsError(ERR_CERT_INVALID));
}
// Mismatched signature algorithms in the leaf certificate.
//
// Certificate.signatureAlgorithm: sha256WithRSAEncryption
// TBSCertificate.algorithm: sha1WithRSASignature
TEST_F(CertVerifyProcInspectSignatureAlgorithmsTest, LeafSha256Sha1) {
if (!SupportsImportingMismatchedAlgorithms())
return;
int rv = VerifyLeaf({DigestAlgorithm::Sha256, DigestAlgorithm::Sha1});
ASSERT_THAT(rv, IsError(ERR_CERT_INVALID));
}
// Unrecognized signature algorithm in the leaf certificate.
//
// Certificate.signatureAlgorithm: sha256WithRSAEncryption
// TBSCertificate.algorithm: ?
TEST_F(CertVerifyProcInspectSignatureAlgorithmsTest, LeafSha256Unknown) {
if (!SupportsImportingMismatchedAlgorithms())
return;
int rv = VerifyLeaf({DigestAlgorithm::Sha256, kUnknownDigestAlgorithm});
ASSERT_THAT(rv, IsError(ERR_CERT_INVALID));
}
// Unrecognized signature algorithm in the leaf certificate.
//
// Certificate.signatureAlgorithm: ?
// TBSCertificate.algorithm: sha256WithRSAEncryption
TEST_F(CertVerifyProcInspectSignatureAlgorithmsTest, LeafUnknownSha256) {
if (!SupportsImportingMismatchedAlgorithms())
return;
int rv = VerifyLeaf({kUnknownDigestAlgorithm, DigestAlgorithm::Sha256});
ASSERT_THAT(rv, IsError(ERR_CERT_INVALID));
}
// Mismatched signature algorithms in the intermediate certificate.
//
// Certificate.signatureAlgorithm: sha1WithRSASignature
// TBSCertificate.algorithm: sha256WithRSAEncryption
TEST_F(CertVerifyProcInspectSignatureAlgorithmsTest, IntermediateSha1Sha256) {
if (!SupportsImportingMismatchedAlgorithms())
return;
int rv = VerifyIntermediate({DigestAlgorithm::Sha1, DigestAlgorithm::Sha256});
ASSERT_THAT(rv, IsError(ERR_CERT_INVALID));
}
// Mismatched signature algorithms in the intermediate certificate.
//
// Certificate.signatureAlgorithm: sha256WithRSAEncryption
// TBSCertificate.algorithm: sha1WithRSASignature
TEST_F(CertVerifyProcInspectSignatureAlgorithmsTest, IntermediateSha256Sha1) {
if (!SupportsImportingMismatchedAlgorithms())
return;
int rv = VerifyIntermediate({DigestAlgorithm::Sha256, DigestAlgorithm::Sha1});
ASSERT_THAT(rv, IsError(ERR_CERT_INVALID));
}
// Mismatched signature algorithms in the root certificate.
//
// Certificate.signatureAlgorithm: sha256WithRSAEncryption
// TBSCertificate.algorithm: sha1WithRSASignature
TEST_F(CertVerifyProcInspectSignatureAlgorithmsTest, RootSha256Sha1) {
if (!SupportsImportingMismatchedAlgorithms())
return;
int rv = VerifyRoot({DigestAlgorithm::Sha256, DigestAlgorithm::Sha1});
ASSERT_THAT(rv, IsOk());
}
// Unrecognized signature algorithm in the root certificate.
//
// Certificate.signatureAlgorithm: ?
// TBSCertificate.algorithm: sha256WithRSAEncryption
TEST_F(CertVerifyProcInspectSignatureAlgorithmsTest, RootUnknownSha256) {
if (!SupportsImportingMismatchedAlgorithms())
return;
int rv = VerifyRoot({kUnknownDigestAlgorithm, DigestAlgorithm::Sha256});
ASSERT_THAT(rv, IsOk());
}
TEST_P(CertVerifyProcInternalTest, NameConstraintsFailure) {
if (!SupportsReturningVerifiedChain()) {
LOG(INFO) << "Skipping this test in this platform.";
return;
}
CertificateList ca_cert_list =
CreateCertificateListFromFile(GetTestCertsDirectory(), "root_ca_cert.pem",
X509Certificate::FORMAT_AUTO);
ASSERT_EQ(1U, ca_cert_list.size());
ScopedTestRoot test_root(ca_cert_list[0].get());
CertificateList cert_list = CreateCertificateListFromFile(
GetTestCertsDirectory(), "name_constraint_bad.pem",
X509Certificate::FORMAT_AUTO);
ASSERT_EQ(1U, cert_list.size());
X509Certificate::OSCertHandles intermediates;
scoped_refptr<X509Certificate> leaf = X509Certificate::CreateFromHandle(
cert_list[0]->os_cert_handle(), intermediates);
ASSERT_TRUE(leaf);
int flags = 0;
CertVerifyResult verify_result;
int error = Verify(leaf.get(), "test.example.com", flags, NULL,
CertificateList(), &verify_result);
EXPECT_THAT(error, IsError(ERR_CERT_NAME_CONSTRAINT_VIOLATION));
EXPECT_EQ(CERT_STATUS_NAME_CONSTRAINT_VIOLATION,
verify_result.cert_status & CERT_STATUS_NAME_CONSTRAINT_VIOLATION);
}
TEST(CertVerifyProcTest, TestHasTooLongValidity) {
struct {
const char* const file;
bool is_valid_too_long;
} tests[] = {
{"twitter-chain.pem", false},
{"start_after_expiry.pem", true},
{"pre_br_validity_ok.pem", false},
{"pre_br_validity_bad_121.pem", true},
{"pre_br_validity_bad_2020.pem", true},
{"10_year_validity.pem", false},
{"11_year_validity.pem", true},
{"39_months_after_2015_04.pem", false},
{"40_months_after_2015_04.pem", true},
{"60_months_after_2012_07.pem", false},
{"61_months_after_2012_07.pem", true},
};
base::FilePath certs_dir = GetTestCertsDirectory();
for (size_t i = 0; i < arraysize(tests); ++i) {
scoped_refptr<X509Certificate> certificate =
ImportCertFromFile(certs_dir, tests[i].file);
SCOPED_TRACE(tests[i].file);
ASSERT_TRUE(certificate);
EXPECT_EQ(tests[i].is_valid_too_long,
CertVerifyProc::HasTooLongValidity(*certificate));
}
}
// TODO(crbug.com/610546): Fix and re-enable this test.
TEST_P(CertVerifyProcInternalTest, DISABLED_TestKnownRoot) {
if (!SupportsDetectingKnownRoots()) {
LOG(INFO) << "Skipping this test on this platform.";
return;
}
base::FilePath certs_dir = GetTestCertsDirectory();
CertificateList certs = CreateCertificateListFromFile(
certs_dir, "twitter-chain.pem", X509Certificate::FORMAT_AUTO);
ASSERT_EQ(3U, certs.size());
X509Certificate::OSCertHandles intermediates;
intermediates.push_back(certs[1]->os_cert_handle());
scoped_refptr<X509Certificate> cert_chain = X509Certificate::CreateFromHandle(
certs[0]->os_cert_handle(), intermediates);
ASSERT_TRUE(cert_chain);
int flags = 0;
CertVerifyResult verify_result;
// This will blow up, May 9th, 2016. Sorry! Please disable and file a bug
// against agl.
int error = Verify(cert_chain.get(), "twitter.com", flags, NULL,
CertificateList(), &verify_result);
EXPECT_THAT(error, IsOk());
EXPECT_TRUE(verify_result.is_issued_by_known_root);
}
// This tests that on successful certificate verification,
// CertVerifyResult::public_key_hashes is filled with a SHA1 and SHA256 hash
// for each of the certificates in the chain.
TEST_P(CertVerifyProcInternalTest, PublicKeyHashes) {
if (!SupportsReturningVerifiedChain()) {
LOG(INFO) << "Skipping this test in this platform.";
return;
}
base::FilePath certs_dir = GetTestCertsDirectory();
CertificateList certs = CreateCertificateListFromFile(
certs_dir, "x509_verify_results.chain.pem", X509Certificate::FORMAT_AUTO);
ASSERT_EQ(3U, certs.size());
X509Certificate::OSCertHandles intermediates;
intermediates.push_back(certs[1]->os_cert_handle());
intermediates.push_back(certs[2]->os_cert_handle());
ScopedTestRoot scoped_root(certs[2].get());
scoped_refptr<X509Certificate> cert_chain = X509Certificate::CreateFromHandle(
certs[0]->os_cert_handle(), intermediates);
ASSERT_TRUE(cert_chain);
ASSERT_EQ(2U, cert_chain->GetIntermediateCertificates().size());
int flags = 0;
CertVerifyResult verify_result;
int error = Verify(cert_chain.get(), "127.0.0.1", flags, NULL,
CertificateList(), &verify_result);
EXPECT_THAT(error, IsOk());
// There are 2 hashes each of the 3 certificates in the verified chain.
EXPECT_EQ(6u, verify_result.public_key_hashes.size());
// Convert |public_key_hashes| to strings for ease of comparison.
std::vector<std::string> public_key_hash_strings;
for (const auto& public_key_hash : verify_result.public_key_hashes)
public_key_hash_strings.push_back(public_key_hash.ToString());
std::vector<std::string> expected_public_key_hashes = {
// Target
"sha1/fSQl8GTgpmark/9mDK9qzIIGfFE=",
"sha256/5I5+4ndAhwDiWd1WqfBgDkKAAIEhsq0MfAx25Hoc+dA=",
// Intermediate
"sha1/7+0Ms07hEkAc6zVPOo+uLtMEwfU=",
"sha256/MtnqgdSwAIgEjse7SpxnmyKoo/RTiL9CDIWwFnz4nas=",
// Trust anchor
"sha1/dJwvO4gEVIZvretArGyBNggjlrQ=",
"sha256/z7x1Szes+eQOqJp6rBK3u/tQMs55FYojZHUCFiBcjuc="};
// |public_key_hashes| does not have an ordering guarantee.
EXPECT_THAT(expected_public_key_hashes,
testing::UnorderedElementsAreArray(public_key_hash_strings));
}
// A regression test for http://crbug.com/70293.
// The certificate in question has a key purpose of clientAuth, and also lacks
// the required key usage for serverAuth.
TEST_P(CertVerifyProcInternalTest, WrongKeyPurpose) {
base::FilePath certs_dir = GetTestCertsDirectory();
scoped_refptr<X509Certificate> server_cert =
ImportCertFromFile(certs_dir, "invalid_key_usage_cert.der");
ASSERT_NE(static_cast<X509Certificate*>(NULL), server_cert.get());
int flags = 0;
CertVerifyResult verify_result;
int error = Verify(server_cert.get(), "jira.aquameta.com", flags, NULL,
CertificateList(), &verify_result);
EXPECT_TRUE(verify_result.cert_status & CERT_STATUS_COMMON_NAME_INVALID);
// TODO(crbug.com/649017): Don't special-case builtin verifier.
if (verify_proc_type() != CERT_VERIFY_PROC_BUILTIN)
EXPECT_TRUE(verify_result.cert_status & CERT_STATUS_INVALID);
// TODO(wtc): fix http://crbug.com/75520 to get all the certificate errors
// from NSS.
if (verify_proc_type() != CERT_VERIFY_PROC_NSS &&
verify_proc_type() != CERT_VERIFY_PROC_ANDROID) {
// The certificate is issued by an unknown CA.
EXPECT_TRUE(verify_result.cert_status & CERT_STATUS_AUTHORITY_INVALID);
}
// TODO(crbug.com/649017): Don't special-case builtin verifier.
if (verify_proc_type() == CERT_VERIFY_PROC_BUILTIN) {
EXPECT_THAT(error, IsError(ERR_CERT_AUTHORITY_INVALID));
} else {
EXPECT_THAT(error, IsError(ERR_CERT_INVALID));
}
}
// Basic test for returning the chain in CertVerifyResult. Note that the
// returned chain may just be a reflection of the originally supplied chain;
// that is, if any errors occur, the default chain returned is an exact copy
// of the certificate to be verified. The remaining VerifyReturn* tests are
// used to ensure that the actual, verified chain is being returned by
// Verify().
TEST_P(CertVerifyProcInternalTest, VerifyReturnChainBasic) {
if (!SupportsReturningVerifiedChain()) {
LOG(INFO) << "Skipping this test in this platform.";
return;
}
base::FilePath certs_dir = GetTestCertsDirectory();
CertificateList certs = CreateCertificateListFromFile(
certs_dir, "x509_verify_results.chain.pem", X509Certificate::FORMAT_AUTO);
ASSERT_EQ(3U, certs.size());
X509Certificate::OSCertHandles intermediates;
intermediates.push_back(certs[1]->os_cert_handle());
intermediates.push_back(certs[2]->os_cert_handle());
ScopedTestRoot scoped_root(certs[2].get());
scoped_refptr<X509Certificate> google_full_chain =
X509Certificate::CreateFromHandle(certs[0]->os_cert_handle(),
intermediates);
ASSERT_NE(static_cast<X509Certificate*>(NULL), google_full_chain.get());
ASSERT_EQ(2U, google_full_chain->GetIntermediateCertificates().size());
CertVerifyResult verify_result;
EXPECT_EQ(static_cast<X509Certificate*>(NULL),
verify_result.verified_cert.get());
int error = Verify(google_full_chain.get(), "127.0.0.1", 0, NULL,
CertificateList(), &verify_result);
EXPECT_THAT(error, IsOk());
ASSERT_NE(static_cast<X509Certificate*>(NULL),
verify_result.verified_cert.get());
EXPECT_NE(google_full_chain, verify_result.verified_cert);
EXPECT_TRUE(X509Certificate::IsSameOSCert(
google_full_chain->os_cert_handle(),
verify_result.verified_cert->os_cert_handle()));
const X509Certificate::OSCertHandles& return_intermediates =
verify_result.verified_cert->GetIntermediateCertificates();
ASSERT_EQ(2U, return_intermediates.size());
EXPECT_TRUE(X509Certificate::IsSameOSCert(return_intermediates[0],
certs[1]->os_cert_handle()));
EXPECT_TRUE(X509Certificate::IsSameOSCert(return_intermediates[1],
certs[2]->os_cert_handle()));
}
// Test that certificates issued for 'intranet' names (that is, containing no
// known public registry controlled domain information) issued by well-known
// CAs are flagged appropriately, while certificates that are issued by
// internal CAs are not flagged.
TEST(CertVerifyProcTest, IntranetHostsRejected) {
CertificateList cert_list = CreateCertificateListFromFile(
GetTestCertsDirectory(), "reject_intranet_hosts.pem",
X509Certificate::FORMAT_AUTO);
ASSERT_EQ(1U, cert_list.size());
scoped_refptr<X509Certificate> cert(cert_list[0]);
CertVerifyResult verify_result;
int error = 0;
// Intranet names for public CAs should be flagged:
CertVerifyResult dummy_result;
dummy_result.is_issued_by_known_root = true;
scoped_refptr<CertVerifyProc> verify_proc =
new MockCertVerifyProc(dummy_result);
error = verify_proc->Verify(cert.get(), "webmail", std::string(), 0, nullptr,
CertificateList(), &verify_result);
EXPECT_THAT(error, IsOk());
EXPECT_TRUE(verify_result.cert_status & CERT_STATUS_NON_UNIQUE_NAME);
// However, if the CA is not well known, these should not be flagged:
dummy_result.Reset();
dummy_result.is_issued_by_known_root = false;
verify_proc = make_scoped_refptr(new MockCertVerifyProc(dummy_result));
error = verify_proc->Verify(cert.get(), "webmail", std::string(), 0, nullptr,
CertificateList(), &verify_result);
EXPECT_THAT(error, IsOk());
EXPECT_FALSE(verify_result.cert_status & CERT_STATUS_NON_UNIQUE_NAME);
}
// While all SHA-1 certificates should be rejected, in the event that there
// emerges some unexpected bug, test that the 'legacy' behaviour works
// correctly - rejecting all SHA-1 certificates from publicly trusted CAs
// that were issued after 1 January 2016, while still allowing those from
// before that date, with SHA-1 in the intermediate, or from an enterprise
// CA.
TEST(CertVerifyProcTest, VerifyRejectsSHA1AfterDeprecationLegacyMode) {
base::test::ScopedFeatureList scoped_feature_list;
scoped_feature_list.InitAndEnableFeature(CertVerifyProc::kSHA1LegacyMode);
CertVerifyResult dummy_result;
CertVerifyResult verify_result;
int error = 0;
scoped_refptr<X509Certificate> cert;
// Publicly trusted SHA-1 leaf certificates issued before 1 January 2016
// are accepted.
verify_result.Reset();
dummy_result.Reset();
dummy_result.is_issued_by_known_root = true;
dummy_result.has_sha1 = true;
dummy_result.has_sha1_leaf = true;
scoped_refptr<CertVerifyProc> verify_proc =
new MockCertVerifyProc(dummy_result);
cert = CreateCertificateChainFromFile(GetTestCertsDirectory(),
"sha1_dec_2015.pem",
X509Certificate::FORMAT_AUTO);
ASSERT_TRUE(cert);
error = verify_proc->Verify(cert.get(), "127.0.0.1", std::string(), 0, NULL,
CertificateList(), &verify_result);
EXPECT_THAT(error, IsOk());
EXPECT_TRUE(verify_result.cert_status & CERT_STATUS_SHA1_SIGNATURE_PRESENT);
// Publicly trusted SHA-1 leaf certificates issued on/after 1 January 2016
// are rejected.
verify_result.Reset();
dummy_result.Reset();
dummy_result.is_issued_by_known_root = true;
dummy_result.has_sha1 = true;
dummy_result.has_sha1_leaf = true;
verify_proc = make_scoped_refptr(new MockCertVerifyProc(dummy_result));
cert = CreateCertificateChainFromFile(GetTestCertsDirectory(),
"sha1_jan_2016.pem",
X509Certificate::FORMAT_AUTO);
ASSERT_TRUE(cert);
error = verify_proc->Verify(cert.get(), "127.0.0.1", std::string(), 0, NULL,
CertificateList(), &verify_result);
EXPECT_THAT(error, IsError(ERR_CERT_WEAK_SIGNATURE_ALGORITHM));
EXPECT_TRUE(verify_result.cert_status & CERT_STATUS_WEAK_SIGNATURE_ALGORITHM);
// Enterprise issued SHA-1 leaf certificates issued on/after 1 January 2016
// remain accepted.
verify_result.Reset();
dummy_result.Reset();
dummy_result.is_issued_by_known_root = false;
dummy_result.has_sha1 = true;
dummy_result.has_sha1_leaf = true;
verify_proc = make_scoped_refptr(new MockCertVerifyProc(dummy_result));
cert = CreateCertificateChainFromFile(GetTestCertsDirectory(),
"sha1_jan_2016.pem",
X509Certificate::FORMAT_AUTO);
ASSERT_TRUE(cert);
error = verify_proc->Verify(cert.get(), "127.0.0.1", std::string(), 0, NULL,
CertificateList(), &verify_result);
EXPECT_THAT(error, IsOk());
EXPECT_TRUE(verify_result.cert_status & CERT_STATUS_SHA1_SIGNATURE_PRESENT);
// Publicly trusted SHA-1 intermediates issued on/after 1 January 2016 are,
// unfortunately, accepted. This can arise due to OS path building quirks.
verify_result.Reset();
dummy_result.Reset();
dummy_result.is_issued_by_known_root = true;
dummy_result.has_sha1 = true;
dummy_result.has_sha1_leaf = false;
verify_proc = make_scoped_refptr(new MockCertVerifyProc(dummy_result));
cert = CreateCertificateChainFromFile(GetTestCertsDirectory(),
"sha1_jan_2016.pem",
X509Certificate::FORMAT_AUTO);
ASSERT_TRUE(cert);
error = verify_proc->Verify(cert.get(), "127.0.0.1", std::string(), 0, NULL,
CertificateList(), &verify_result);
EXPECT_THAT(error, IsOk());
EXPECT_TRUE(verify_result.cert_status & CERT_STATUS_SHA1_SIGNATURE_PRESENT);
}
// Test that the certificate returned in CertVerifyResult is able to reorder
// certificates that are not ordered from end-entity to root. While this is
// a protocol violation if sent during a TLS handshake, if multiple sources
// of intermediate certificates are combined, it's possible that order may
// not be maintained.
TEST_P(CertVerifyProcInternalTest, VerifyReturnChainProperlyOrdered) {
if (!SupportsReturningVerifiedChain()) {
LOG(INFO) << "Skipping this test in this platform.";
return;
}
base::FilePath certs_dir = GetTestCertsDirectory();
CertificateList certs = CreateCertificateListFromFile(
certs_dir, "x509_verify_results.chain.pem", X509Certificate::FORMAT_AUTO);
ASSERT_EQ(3U, certs.size());
// Construct the chain out of order.
X509Certificate::OSCertHandles intermediates;
intermediates.push_back(certs[2]->os_cert_handle());
intermediates.push_back(certs[1]->os_cert_handle());
ScopedTestRoot scoped_root(certs[2].get());
scoped_refptr<X509Certificate> google_full_chain =
X509Certificate::CreateFromHandle(certs[0]->os_cert_handle(),
intermediates);
ASSERT_NE(static_cast<X509Certificate*>(NULL), google_full_chain.get());
ASSERT_EQ(2U, google_full_chain->GetIntermediateCertificates().size());
CertVerifyResult verify_result;
EXPECT_EQ(static_cast<X509Certificate*>(NULL),
verify_result.verified_cert.get());
int error = Verify(google_full_chain.get(), "127.0.0.1", 0, NULL,
CertificateList(), &verify_result);
EXPECT_THAT(error, IsOk());
ASSERT_NE(static_cast<X509Certificate*>(NULL),
verify_result.verified_cert.get());
EXPECT_NE(google_full_chain, verify_result.verified_cert);
EXPECT_TRUE(X509Certificate::IsSameOSCert(
google_full_chain->os_cert_handle(),
verify_result.verified_cert->os_cert_handle()));
const X509Certificate::OSCertHandles& return_intermediates =
verify_result.verified_cert->GetIntermediateCertificates();
ASSERT_EQ(2U, return_intermediates.size());
EXPECT_TRUE(X509Certificate::IsSameOSCert(return_intermediates[0],
certs[1]->os_cert_handle()));
EXPECT_TRUE(X509Certificate::IsSameOSCert(return_intermediates[1],
certs[2]->os_cert_handle()));
}
// Test that Verify() filters out certificates which are not related to
// or part of the certificate chain being verified.
TEST_P(CertVerifyProcInternalTest, VerifyReturnChainFiltersUnrelatedCerts) {
if (!SupportsReturningVerifiedChain()) {
LOG(INFO) << "Skipping this test in this platform.";
return;
}
base::FilePath certs_dir = GetTestCertsDirectory();
CertificateList certs = CreateCertificateListFromFile(
certs_dir, "x509_verify_results.chain.pem", X509Certificate::FORMAT_AUTO);
ASSERT_EQ(3U, certs.size());
ScopedTestRoot scoped_root(certs[2].get());
scoped_refptr<X509Certificate> unrelated_certificate =
ImportCertFromFile(certs_dir, "duplicate_cn_1.pem");
scoped_refptr<X509Certificate> unrelated_certificate2 =
ImportCertFromFile(certs_dir, "aia-cert.pem");
ASSERT_NE(static_cast<X509Certificate*>(NULL), unrelated_certificate.get());
ASSERT_NE(static_cast<X509Certificate*>(NULL), unrelated_certificate2.get());
// Interject unrelated certificates into the list of intermediates.
X509Certificate::OSCertHandles intermediates;
intermediates.push_back(unrelated_certificate->os_cert_handle());
intermediates.push_back(certs[1]->os_cert_handle());
intermediates.push_back(unrelated_certificate2->os_cert_handle());
intermediates.push_back(certs[2]->os_cert_handle());
scoped_refptr<X509Certificate> google_full_chain =
X509Certificate::CreateFromHandle(certs[0]->os_cert_handle(),
intermediates);
ASSERT_NE(static_cast<X509Certificate*>(NULL), google_full_chain.get());
ASSERT_EQ(4U, google_full_chain->GetIntermediateCertificates().size());
CertVerifyResult verify_result;
EXPECT_EQ(static_cast<X509Certificate*>(NULL),
verify_result.verified_cert.get());
int error = Verify(google_full_chain.get(), "127.0.0.1", 0, NULL,
CertificateList(), &verify_result);
EXPECT_THAT(error, IsOk());
ASSERT_NE(static_cast<X509Certificate*>(NULL),
verify_result.verified_cert.get());
EXPECT_NE(google_full_chain, verify_result.verified_cert);
EXPECT_TRUE(X509Certificate::IsSameOSCert(
google_full_chain->os_cert_handle(),
verify_result.verified_cert->os_cert_handle()));
const X509Certificate::OSCertHandles& return_intermediates =
verify_result.verified_cert->GetIntermediateCertificates();
ASSERT_EQ(2U, return_intermediates.size());
EXPECT_TRUE(X509Certificate::IsSameOSCert(return_intermediates[0],
certs[1]->os_cert_handle()));
EXPECT_TRUE(X509Certificate::IsSameOSCert(return_intermediates[1],
certs[2]->os_cert_handle()));
}
TEST_P(CertVerifyProcInternalTest, AdditionalTrustAnchors) {
if (!SupportsAdditionalTrustAnchors()) {
LOG(INFO) << "Skipping this test in this platform.";
return;
}
// |ca_cert| is the issuer of |cert|.
CertificateList ca_cert_list =
CreateCertificateListFromFile(GetTestCertsDirectory(), "root_ca_cert.pem",
X509Certificate::FORMAT_AUTO);
ASSERT_EQ(1U, ca_cert_list.size());
scoped_refptr<X509Certificate> ca_cert(ca_cert_list[0]);
CertificateList cert_list = CreateCertificateListFromFile(
GetTestCertsDirectory(), "ok_cert.pem", X509Certificate::FORMAT_AUTO);
ASSERT_EQ(1U, cert_list.size());
scoped_refptr<X509Certificate> cert(cert_list[0]);
// Verification of |cert| fails when |ca_cert| is not in the trust anchors
// list.
int flags = 0;
CertVerifyResult verify_result;
int error = Verify(cert.get(), "127.0.0.1", flags, NULL, CertificateList(),
&verify_result);
EXPECT_THAT(error, IsError(ERR_CERT_AUTHORITY_INVALID));
EXPECT_EQ(CERT_STATUS_AUTHORITY_INVALID, verify_result.cert_status);
EXPECT_FALSE(verify_result.is_issued_by_additional_trust_anchor);
// Now add the |ca_cert| to the |trust_anchors|, and verification should pass.
CertificateList trust_anchors;
trust_anchors.push_back(ca_cert);
error = Verify(cert.get(), "127.0.0.1", flags, NULL, trust_anchors,
&verify_result);
EXPECT_THAT(error, IsOk());
EXPECT_EQ(0U, verify_result.cert_status);
EXPECT_TRUE(verify_result.is_issued_by_additional_trust_anchor);
// Clearing the |trust_anchors| makes verification fail again (the cache
// should be skipped).
error = Verify(cert.get(), "127.0.0.1", flags, NULL, CertificateList(),
&verify_result);
EXPECT_THAT(error, IsError(ERR_CERT_AUTHORITY_INVALID));
EXPECT_EQ(CERT_STATUS_AUTHORITY_INVALID, verify_result.cert_status);
EXPECT_FALSE(verify_result.is_issued_by_additional_trust_anchor);
}
// Tests that certificates issued by user-supplied roots are not flagged as
// issued by a known root. This should pass whether or not the platform supports
// detecting known roots.
TEST_P(CertVerifyProcInternalTest, IsIssuedByKnownRootIgnoresTestRoots) {
// Load root_ca_cert.pem into the test root store.
ScopedTestRoot test_root(
ImportCertFromFile(GetTestCertsDirectory(), "root_ca_cert.pem").get());
scoped_refptr<X509Certificate> cert(
ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem"));
// Verification should pass.
int flags = 0;
CertVerifyResult verify_result;
int error = Verify(cert.get(), "127.0.0.1", flags, NULL, CertificateList(),
&verify_result);
EXPECT_THAT(error, IsOk());
EXPECT_EQ(0U, verify_result.cert_status);
// But should not be marked as a known root.
EXPECT_FALSE(verify_result.is_issued_by_known_root);
}
// Test that CRLSets are effective in making a certificate appear to be
// revoked.
TEST_P(CertVerifyProcInternalTest, CRLSet) {
if (!SupportsCRLSet()) {
LOG(INFO) << "Skipping test as verifier doesn't support CRLSet";
return;
}
CertificateList ca_cert_list =
CreateCertificateListFromFile(GetTestCertsDirectory(), "root_ca_cert.pem",
X509Certificate::FORMAT_AUTO);
ASSERT_EQ(1U, ca_cert_list.size());
ScopedTestRoot test_root(ca_cert_list[0].get());
CertificateList cert_list = CreateCertificateListFromFile(
GetTestCertsDirectory(), "ok_cert.pem", X509Certificate::FORMAT_AUTO);
ASSERT_EQ(1U, cert_list.size());
scoped_refptr<X509Certificate> cert(cert_list[0]);
int flags = 0;
CertVerifyResult verify_result;
int error = Verify(cert.get(), "127.0.0.1", flags, NULL, CertificateList(),
&verify_result);
EXPECT_THAT(error, IsOk());
EXPECT_EQ(0U, verify_result.cert_status);
scoped_refptr<CRLSet> crl_set;
std::string crl_set_bytes;
// First test blocking by SPKI.
EXPECT_TRUE(base::ReadFileToString(
GetTestCertsDirectory().AppendASCII("crlset_by_leaf_spki.raw"),
&crl_set_bytes));
ASSERT_TRUE(CRLSetStorage::Parse(crl_set_bytes, &crl_set));
error = Verify(cert.get(), "127.0.0.1", flags, crl_set.get(),
CertificateList(), &verify_result);
EXPECT_THAT(error, IsError(ERR_CERT_REVOKED));
// Second, test revocation by serial number of a cert directly under the
// root.
crl_set_bytes.clear();
EXPECT_TRUE(base::ReadFileToString(
GetTestCertsDirectory().AppendASCII("crlset_by_root_serial.raw"),
&crl_set_bytes));
ASSERT_TRUE(CRLSetStorage::Parse(crl_set_bytes, &crl_set));
error = Verify(cert.get(), "127.0.0.1", flags, crl_set.get(),
CertificateList(), &verify_result);
EXPECT_THAT(error, IsError(ERR_CERT_REVOKED));
}
TEST_P(CertVerifyProcInternalTest, CRLSetLeafSerial) {
if (!SupportsCRLSet()) {
LOG(INFO) << "Skipping test as verifier doesn't support CRLSet";
return;
}
CertificateList ca_cert_list =
CreateCertificateListFromFile(GetTestCertsDirectory(), "root_ca_cert.pem",
X509Certificate::FORMAT_AUTO);
ASSERT_EQ(1U, ca_cert_list.size());
ScopedTestRoot test_root(ca_cert_list[0].get());
CertificateList intermediate_cert_list = CreateCertificateListFromFile(
GetTestCertsDirectory(), "intermediate_ca_cert.pem",
X509Certificate::FORMAT_AUTO);
ASSERT_EQ(1U, intermediate_cert_list.size());
X509Certificate::OSCertHandles intermediates;
intermediates.push_back(intermediate_cert_list[0]->os_cert_handle());
CertificateList cert_list = CreateCertificateListFromFile(
GetTestCertsDirectory(), "ok_cert_by_intermediate.pem",
X509Certificate::FORMAT_AUTO);
ASSERT_EQ(1U, cert_list.size());
scoped_refptr<X509Certificate> leaf = X509Certificate::CreateFromHandle(
cert_list[0]->os_cert_handle(), intermediates);
ASSERT_TRUE(leaf);
int flags = 0;
CertVerifyResult verify_result;
int error = Verify(leaf.get(), "127.0.0.1", flags, NULL, CertificateList(),
&verify_result);
EXPECT_THAT(error, IsOk());
// Test revocation by serial number of a certificate not under the root.
scoped_refptr<CRLSet> crl_set;
std::string crl_set_bytes;
ASSERT_TRUE(base::ReadFileToString(
GetTestCertsDirectory().AppendASCII("crlset_by_intermediate_serial.raw"),
&crl_set_bytes));
ASSERT_TRUE(CRLSetStorage::Parse(crl_set_bytes, &crl_set));
error = Verify(leaf.get(), "127.0.0.1", flags, crl_set.get(),
CertificateList(), &verify_result);
EXPECT_THAT(error, IsError(ERR_CERT_REVOKED));
}
// Tests that CRLSets participate in path building functions, and that as
// long as a valid path exists within the verification graph, verification
// succeeds.
//
// In this test, there are two roots (D and E), and three possible paths
// to validate a leaf (A):
// 1. A(B) -> B(C) -> C(D) -> D(D)
// 2. A(B) -> B(C) -> C(E) -> E(E)
// 3. A(B) -> B(F) -> F(E) -> E(E)
//
// Each permutation of revocation is tried:
// 1. Revoking E by SPKI, so that only Path 1 is valid (as E is in Paths 2 & 3)
// 2. Revoking C(D) and F(E) by serial, so that only Path 2 is valid.
// 3. Revoking C by SPKI, so that only Path 3 is valid (as C is in Paths 1 & 2)
TEST_P(CertVerifyProcInternalTest, CRLSetDuringPathBuilding) {
if (!SupportsCRLSetsInPathBuilding()) {
LOG(INFO) << "Skipping this test on this platform.";
return;
}
CertificateList path_1_certs;
ASSERT_TRUE(
LoadCertificateFiles({"multi-root-A-by-B.pem", "multi-root-B-by-C.pem",
"multi-root-C-by-D.pem", "multi-root-D-by-D.pem"},
&path_1_certs));
CertificateList path_2_certs;
ASSERT_TRUE(
LoadCertificateFiles({"multi-root-A-by-B.pem", "multi-root-B-by-C.pem",
"multi-root-C-by-E.pem", "multi-root-E-by-E.pem"},
&path_2_certs));
CertificateList path_3_certs;
ASSERT_TRUE(
LoadCertificateFiles({"multi-root-A-by-B.pem", "multi-root-B-by-F.pem",
"multi-root-F-by-E.pem", "multi-root-E-by-E.pem"},
&path_3_certs));
// Add D and E as trust anchors.
ScopedTestRoot test_root_D(path_1_certs[3].get()); // D-by-D
ScopedTestRoot test_root_E(path_2_certs[3].get()); // E-by-E
// Create a chain that contains all the certificate paths possible.
// CertVerifyProcInternalTest.VerifyReturnChainFiltersUnrelatedCerts already
// ensures that it's safe to send additional certificates as inputs, and
// that they're ignored if not necessary.
// This is to avoid relying on AIA or internal object caches when
// interacting with the underlying library.
X509Certificate::OSCertHandles intermediates;
intermediates.push_back(path_1_certs[1]->os_cert_handle()); // B-by-C
intermediates.push_back(path_1_certs[2]->os_cert_handle()); // C-by-D
intermediates.push_back(path_2_certs[2]->os_cert_handle()); // C-by-E
intermediates.push_back(path_3_certs[1]->os_cert_handle()); // B-by-F
intermediates.push_back(path_3_certs[2]->os_cert_handle()); // F-by-E
scoped_refptr<X509Certificate> cert = X509Certificate::CreateFromHandle(
path_1_certs[0]->os_cert_handle(), intermediates);
ASSERT_TRUE(cert);
struct TestPermutations {
const char* crlset;
bool expect_valid;
scoped_refptr<X509Certificate> expected_intermediate;
} kTests[] = {
{"multi-root-crlset-D-and-E.raw", false, nullptr},
{"multi-root-crlset-E.raw", true, path_1_certs[2].get()},
{"multi-root-crlset-CD-and-FE.raw", true, path_2_certs[2].get()},
{"multi-root-crlset-C.raw", true, path_3_certs[2].get()},
{"multi-root-crlset-unrelated.raw", true, nullptr}};
for (const auto& testcase : kTests) {
SCOPED_TRACE(testcase.crlset);
scoped_refptr<CRLSet> crl_set;
std::string crl_set_bytes;
EXPECT_TRUE(base::ReadFileToString(
GetTestCertsDirectory().AppendASCII(testcase.crlset), &crl_set_bytes));
ASSERT_TRUE(CRLSetStorage::Parse(crl_set_bytes, &crl_set));
int flags = 0;
CertVerifyResult verify_result;
int error = Verify(cert.get(), "127.0.0.1", flags, crl_set.get(),
CertificateList(), &verify_result);
if (!testcase.expect_valid) {
EXPECT_NE(OK, error);
EXPECT_NE(0U, verify_result.cert_status);
continue;
}
ASSERT_THAT(error, IsOk());
ASSERT_EQ(0U, verify_result.cert_status);
ASSERT_TRUE(verify_result.verified_cert.get());
if (!testcase.expected_intermediate)
continue;
const X509Certificate::OSCertHandles& verified_intermediates =
verify_result.verified_cert->GetIntermediateCertificates();
ASSERT_EQ(3U, verified_intermediates.size());
scoped_refptr<X509Certificate> intermediate =
X509Certificate::CreateFromHandle(verified_intermediates[1],
X509Certificate::OSCertHandles());
ASSERT_TRUE(intermediate);
EXPECT_TRUE(testcase.expected_intermediate->Equals(intermediate.get()))
<< "Expected: " << testcase.expected_intermediate->subject().common_name
<< " issued by " << testcase.expected_intermediate->issuer().common_name
<< "; Got: " << intermediate->subject().common_name << " issued by "
<< intermediate->issuer().common_name;
}
}
// TODO(crbug.com/649017): This is not parameterized by the CertVerifyProc
// because the CertVerifyProc::Verify() does this unconditionally based on the
// platform.
bool AreSHA1IntermediatesAllowed() {
#if defined(OS_WIN)
// TODO(rsleevi): Remove this once https://crbug.com/588789 is resolved
// for Windows 7/2008 users.
// Note: This must be kept in sync with cert_verify_proc.cc
return base::win::GetVersion() < base::win::VERSION_WIN8;
#else
return false;
#endif
}
TEST(CertVerifyProcTest, RejectsMD2) {
scoped_refptr<X509Certificate> cert(
ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem"));
ASSERT_TRUE(cert);
CertVerifyResult result;
result.has_md2 = true;
scoped_refptr<CertVerifyProc> verify_proc = new MockCertVerifyProc(result);
int flags = 0;
CertVerifyResult verify_result;
int error = verify_proc->Verify(cert.get(), "127.0.0.1", std::string(), flags,
nullptr /* crl_set */, CertificateList(),
&verify_result);
EXPECT_THAT(error, IsError(ERR_CERT_INVALID));
EXPECT_TRUE(verify_result.cert_status & CERT_STATUS_INVALID);
}
TEST(CertVerifyProcTest, RejectsMD4) {
scoped_refptr<X509Certificate> cert(
ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem"));
ASSERT_TRUE(cert);
CertVerifyResult result;
result.has_md4 = true;
scoped_refptr<CertVerifyProc> verify_proc = new MockCertVerifyProc(result);
int flags = 0;
CertVerifyResult verify_result;
int error = verify_proc->Verify(cert.get(), "127.0.0.1", std::string(), flags,
nullptr /* crl_set */, CertificateList(),
&verify_result);
EXPECT_THAT(error, IsError(ERR_CERT_INVALID));
EXPECT_TRUE(verify_result.cert_status & CERT_STATUS_INVALID);
}
TEST(CertVerifyProcTest, RejectsMD5) {
scoped_refptr<X509Certificate> cert(
ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem"));
ASSERT_TRUE(cert);
CertVerifyResult result;
result.has_md5 = true;
scoped_refptr<CertVerifyProc> verify_proc = new MockCertVerifyProc(result);
int flags = 0;
CertVerifyResult verify_result;
int error = verify_proc->Verify(cert.get(), "127.0.0.1", std::string(), flags,
nullptr /* crl_set */, CertificateList(),
&verify_result);
EXPECT_THAT(error, IsError(ERR_CERT_WEAK_SIGNATURE_ALGORITHM));
EXPECT_TRUE(verify_result.cert_status & CERT_STATUS_WEAK_SIGNATURE_ALGORITHM);
}
TEST(CertVerifyProcTest, RejectsPublicSHA1Leaves) {
scoped_refptr<X509Certificate> cert(
ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem"));
ASSERT_TRUE(cert);
CertVerifyResult result;
result.has_sha1 = true;
result.has_sha1_leaf = true;
result.is_issued_by_known_root = true;
scoped_refptr<CertVerifyProc> verify_proc = new MockCertVerifyProc(result);
int flags = 0;
CertVerifyResult verify_result;
int error = verify_proc->Verify(cert.get(), "127.0.0.1", std::string(), flags,
nullptr /* crl_set */, CertificateList(),
&verify_result);
EXPECT_THAT(error, IsError(ERR_CERT_WEAK_SIGNATURE_ALGORITHM));
EXPECT_TRUE(verify_result.cert_status & CERT_STATUS_WEAK_SIGNATURE_ALGORITHM);
}
TEST(CertVerifyProcTest, RejectsPublicSHA1IntermediatesUnlessAllowed) {
scoped_refptr<X509Certificate> cert(ImportCertFromFile(
GetTestCertsDirectory(), "39_months_after_2015_04.pem"));
ASSERT_TRUE(cert);
CertVerifyResult result;
result.has_sha1 = true;
result.has_sha1_leaf = false;
result.is_issued_by_known_root = true;
scoped_refptr<CertVerifyProc> verify_proc = new MockCertVerifyProc(result);
int flags = 0;
CertVerifyResult verify_result;
int error = verify_proc->Verify(cert.get(), "127.0.0.1", std::string(), flags,
nullptr /* crl_set */, CertificateList(),
&verify_result);
if (AreSHA1IntermediatesAllowed()) {
EXPECT_THAT(error, IsOk());
EXPECT_TRUE(verify_result.cert_status & CERT_STATUS_SHA1_SIGNATURE_PRESENT);
} else {
EXPECT_THAT(error, IsError(ERR_CERT_WEAK_SIGNATURE_ALGORITHM));
EXPECT_TRUE(verify_result.cert_status &
CERT_STATUS_WEAK_SIGNATURE_ALGORITHM);
}
}
TEST(CertVerifyProcTest, RejectsPrivateSHA1UnlessFlag) {
scoped_refptr<X509Certificate> cert(
ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem"));
ASSERT_TRUE(cert);
CertVerifyResult result;
result.has_sha1 = true;
result.has_sha1_leaf = true;
result.is_issued_by_known_root = false;
scoped_refptr<CertVerifyProc> verify_proc = new MockCertVerifyProc(result);
// SHA-1 should be rejected by default for private roots...
int flags = 0;
CertVerifyResult verify_result;
int error = verify_proc->Verify(cert.get(), "127.0.0.1", std::string(), flags,
nullptr /* crl_set */, CertificateList(),
&verify_result);
EXPECT_THAT(error, IsError(ERR_CERT_WEAK_SIGNATURE_ALGORITHM));
EXPECT_TRUE(verify_result.cert_status & CERT_STATUS_SHA1_SIGNATURE_PRESENT);
// ... unless VERIFY_ENABLE_SHA1_LOCAL_ANCHORS was supplied.
flags = CertVerifier::VERIFY_ENABLE_SHA1_LOCAL_ANCHORS;
verify_result.Reset();
error = verify_proc->Verify(cert.get(), "127.0.0.1", std::string(), flags,
nullptr /* crl_set */, CertificateList(),
&verify_result);
EXPECT_THAT(error, IsOk());
EXPECT_TRUE(verify_result.cert_status & CERT_STATUS_SHA1_SIGNATURE_PRESENT);
}
enum ExpectedAlgorithms {
EXPECT_MD2 = 1 << 0,
EXPECT_MD4 = 1 << 1,
EXPECT_MD5 = 1 << 2,
EXPECT_SHA1 = 1 << 3,
EXPECT_SHA1_LEAF = 1 << 4,
};
struct WeakDigestTestData {
const char* root_cert_filename;
const char* intermediate_cert_filename;
const char* ee_cert_filename;
int expected_algorithms;
};
const char* StringOrDefault(const char* str, const char* default_value) {
if (!str)
return default_value;
return str;
}
// GTest 'magic' pretty-printer, so that if/when a test fails, it knows how
// to output the parameter that was passed. Without this, it will simply
// attempt to print out the first twenty bytes of the object, which depending
// on platform and alignment, may result in an invalid read.
void PrintTo(const WeakDigestTestData& data, std::ostream* os) {
*os << "root: " << StringOrDefault(data.root_cert_filename, "none")
<< "; intermediate: "
<< StringOrDefault(data.intermediate_cert_filename, "none")
<< "; end-entity: " << data.ee_cert_filename;
}
class CertVerifyProcWeakDigestTest
: public testing::TestWithParam<WeakDigestTestData> {
public:
CertVerifyProcWeakDigestTest() {}
virtual ~CertVerifyProcWeakDigestTest() {}
};
// Tests that the CertVerifyProc::Verify() properly surfaces the (weak) hash
// algorithms used in the chain.
TEST_P(CertVerifyProcWeakDigestTest, VerifyDetectsAlgorithm) {
WeakDigestTestData data = GetParam();
base::FilePath certs_dir = GetTestCertsDirectory();
scoped_refptr<X509Certificate> intermediate_cert;
scoped_refptr<X509Certificate> root_cert;
// Build |intermediates| as the full chain (including trust anchor).
X509Certificate::OSCertHandles intermediates;
if (data.intermediate_cert_filename) {
intermediate_cert =
ImportCertFromFile(certs_dir, data.intermediate_cert_filename);
ASSERT_TRUE(intermediate_cert);
intermediates.push_back(intermediate_cert->os_cert_handle());
}
if (data.root_cert_filename) {
root_cert = ImportCertFromFile(certs_dir, data.root_cert_filename);
ASSERT_TRUE(root_cert);
intermediates.push_back(root_cert->os_cert_handle());
}
scoped_refptr<X509Certificate> ee_cert =
ImportCertFromFile(certs_dir, data.ee_cert_filename);
ASSERT_TRUE(ee_cert);
scoped_refptr<X509Certificate> ee_chain = X509Certificate::CreateFromHandle(
ee_cert->os_cert_handle(), intermediates);
ASSERT_TRUE(ee_chain);
int flags = 0;
CertVerifyResult verify_result;
// Use a mock CertVerifyProc that returns success with a verified_cert of
// |ee_chain|.
//
// This is sufficient for the purposes of this test, as the checking for weak
// hash algorithms is done by CertVerifyProc::Verify().
scoped_refptr<CertVerifyProc> proc =
new MockCertVerifyProc(CertVerifyResult());
proc->Verify(ee_chain.get(), "127.0.0.1", std::string(), flags, nullptr,
CertificateList(), &verify_result);
EXPECT_EQ(!!(data.expected_algorithms & EXPECT_MD2), verify_result.has_md2);
EXPECT_EQ(!!(data.expected_algorithms & EXPECT_MD4), verify_result.has_md4);
EXPECT_EQ(!!(data.expected_algorithms & EXPECT_MD5), verify_result.has_md5);
EXPECT_EQ(!!(data.expected_algorithms & EXPECT_SHA1), verify_result.has_sha1);
EXPECT_EQ(!!(data.expected_algorithms & EXPECT_SHA1_LEAF),
verify_result.has_sha1_leaf);
}
// The signature algorithm of the root CA should not matter.
const WeakDigestTestData kVerifyRootCATestData[] = {
{"weak_digest_md5_root.pem", "weak_digest_sha1_intermediate.pem",
"weak_digest_sha1_ee.pem", EXPECT_SHA1 | EXPECT_SHA1_LEAF},
{"weak_digest_md4_root.pem", "weak_digest_sha1_intermediate.pem",
"weak_digest_sha1_ee.pem", EXPECT_SHA1 | EXPECT_SHA1_LEAF},
{"weak_digest_md2_root.pem", "weak_digest_sha1_intermediate.pem",
"weak_digest_sha1_ee.pem", EXPECT_SHA1 | EXPECT_SHA1_LEAF},
};
INSTANTIATE_TEST_CASE_P(VerifyRoot,
CertVerifyProcWeakDigestTest,
testing::ValuesIn(kVerifyRootCATestData));
// The signature algorithm of intermediates should be properly detected.
const WeakDigestTestData kVerifyIntermediateCATestData[] = {
{"weak_digest_sha1_root.pem", "weak_digest_md5_intermediate.pem",
"weak_digest_sha1_ee.pem", EXPECT_MD5 | EXPECT_SHA1 | EXPECT_SHA1_LEAF},
{"weak_digest_sha1_root.pem", "weak_digest_md4_intermediate.pem",
"weak_digest_sha1_ee.pem", EXPECT_MD4 | EXPECT_SHA1 | EXPECT_SHA1_LEAF},
{"weak_digest_sha1_root.pem", "weak_digest_md2_intermediate.pem",
"weak_digest_sha1_ee.pem", EXPECT_MD2 | EXPECT_SHA1 | EXPECT_SHA1_LEAF},
};
INSTANTIATE_TEST_CASE_P(VerifyIntermediate,
CertVerifyProcWeakDigestTest,
testing::ValuesIn(kVerifyIntermediateCATestData));
// The signature algorithm of end-entity should be properly detected.
const WeakDigestTestData kVerifyEndEntityTestData[] = {
{"weak_digest_sha1_root.pem", "weak_digest_sha1_intermediate.pem",
"weak_digest_md5_ee.pem", EXPECT_MD5 | EXPECT_SHA1},
{"weak_digest_sha1_root.pem", "weak_digest_sha1_intermediate.pem",
"weak_digest_md4_ee.pem", EXPECT_MD4 | EXPECT_SHA1},
{"weak_digest_sha1_root.pem", "weak_digest_sha1_intermediate.pem",
"weak_digest_md2_ee.pem", EXPECT_MD2 | EXPECT_SHA1},
};
INSTANTIATE_TEST_CASE_P(VerifyEndEntity,
CertVerifyProcWeakDigestTest,
testing::ValuesIn(kVerifyEndEntityTestData));
// Incomplete chains do not report the status of the intermediate.
// Note: really each of these tests should also expect the digest algorithm of
// the intermediate (included as a comment). However CertVerifyProc::Verify() is
// unable to distinguish that this is an intermediate and not a trust anchor, so
// this intermediate is treated like a trust anchor.
const WeakDigestTestData kVerifyIncompleteIntermediateTestData[] = {
{NULL, "weak_digest_md5_intermediate.pem", "weak_digest_sha1_ee.pem",
/*EXPECT_MD5 |*/ EXPECT_SHA1 | EXPECT_SHA1_LEAF},
{NULL, "weak_digest_md4_intermediate.pem", "weak_digest_sha1_ee.pem",
/*EXPECT_MD4 |*/ EXPECT_SHA1 | EXPECT_SHA1_LEAF},
{NULL, "weak_digest_md2_intermediate.pem", "weak_digest_sha1_ee.pem",
/*EXPECT_MD2 |*/ EXPECT_SHA1 | EXPECT_SHA1_LEAF},
};
INSTANTIATE_TEST_CASE_P(
MAYBE_VerifyIncompleteIntermediate,
CertVerifyProcWeakDigestTest,
testing::ValuesIn(kVerifyIncompleteIntermediateTestData));
// Incomplete chains should report the status of the end-entity.
// Note: really each of these tests should also expect EXPECT_SHA1 (included as
// a comment). However CertVerifyProc::Verify() is unable to distinguish that
// this is an intermediate and not a trust anchor, so this intermediate is
// treated like a trust anchor.
const WeakDigestTestData kVerifyIncompleteEETestData[] = {
{NULL, "weak_digest_sha1_intermediate.pem", "weak_digest_md5_ee.pem",
/*EXPECT_SHA1 |*/ EXPECT_MD5},
{NULL, "weak_digest_sha1_intermediate.pem", "weak_digest_md4_ee.pem",
/*EXPECT_SHA1 |*/ EXPECT_MD4},
{NULL, "weak_digest_sha1_intermediate.pem", "weak_digest_md2_ee.pem",
/*EXPECT_SHA1 |*/ EXPECT_MD2},
};
INSTANTIATE_TEST_CASE_P(VerifyIncompleteEndEntity,
CertVerifyProcWeakDigestTest,
testing::ValuesIn(kVerifyIncompleteEETestData));
// Differing algorithms between the intermediate and the EE should still be
// reported.
const WeakDigestTestData kVerifyMixedTestData[] = {
{"weak_digest_sha1_root.pem", "weak_digest_md5_intermediate.pem",
"weak_digest_md2_ee.pem", EXPECT_MD2 | EXPECT_MD5},
{"weak_digest_sha1_root.pem", "weak_digest_md2_intermediate.pem",
"weak_digest_md5_ee.pem", EXPECT_MD2 | EXPECT_MD5},
{"weak_digest_sha1_root.pem", "weak_digest_md4_intermediate.pem",
"weak_digest_md2_ee.pem", EXPECT_MD2 | EXPECT_MD4},
};
INSTANTIATE_TEST_CASE_P(VerifyMixed,
CertVerifyProcWeakDigestTest,
testing::ValuesIn(kVerifyMixedTestData));
// The EE is a trusted certificate. Even though it uses weak hashes, these
// should not be reported.
const WeakDigestTestData kVerifyTrustedEETestData[] = {
{NULL, NULL, "weak_digest_md5_ee.pem", 0},
{NULL, NULL, "weak_digest_md4_ee.pem", 0},
{NULL, NULL, "weak_digest_md2_ee.pem", 0},
{NULL, NULL, "weak_digest_sha1_ee.pem", 0},
};
INSTANTIATE_TEST_CASE_P(VerifyTrustedEE,
CertVerifyProcWeakDigestTest,
testing::ValuesIn(kVerifyTrustedEETestData));
// Test fixture for verifying certificate names.
class CertVerifyProcNameTest : public ::testing::Test {
protected:
void VerifyCertName(const char* hostname, bool valid) {
scoped_refptr<X509Certificate> cert(ImportCertFromFile(
GetTestCertsDirectory(), "subjectAltName_sanity_check.pem"));
ASSERT_TRUE(cert);
CertVerifyResult result;
result.is_issued_by_known_root = false;
scoped_refptr<CertVerifyProc> verify_proc = new MockCertVerifyProc(result);
CertVerifyResult verify_result;
int error = verify_proc->Verify(cert.get(), hostname, std::string(), 0,
nullptr, CertificateList(), &verify_result);
if (valid) {
EXPECT_THAT(error, IsOk());
EXPECT_FALSE(verify_result.cert_status & CERT_STATUS_COMMON_NAME_INVALID);
} else {
EXPECT_THAT(error, IsError(ERR_CERT_COMMON_NAME_INVALID));
EXPECT_TRUE(verify_result.cert_status & CERT_STATUS_COMMON_NAME_INVALID);
}
}
};
// Don't match the common name
TEST_F(CertVerifyProcNameTest, DontMatchCommonName) {
VerifyCertName("127.0.0.1", false);
}
// Matches the iPAddress SAN (IPv4)
TEST_F(CertVerifyProcNameTest, MatchesIpSanIpv4) {
VerifyCertName("127.0.0.2", true);
}
// Matches the iPAddress SAN (IPv6)
TEST_F(CertVerifyProcNameTest, MatchesIpSanIpv6) {
VerifyCertName("FE80:0:0:0:0:0:0:1", true);
}
// Should not match the iPAddress SAN
TEST_F(CertVerifyProcNameTest, DoesntMatchIpSanIpv6) {
VerifyCertName("[FE80:0:0:0:0:0:0:1]", false);
}
// Compressed form matches the iPAddress SAN (IPv6)
TEST_F(CertVerifyProcNameTest, MatchesIpSanCompressedIpv6) {
VerifyCertName("FE80::1", true);
}
// IPv6 mapped form should NOT match iPAddress SAN
TEST_F(CertVerifyProcNameTest, DoesntMatchIpSanIPv6Mapped) {
VerifyCertName("::127.0.0.2", false);
}
// Matches the dNSName SAN
TEST_F(CertVerifyProcNameTest, MatchesDnsSan) {
VerifyCertName("test.example", true);
}
// Matches the dNSName SAN (trailing . ignored)
TEST_F(CertVerifyProcNameTest, MatchesDnsSanTrailingDot) {
VerifyCertName("test.example.", true);
}
// Should not match the dNSName SAN
TEST_F(CertVerifyProcNameTest, DoesntMatchDnsSan) {
VerifyCertName("www.test.example", false);
}
// Should not match the dNSName SAN
TEST_F(CertVerifyProcNameTest, DoesntMatchDnsSanInvalid) {
VerifyCertName("test..example", false);
}
// Should not match the dNSName SAN
TEST_F(CertVerifyProcNameTest, DoesntMatchDnsSanTwoTrailingDots) {
VerifyCertName("test.example..", false);
}
// Should not match the dNSName SAN
TEST_F(CertVerifyProcNameTest, DoesntMatchDnsSanLeadingAndTrailingDot) {
VerifyCertName(".test.example.", false);
}
// Should not match the dNSName SAN
TEST_F(CertVerifyProcNameTest, DoesntMatchDnsSanTrailingDot) {
VerifyCertName(".test.example", false);
}
// Tests that commonName-fallback is handled correctly:
// - If it's a publicly trusted certificate, the commonName should never
// match.
// - If it chains to a private root, the commonName should not match if
// the subjectAltName is absent, and the flags don't allow fallback.
// - If it chains to a private root, the commonName SHOULD match iff the
// subjectAltName is absent and the flags allow a fallback.
TEST_F(CertVerifyProcNameTest, HandlesCommonNameFallbackLocalAnchors) {
scoped_refptr<X509Certificate> cert(
ImportCertFromFile(GetTestCertsDirectory(), "salesforce_com_test.pem"));
ASSERT_TRUE(cert);
CertVerifyResult result;
scoped_refptr<CertVerifyProc> verify_proc;
CertVerifyResult verify_result;
int error;
// Publicly trusted: Always ignores commonName, regardless of flags.
result = CertVerifyResult();
verify_result = CertVerifyResult();
error = 0;
result.is_issued_by_known_root = true;
verify_proc = new MockCertVerifyProc(result);
error = verify_proc->Verify(cert.get(), "prerelna1.pre.salesforce.com",
std::string(), 0, nullptr, CertificateList(),
&verify_result);
EXPECT_THAT(error, IsError(ERR_CERT_COMMON_NAME_INVALID));
EXPECT_TRUE(verify_result.cert_status & CERT_STATUS_COMMON_NAME_INVALID);
result = CertVerifyResult();
verify_result = CertVerifyResult();
error = 0;
result.is_issued_by_known_root = true;
verify_proc = new MockCertVerifyProc(result);
error = verify_proc->Verify(
cert.get(), "prerelna1.pre.salesforce.com", std::string(),
CertVerifier::VERIFY_ENABLE_COMMON_NAME_FALLBACK_LOCAL_ANCHORS, nullptr,
CertificateList(), &verify_result);
EXPECT_THAT(error, IsError(ERR_CERT_COMMON_NAME_INVALID));
EXPECT_TRUE(verify_result.cert_status & CERT_STATUS_COMMON_NAME_INVALID);
// Privately trusted: Ignores commonName by default.
result = CertVerifyResult();
verify_result = CertVerifyResult();
error = 0;
result.is_issued_by_known_root = false;
verify_proc = new MockCertVerifyProc(result);
error = verify_proc->Verify(cert.get(), "prerelna1.pre.salesforce.com",
std::string(), 0, nullptr, CertificateList(),
&verify_result);
EXPECT_THAT(error, IsError(ERR_CERT_COMMON_NAME_INVALID));
EXPECT_TRUE(verify_result.cert_status & CERT_STATUS_COMMON_NAME_INVALID);
// Privately trusted: Falls back to common name if flags allow.
result = CertVerifyResult();
verify_result = CertVerifyResult();
error = 0;
result.is_issued_by_known_root = false;
verify_proc = new MockCertVerifyProc(result);
error = verify_proc->Verify(
cert.get(), "prerelna1.pre.salesforce.com", std::string(),
CertVerifier::VERIFY_ENABLE_COMMON_NAME_FALLBACK_LOCAL_ANCHORS, nullptr,
CertificateList(), &verify_result);
EXPECT_THAT(error, IsOk());
EXPECT_FALSE(verify_result.cert_status & CERT_STATUS_COMMON_NAME_INVALID);
}
// Tests that CertVerifyProc records a histogram correctly when a
// certificate chaining to a private root contains the TLS feature
// extension and does not have a stapled OCSP response.
TEST(CertVerifyProcTest, HasTLSFeatureExtensionUMA) {
base::HistogramTester histograms;
scoped_refptr<X509Certificate> cert(
ImportCertFromFile(GetTestCertsDirectory(), "tls_feature_extension.pem"));
ASSERT_TRUE(cert);
CertVerifyResult result;
result.is_issued_by_known_root = false;
scoped_refptr<CertVerifyProc> verify_proc = new MockCertVerifyProc(result);
histograms.ExpectTotalCount(kTLSFeatureExtensionHistogram, 0);
histograms.ExpectTotalCount(kTLSFeatureExtensionOCSPHistogram, 0);
int flags = 0;
CertVerifyResult verify_result;
int error = verify_proc->Verify(cert.get(), "127.0.0.1", std::string(), flags,
NULL, CertificateList(), &verify_result);
EXPECT_EQ(OK, error);
histograms.ExpectTotalCount(kTLSFeatureExtensionHistogram, 1);
histograms.ExpectBucketCount(kTLSFeatureExtensionHistogram, true, 1);
histograms.ExpectTotalCount(kTLSFeatureExtensionOCSPHistogram, 1);
histograms.ExpectBucketCount(kTLSFeatureExtensionOCSPHistogram, false, 1);
}
// Tests that CertVerifyProc records a histogram correctly when a
// certificate chaining to a private root contains the TLS feature
// extension and does have a stapled OCSP response.
TEST(CertVerifyProcTest, HasTLSFeatureExtensionWithStapleUMA) {
base::HistogramTester histograms;
scoped_refptr<X509Certificate> cert(
ImportCertFromFile(GetTestCertsDirectory(), "tls_feature_extension.pem"));
ASSERT_TRUE(cert);
CertVerifyResult result;
result.is_issued_by_known_root = false;
scoped_refptr<CertVerifyProc> verify_proc = new MockCertVerifyProc(result);
histograms.ExpectTotalCount(kTLSFeatureExtensionHistogram, 0);
histograms.ExpectTotalCount(kTLSFeatureExtensionOCSPHistogram, 0);
int flags = 0;
CertVerifyResult verify_result;
int error =
verify_proc->Verify(cert.get(), "127.0.0.1", "dummy response", flags,
nullptr, CertificateList(), &verify_result);
EXPECT_EQ(OK, error);
histograms.ExpectTotalCount(kTLSFeatureExtensionHistogram, 1);
histograms.ExpectBucketCount(kTLSFeatureExtensionHistogram, true, 1);
histograms.ExpectTotalCount(kTLSFeatureExtensionOCSPHistogram, 1);
histograms.ExpectBucketCount(kTLSFeatureExtensionOCSPHistogram, true, 1);
}
// Tests that CertVerifyProc records a histogram correctly when a
// certificate chaining to a private root does not contain the TLS feature
// extension.
TEST(CertVerifyProcTest, DoesNotHaveTLSFeatureExtensionUMA) {
base::HistogramTester histograms;
scoped_refptr<X509Certificate> cert(
ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem"));
ASSERT_TRUE(cert);
CertVerifyResult result;
result.is_issued_by_known_root = false;
scoped_refptr<CertVerifyProc> verify_proc = new MockCertVerifyProc(result);
histograms.ExpectTotalCount(kTLSFeatureExtensionHistogram, 0);
histograms.ExpectTotalCount(kTLSFeatureExtensionOCSPHistogram, 0);
int flags = 0;
CertVerifyResult verify_result;
int error = verify_proc->Verify(cert.get(), "127.0.0.1", std::string(), flags,
NULL, CertificateList(), &verify_result);
EXPECT_EQ(OK, error);
histograms.ExpectTotalCount(kTLSFeatureExtensionHistogram, 1);
histograms.ExpectBucketCount(kTLSFeatureExtensionHistogram, false, 1);
histograms.ExpectTotalCount(kTLSFeatureExtensionOCSPHistogram, 0);
}
// Tests that CertVerifyProc does not record a histogram when a
// certificate contains the TLS feature extension but chains to a public
// root.
TEST(CertVerifyProcTest, HasTLSFeatureExtensionWithPublicRootUMA) {
base::HistogramTester histograms;
scoped_refptr<X509Certificate> cert(
ImportCertFromFile(GetTestCertsDirectory(), "tls_feature_extension.pem"));
ASSERT_TRUE(cert);
CertVerifyResult result;
result.is_issued_by_known_root = true;
scoped_refptr<CertVerifyProc> verify_proc = new MockCertVerifyProc(result);
histograms.ExpectTotalCount(kTLSFeatureExtensionHistogram, 0);
int flags = 0;
CertVerifyResult verify_result;
int error = verify_proc->Verify(cert.get(), "127.0.0.1", std::string(), flags,
NULL, CertificateList(), &verify_result);
EXPECT_EQ(OK, error);
histograms.ExpectTotalCount(kTLSFeatureExtensionHistogram, 0);
histograms.ExpectTotalCount(kTLSFeatureExtensionOCSPHistogram, 0);
}
} // namespace net
| [
"[email protected]"
]
| |
b8d970ff0d5d4d623442aaaf43d6b989e1acc168 | 80c3acebbf37278bf5899c207b1f32e45bd22092 | /Projekt/Content/content_manager.h | 38c1976d828346dc056a4b993213da846f3dda78 | []
| no_license | Kobzol/ZPG-project | fc9d85c5b61ed0379e8fc5f08d092eadbb87b6bd | c3e423cea687be51b5472c985c519308228ca10c | refs/heads/master | 2021-01-10T16:49:20.196016 | 2015-11-11T22:42:20 | 2015-11-11T22:42:20 | 44,061,033 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 549 | h | #pragma once
#include <unordered_map>
template <typename T>
class ContentManager
{
public:
void load(std::string identifier, const T &item)
{
this->items.emplace(identifier, item);
}
bool hasKey(std::string identifier)
{
return this->items.count(identifier) > 0;
}
T& get(std::string identifier)
{
if (this->items.count(identifier))
{
return this->items[identifier];
}
else throw std::runtime_error("No item with identifier " + identifier + " has been found.");
}
protected:
std::unordered_map<std::string, T> items;
}; | [
"[email protected]"
]
| |
b5c8cbf9b63e4ac685868aaa303c39d754bec457 | 75cdf0c1e66c0c6e7930788acc5a752fcf63e753 | /SimpleCoordinate.cpp | de8b1438e4fd02f9381ce3ab120858fc0fd2e652 | []
| no_license | topromulan/macrowave-balls-out-billiards | 179bcfcd2fbb59a92cef50fc75a9e5de955ef7c1 | d20f70f1098cb6a7812d4729c99061ba258d9bba | refs/heads/master | 2016-09-05T09:15:34.675497 | 2009-04-08T03:37:39 | 2009-04-08T03:37:39 | 158,879 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 276 | cpp |
#include "SimpleCoordinate.H"
void SimpleCoordinate::x(number n) {
longitudinal = n;
};
void SimpleCoordinate::y(number n) {
latitudinal = n;
};
number SimpleCoordinate::x(void) {
return longitudinal;
};
number SimpleCoordinate::y(void) {
return latitudinal;
};
| [
"[email protected]"
]
| |
6d7b96a29f6c7e3b8c8993743a8bfa357f88eb07 | 9a645579be52befbeb5adc9bc6dd1d4545bcf2b7 | /include/LuaResource.h | 3d0bb136ec9a2372df46319ea9506f14659fd97b | [
"MIT"
]
| permissive | PixelArtDragon/PolisEngine | 55f2d0d179eb072f169fb0d2f8db9319bde44677 | be3446937eade8457e93db64b59d57bb110aefdd | refs/heads/main | 2023-08-28T03:52:19.917969 | 2021-11-11T12:54:47 | 2021-11-11T12:54:47 | 396,887,959 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 175 | h | #pragma once
#include "sol/sol.hpp"
#include "ResourceLoader.h"
class LuaResource {
public:
static void AddResources(sol::state& lua, ResourceLoader& resource_loader);
};
| [
"[email protected]"
]
| |
eee09923ae701fdc18a8a0a3aa29d9207a281cca | ec9554cb393d8dd8e13f7546e81b9e7db3dfe700 | /atom/.node-gyp/.node-gyp/iojs-1.3.13/src/node_javascript.h | 52e1898163e99651cd6b6a904cfdc4ed291b64c8 | []
| no_license | plapier/dotfiles | ecbfa796f06e44814a3cc4c6179beb88c0fb77eb | 712b572b5b10e21b15dfcda5a1d981c4f6d1c8db | refs/heads/master | 2021-01-17T05:46:54.120302 | 2017-07-25T07:14:17 | 2017-07-25T07:14:17 | 1,829,553 | 3 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 434 | h | #ifndef SRC_NODE_JAVASCRIPT_H_
#define SRC_NODE_JAVASCRIPT_H_
#if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
#include "v8.h"
#include "env.h"
namespace node {
void DefineJavaScript(Environment* env, v8::Local<v8::Object> target);
v8::Local<v8::String> MainSource(Environment* env);
} // namespace node
#endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
#endif // SRC_NODE_JAVASCRIPT_H_
| [
"[email protected]"
]
| |
b9e0323e0de053a5fe851bf5947932e4adb4fa04 | a962db3467be3b04b68714abb00611ff92c121b6 | /Cpp-Primer-5th-answers/ch15/ex15.26/limit_quote.cpp | 716cde44f5475e27aa9dfd55b29d61c9e943216a | [
"CC0-1.0"
]
| permissive | blueyi/cpp_study | 6bf636076c4489996a95067bbf41d634b6a36b5d | 8d839744f9a7c7d217c265e6ca480eb78dbc7162 | refs/heads/master | 2020-04-05T14:04:48.226583 | 2016-09-01T01:16:45 | 2016-09-01T01:16:45 | 38,018,441 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 234 | cpp | #include "limit_quote.h"
void Limit_quote::debug() const
{
std::cout //<< "data members of this class:\n"
<< "max_qty= " << this->quantity << " "
<< "discount= " << this->discount<< " \n";
}
| [
"[email protected]"
]
| |
20f14f6fb7ead4b184206c26eb6f65ca027335b0 | af0ecafb5428bd556d49575da2a72f6f80d3d14b | /CodeJamCrawler/dataset/08_592_5.cpp | d39babb69db72ae7414a71f947a10199dd61ac50 | []
| no_license | gbrlas/AVSP | 0a2a08be5661c1b4a2238e875b6cdc88b4ee0997 | e259090bf282694676b2568023745f9ffb6d73fd | refs/heads/master | 2021-06-16T22:25:41.585830 | 2017-06-09T06:32:01 | 2017-06-09T06:32:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,464 | cpp | package com.murphy.google.code.jam;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.util.Arrays;
public class Round1CProblem1 {
public static void main(String arg[])throws Exception{
String input_file = "A-small-attempt0.in";
BufferedReader file_in = new BufferedReader(new FileReader(input_file));
String output_file = "output.txt";
FileOutputStream file_out = new FileOutputStream(output_file );
int num_cases = Integer.parseInt(file_in.readLine());
for(int i=1; i<=num_cases; i++){
String[] token = file_in.readLine().split(" ");
int P = Integer.parseInt(token[0]);
int K = Integer.parseInt(token[1]);
int L = Integer.parseInt(token[2]);
int[] frequency = new int[L];
token = file_in.readLine().split(" ");
for(int j=0; j<L; j++){
frequency[j] = Integer.parseInt(token[j]);
}
// sort the frequency
Arrays.sort(frequency);
int[] freq_table = new int[frequency.length];
for(int j=0; j<L; j++){
freq_table[L-1-j] = frequency[j];
}
int key_presses = 0;
int pos = 0;
for(int j=1; j<=P; j++){
for(int k=0; k<K; k++){
if(pos<freq_table.length){
key_presses += (freq_table[pos]*j);
pos++;
}else break;
}
}
String output = "Case #"+i+": "+key_presses+"\r\n";
file_out.write(output.getBytes());
}
file_in.close();
file_out.close();
}
}
| [
"[email protected]"
]
| |
c94cbe16484432a07ae6bc11c1df74c159c66ed4 | fa425c0b3c15794c36f463139b807cc4e4d31c3c | /sds.h | 2c9c061c59117b6b4b0ca5bf0eaebd9cfe302357 | []
| no_license | lygn128/Tinyfs | f8cb925325f8ba65b06cb8eeea4b37e778907c99 | 13ba9727d17afeab295e0f7e87214549583c8693 | refs/heads/master | 2021-01-10T07:42:32.398402 | 2016-04-08T11:35:48 | 2016-04-08T11:35:48 | 54,556,831 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 613 | h | //
// Created by lygn128 on 16-3-14.
//
#ifndef TFNODE_SDS_H
#define TFNODE_SDS_H
class sds {
int len;
int free;
public:
char *buff;
public:
sds(const char * str,int initLen);
sds(const char * str);
sds(const sds& ads);
sds();
static sds* newsds(char * buff,int initLenght);
static sds ** splitsds(char * string,int srclen,char *sep,int seplen,int * num);
void display();
sds sdtrim(const char *cset);
sds * sdcat(sds *src);
sds * sdcat(char * str);
sds * sdsAddprefix(char * str);
int getLen();
short sdstos();
};
#endif //TFNODE_SDS_H
| [
"5723366asd!Q"
]
| 5723366asd!Q |
d5c394784abeddbaa265e61cc344d9d70f7200e1 | 97d0e587d3f904e763c3071159a6570142b8c15c | /User.cpp | fcd70f37e99320f64c70a03e8617db54a9a76cc9 | []
| no_license | Umar-Baloch/Flixer | 98c86f2a49b9c57ff8def8bf229787350d71fd60 | 6118f676b71cd3c2b76a3d028b90511ba4da01c9 | refs/heads/main | 2023-04-03T22:12:36.845793 | 2021-04-12T17:39:35 | 2021-04-12T17:39:35 | 357,278,981 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,669 | cpp | #include "User.h"
using namespace std;
User::User(){}
//overloaded constructer
User::User(string id, string pwd){
this->ID = id;
this->PWD = pwd;
}
User::~User(){}
void User::set_id(string id){
this->ID = id;
}
void User::set_pwd(string pwd){
this->PWD = pwd;
}
//saves all followers of the user in a string vector
void User::set_followers(string flrs){
istringstream ss(flrs);
string token;
while(getline(ss, token, ',')) {
this->Followers.push_back(token);
}
}
//saves all of the users we are following in a string vector
void User::set_following(string flngs){
istringstream ss(flngs);
string token;
while(getline(ss, token, ',')) {
this->Following.push_back(token);
}
}
//function to call when some user unfollows us
void User::remove_follower(string flr){
int foundAt;
for(int i = 0; i != Followers.size(); i++){
if(Followers[i] == flr){
foundAt = i;
}
}
Followers.erase (Followers.begin()+foundAt);
}
//function to call when we unfollows some user
void User::remove_following(string flng){
int foundAt;
for(int i = 0; i != Following.size(); i++){
if(Following[i] == flng){
foundAt = i;
}
}
Following.erase (Following.begin()+foundAt);
}
void User::add_follower(string flr){
this->Followers.push_back(flr);
}
void User::add_following(string flng){
this->Following.push_back(flng);
}
string User::get_id(){
return this->ID;
}
string User::get_pwd(){
return this->PWD;
}
vector<string> User::get_followers(){
return this->Followers;
}
vector<string> User::get_following(){
return this->Following;
}
| [
"[email protected]"
]
| |
5cdda97465cc3e0361b25197b9c3eef93849ecfd | 15b3f4d8703fb23f30021d31d3ffc59e8acf92fd | /BuildSystem/include/arv/editor/file_media_src.h | fb2543360e1643defd577b52e524a1b8e389e13c | []
| no_license | OakCityLabs/iVCam | 2cd72b83d8b7130d3a22741fefcedbaa55becf54 | d4f2e8991cbc4711ed53c154df89328703f92a0b | refs/heads/master | 2021-01-23T10:39:35.021773 | 2017-09-06T16:59:11 | 2017-09-06T16:59:11 | 102,625,718 | 0 | 0 | null | 2017-09-06T15:28:42 | 2017-09-06T15:28:42 | null | UTF-8 | C++ | false | false | 1,603 | h | //
// file_media_source.hpp
// INSMediaApp
//
// Created by jerett on 16/7/13.
// Copyright © 2016 Insta360. All rights reserved.
//
#ifndef file_media_data_source_h
#define file_media_data_source_h
#include <string>
#include <tuple>
#include <av_toolbox/sp.h>
#include "media_src.h"
struct AVStream;
namespace ins {
const static std::string kSrcMode("read_mode");
class any;
class Demuxer;
class FileMediaSrc : public MediaSrc {
public:
///
/// \param url media source URL
explicit FileMediaSrc(const std::string &url);
~FileMediaSrc();
FileMediaSrc(const FileMediaSrc&) = delete;
FileMediaSrc(FileMediaSrc &&) = delete;
FileMediaSrc& operator=(const FileMediaSrc&) = delete;
/**
* @param start_ms Start time in ms
* @param end_ms End time in ms
*/
void set_trim_range(int64_t start_ms, int64_t end_ms) noexcept;
const AVStream* video_stream() const;
const AVStream* audio_stream() const;
int64_t video_duration() const;
int64_t audio_duration() const;
void SetOpt(const std::string &key, const any &val);
bool Prepare() override;
void Start() override;
void Cancel() override;
void Close() override;
public:
double progress() const override {
return progress_;
}
bool eof() const override {
return eof_;
}
private:
void OnEnd();
void OnError();
void Loop();
private:
bool eof_ = false;
double progress_ = 0;
bool stop_ = false;
bool realtime_ = false;
std::string file_url_;
std::tuple<bool, int64_t , int64_t> range_ = {false, 0, 0};
sp<Demuxer> demuxer_;
};
}
#endif /* file_media_source_hpp */
| [
"[email protected]"
]
| |
6ac5fd809e6c806aafc05be3eecba8592b9428b0 | 49cabb3ca07252fd207ee354364dd5fad75bd59c | /E.cpp | 287f13f4c2688d6fcf38ee4bf806a56d4d9ad455 | []
| no_license | Tareq57/Codeforces-Round-702 | a18e0801c5e29e0d71e82fcef9bf054ab5a6658c | c3edbaf4b302f06d149872832aca4a6adfd2b3be | refs/heads/main | 2023-05-28T15:54:22.987682 | 2021-06-11T15:26:30 | 2021-06-11T15:26:30 | 376,063,989 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,363 | cpp | //BISMILLAH
//RABBI JIDNI ILMA
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define pb push_back
#define mp make_pair
#define ull unsigned long long
#define vll vector <long long>
#define pll pair <long long,long long>
#define f first
#define s second
#define up upper_bound
#define lp lower_bound
#define pq priority_queue
#define inf 1e10
#define minf -1e18
#define pi 3.14159265
#define mod 1000000007
#define fastio ios_base::sync_with_stdio(0);cin.tie(NULL);
int main()
{
fastio
ll t;
cin>>t;
while(t--)
{
ll n;
cin>>n;
vll res;
vector<pll>vec;
for(ll i=0;i<n;i++)
{
ll num;
cin>>num;
vec.pb(mp(num,i+1));
}
sort(vec.begin(),vec.end());
ll cnt=1,sum=vec[0].f;
res.pb(vec[0].s);
for(ll i=1;i<n;i++)
{
if(sum>=vec[i].f)
{
cnt++;
res.pb(vec[i].s);
}
else
{
res.clear();
res.pb(vec[i].s);
cnt=1;
}
sum+=vec[i].f;
}
sort(res.begin(),res.end());
cout<<cnt<<endl;
for(auto x:res)cout<<x<<" ";
cout<<endl;
}
}
| [
"[email protected]"
]
| |
58bf53a3992b0062b841d84e474b48c467bae9c4 | e4e230808ce9fdce58d3b888e3c629bf476831e7 | /ZE_SWIMR_0_3_addition_of_depth_sensing/ZE_SWIMR_0_3_addition_of_depth_sensing.ino | 79713127db8f5f87b752557301466e856e1d3d2b | []
| no_license | cappa270/ArduinoMotorControl | eb9ace6af3a1ba00ed36d88545d89339b36cef8f | 34e482cb9607cdbdeaf858407f273d9eccf16b43 | refs/heads/master | 2016-09-06T18:12:19.838423 | 2013-05-07T16:11:23 | 2013-05-07T16:11:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 25,473 | ino |
/*********************************************************************
Written by Mitch Fynaardt
Date: February 1, 2013
Last Rev: February 9, 2013
This sketch utilizes serial library to capture date from
ArduIMU V3 and prints values back to the user. The Arduino Mega also
captures user input via a hardware serial port and calculates a
servo motor speed.
*********************************************************************/
#include <Servo.h>
#include <DHT22.h>
// analog pin for reading water temperature
#define THERMISTORPIN A1
// resistance at 25 degrees C
#define THERMISTORNOMINAL 10000
// temp. for nominal resistance (almost always 25 C)
#define TEMPERATURENOMINAL 25
// how many water temperature samples to take
#define NUMSAMPLES 5
// The beta coefficient of the thermistor (usually 3000-4000)
#define BCOEFFICIENT 3950
// the value of the 'other' resistor in the voltage divider
#define SERIESRESISTOR 10000
// float array for storing the parsed IMU data.
int parsed_IMU_data[3];
// String to store the incoming data from the IMU
String IMU_input_string = "";
//{error, arm, roll, pitch, yaw, x, y, z}
byte commands[] = {0,0,127,127,127,127,127,127};
float danger_threshold = 10.8;
float internal_temp;
float internal_humidity;
float water_temp;
float water_depth;
float total_voltage;
// motor pin objects
#define left_axial_motor_pin 7
#define right_axial_motor_pin 2
#define strafing_motor_pin 4
#define front_left_vertical_motor_pin 6
#define front_right_vertical_motor_pin 3
#define rear_vertical_motor_pin 5
// internal temp and humidity sensor object on pin 8
#define DHT22_PIN 8
// instance of DHT22 internal temp sensor
DHT22 myDHT22(DHT22_PIN);
// samples variable is used to compute water temp
int samples[NUMSAMPLES];
// Battery sensing pin
int batt_pin = A0;
// Servo objects to control servo motors
Servo left_axial_motor;
Servo right_axial_motor;
Servo strafing_motor;
Servo front_left_vertical_motor;
Servo front_right_vertical_motor;
Servo rear_vertical_motor;
// Initialize motor speeds to neutral
int left_axial_motor_speed = 1500;
int right_axial_motor_speed = 1500;
int strafing_motor_speed = 1500;
int front_left_vertical_motor_speed = 1500;
int front_right_vertical_motor_speed = 1500;
int rear_vertical_motor_speed = 1500;
// Initialize direction speeds
int x_speed = 127;
int y_speed = 127;
int z_speed = 127;
int roll_speed = 127;
int pitch_speed = 127;
int yaw_speed = 127;
// loop tracking variables
unsigned long last_time = 0;
unsigned long loop_runs = 0;
unsigned long last_sensor_read = 0;
// motor state tracker
boolean armed = false;
// serial input flags
boolean new_commands_present = false;
boolean new_IMU_data_present = false;
// danger status flags
boolean water_leak = false;
boolean returning_to_surface = false;
// User defined settings
#define FRESH_WATER 1
#if FRESH_WATER == 1
float depth_conversion = 2.9647456347;
#else
float depth_conversion = 3.0336932076;
#endif
// used to print debugging messages
#define DEBUGGING 0
#define MONITOR 0
void setup()
{
Serial.begin(115200);
Serial1.begin(38400);
IMU_input_string.reserve(38);
boolean motor_setup_debug = motor_setup();
#if MONITOR == 1
if (motor_setup_debug)
{
Serial.println("Motors successfully attached to drive pins");
} else {
Serial.println("Motor pins not attached");
}
#endif
}
void loop()
{
if( millis()- last_time > 50)
{
last_time = millis();
// new values read from IMU
get_IMU_data();
// new IMU values and user input interpretted into motor commands
motor_driver();
// sensor values read and calculated
dht22();
water_temp = get_water_temp();
water_depth = get_depth();
// battery check function
check_battery_voltage(danger_threshold);
// send all updated values and info to the user
send_data();
}
// function that reads and stores new user commands
new_commands();
// function that receives new IMU data
new_IMU_data_received();
}
/*********************************************************************
Function to read IMU values and make them useful for the Arduino MEGA
Input: None
Output: None
*******************************************************************/
void get_IMU_data()
{
/* motor driver only runs when there is new IMU input data */
if( IMU_input_string.length() > 0)
{
// Next 6 statements are used to mark indeces of the delimiter characters
int colon_1 = IMU_input_string.indexOf(':');
int comma_1 = IMU_input_string.indexOf(',');
int colon_2 = IMU_input_string.indexOf(':',colon_1 + 1);
int comma_2 = IMU_input_string.indexOf(',',comma_1+1);
int colon_3 = IMU_input_string.indexOf(':',colon_2 + 1);
int star = IMU_input_string.indexOf('*',colon_2 + 1);
String roll_string = IMU_input_string.substring(colon_1+1,comma_1);
String pitch_string = IMU_input_string.substring(colon_2+1,comma_2);
String yaw_string = IMU_input_string.substring(colon_3+1,star);
// Conversion from strings to ints
parsed_IMU_data[0] = roll_string.toInt();
parsed_IMU_data[1] = pitch_string.toInt();
parsed_IMU_data[2] = yaw_string.toInt();
IMU_input_string = "";
#if DEBUGGING == 1
Serial.println();
Serial.println();
Serial.print("loop run: ");
Serial.println(loop_runs);
loop_runs++;
Serial.println("Strings");
Serial.print("RLL:");
Serial.print(roll_string);
Serial.print(" PCH:");
Serial.print(pitch_string);
Serial.print(" YAW: ");
Serial.println(yaw_string);
Serial.println();
Serial.println("Ints");
Serial.print("RLL:");
Serial.print(parsed_IMU_data[0]);
Serial.print(" PCH:");
Serial.print(parsed_IMU_data[1]);
Serial.print(" YAW: ");
Serial.println(parsed_IMU_data[2]);
#endif
}
}
/****************************************************************
End IMU serial read module
****************************************************************/
/****************************************************************
Motor module
This function attaches motor pins and runs startup configurations
****************************************************************/
boolean motor_setup()
{
left_axial_motor.attach(left_axial_motor_pin);
right_axial_motor.attach(right_axial_motor_pin);
strafing_motor.attach(strafing_motor_pin);
front_left_vertical_motor.attach(front_left_vertical_motor_pin);
front_right_vertical_motor.attach(front_right_vertical_motor_pin);
rear_vertical_motor.attach(rear_vertical_motor_pin);
left_axial_motor.writeMicroseconds(left_axial_motor_speed);
right_axial_motor.writeMicroseconds(right_axial_motor_speed);
strafing_motor.writeMicroseconds(strafing_motor_speed);
front_left_vertical_motor.writeMicroseconds(front_left_vertical_motor_speed);
front_right_vertical_motor.writeMicroseconds(front_right_vertical_motor_speed);
rear_vertical_motor.writeMicroseconds(rear_vertical_motor_speed);
return left_axial_motor.attached() && right_axial_motor.attached() && strafing_motor.attached() && front_left_vertical_motor.attached() && front_right_vertical_motor.attached() && rear_vertical_motor.attached();
}
/****************************************************************
End Motor Module
****************************************************************/
/****************************************************************
Motor Driver Module
Input: Boolean - armed state of the servo motors
Output: void
This function starts and stops each motor according to input
and IMU readings
****************************************************************/
void motor_driver()
{
// storage variables which will be used to scale the motor speeds
int current_roll = int(parsed_IMU_data[0]);
int current_pitch = int(parsed_IMU_data[1]);
int current_yaw = int(parsed_IMU_data[2]);
int max_user_input = 255;
int min_user_input = 0;
// maximum increments for motors to prevent motors from drawing more than 12 Amps
int user_roll_max = 250;
int user_pitch_max = 250;
int user_yaw_max = 250;
int user_x_max = 250;
int user_y_max = 250;
int user_z_max = 250;
// this variable is the maximum drive increment that the IMU may send to adjust position
int max_IMU_adjustment = 250;
if( armed)
{
// IMU calculations take place here, the results will bring the Sub back to neutral position
// if no user input is being received
current_roll = constrain(current_roll, -180, 180);
current_pitch = constrain(current_pitch, -180, 180);
current_yaw = constrain(current_yaw, -180, 180);
int IMU_roll_adjustment = map(current_roll, -180, 180, -max_IMU_adjustment, max_IMU_adjustment);
int IMU_pitch_adjustment = map(current_pitch, -180, 180, -max_IMU_adjustment, max_IMU_adjustment);
int IMU_yaw_adjustment = map(current_yaw, -180, 180, -max_IMU_adjustment, max_IMU_adjustment);
// ADD DESCRIPTORS ABOVE EACH MOTOR INDICATING WHICH DIRECTION EACH MAX VALUE DRIVES
roll_speed = map((int)commands[2], min_user_input, max_user_input, -user_roll_max, user_roll_max);
//
pitch_speed = map((int)commands[3], min_user_input, max_user_input, -user_pitch_max, user_pitch_max);
//
yaw_speed = map((int)commands[4], min_user_input, max_user_input, -user_yaw_max, user_yaw_max);
//
x_speed = map((int)commands[5], min_user_input, max_user_input, -user_x_max, user_x_max);
//
y_speed = map((int)commands[6], min_user_input, max_user_input, -user_y_max, user_y_max);
//
z_speed = map((int)commands[7], min_user_input, max_user_input, -user_z_max, user_z_max);
// Drive motors with either the user input or the IMU data
left_axial_motor_speed = 1500 + x_speed - yaw_speed;
right_axial_motor_speed = 1500 + x_speed + yaw_speed;
strafing_motor_speed = 1500 + y_speed;
if (commands[2] == 127 && commands[3] == 127)
{
if (current_pitch > 15 || current_pitch < -15)
{
front_left_vertical_motor_speed = 1500 + (0.5 * IMU_pitch_adjustment);
front_right_vertical_motor_speed = 1500 + (0.5 * IMU_pitch_adjustment);
} else
{
front_left_vertical_motor_speed = 1500;
front_right_vertical_motor_speed = 1500;
}
if ( current_roll > 30 || current_roll < -30)
{
front_left_vertical_motor_speed = front_left_vertical_motor_speed - IMU_roll_adjustment;
front_right_vertical_motor_speed = front_right_vertical_motor_speed + IMU_roll_adjustment;
}
}
else if ( commands[2] == 127 && commands[3] != 127)
{
if ( current_roll > 30 || current_roll < -30)
{
front_left_vertical_motor_speed = 1500 + (0.5 * pitch_speed) - IMU_roll_adjustment;
front_right_vertical_motor_speed = 1500 + (0.5 * pitch_speed) + IMU_roll_adjustment;
} else
{
front_left_vertical_motor_speed = 1500 + (0.5 * pitch_speed);
front_right_vertical_motor_speed = 1500 + (0.5 * pitch_speed);
}
}
else if ( commands[2] != 127 && commands[3] == 127)
{
if ( current_pitch > 15 || current_pitch < -15)
{
front_left_vertical_motor_speed = 1500 + (0.5 * IMU_pitch_adjustment) + roll_speed;
front_right_vertical_motor_speed = 1500 + (0.5 * IMU_pitch_adjustment) - roll_speed;
} else
{
front_left_vertical_motor_speed = 1500 + roll_speed;
front_right_vertical_motor_speed = 1500 - roll_speed;
}
}
front_left_vertical_motor_speed = front_left_vertical_motor_speed + z_speed;
front_right_vertical_motor_speed = front_right_vertical_motor_speed + z_speed;
if (commands[3] != 127)
{
rear_vertical_motor_speed = 1500 - pitch_speed + z_speed;
}
else if (current_pitch > 30 || current_pitch < -30)
{
rear_vertical_motor_speed = 1500 - IMU_pitch_adjustment + z_speed;
}
else
{
rear_vertical_motor_speed = 1500 + z_speed;
}
left_axial_motor_speed = constrain(left_axial_motor_speed, 1250, 1750);
right_axial_motor_speed = constrain(right_axial_motor_speed, 1250, 1750);
strafing_motor_speed = constrain(strafing_motor_speed, 1250, 1750);
front_left_vertical_motor_speed = constrain(front_left_vertical_motor_speed, 1250, 1750);
front_right_vertical_motor_speed = constrain(front_right_vertical_motor_speed, 1250, 1750);
rear_vertical_motor_speed = constrain(rear_vertical_motor_speed, 1250, 1750);
left_axial_motor.writeMicroseconds(left_axial_motor_speed);
right_axial_motor.writeMicroseconds(right_axial_motor_speed);
strafing_motor.writeMicroseconds(strafing_motor_speed);
front_left_vertical_motor.writeMicroseconds(front_left_vertical_motor_speed);
front_right_vertical_motor.writeMicroseconds(front_right_vertical_motor_speed);
rear_vertical_motor.writeMicroseconds(rear_vertical_motor_speed);
}
else
{
left_axial_motor_speed = 1500;
right_axial_motor_speed = 1500;
strafing_motor_speed = 1500;
front_left_vertical_motor_speed = 1500;
front_right_vertical_motor_speed = 1500;
rear_vertical_motor_speed = 1500;
left_axial_motor.writeMicroseconds(left_axial_motor_speed);
right_axial_motor.writeMicroseconds(right_axial_motor_speed);
strafing_motor.writeMicroseconds(strafing_motor_speed);
front_left_vertical_motor.writeMicroseconds(front_left_vertical_motor_speed);
front_right_vertical_motor.writeMicroseconds(front_right_vertical_motor_speed);
rear_vertical_motor.writeMicroseconds(rear_vertical_motor_speed);
}
}
/****************************************************************
End Motor Module
****************************************************************/
/****************************************************************
ESCArm module
This function arms the ESCs
****************************************************************/
void ESCArm()
{
#if MONITOR == 1
Serial.println("Arming ESC...");
#endif
left_axial_motor_speed = 1500;
right_axial_motor_speed = 1500;
strafing_motor_speed = 1500;
front_left_vertical_motor_speed = 1500;
front_right_vertical_motor_speed = 1500;
rear_vertical_motor_speed = 1500;
left_axial_motor.writeMicroseconds(left_axial_motor_speed);
right_axial_motor.writeMicroseconds(right_axial_motor_speed);
strafing_motor.writeMicroseconds(strafing_motor_speed);
front_left_vertical_motor.writeMicroseconds(front_left_vertical_motor_speed);
front_right_vertical_motor.writeMicroseconds(front_right_vertical_motor_speed);
rear_vertical_motor.writeMicroseconds(rear_vertical_motor_speed);
delay(20);
#if MONITOR == 1
Serial.println("Armed");
#endif
armed = true;
}
/****************************************************************
End Motor Module
****************************************************************/
/****************************************************************
Stop module
This function disarms the ESCs
****************************************************************/
void Stop()
{
#if MONITOR == 1
Serial.println("Stopping");
#endif
left_axial_motor_speed = 1500;
right_axial_motor_speed = 1500;
strafing_motor_speed = 1500;
front_left_vertical_motor_speed = 1500;
front_right_vertical_motor_speed = 1500;
rear_vertical_motor_speed = 1500;
left_axial_motor.writeMicroseconds(left_axial_motor_speed);
right_axial_motor.writeMicroseconds(right_axial_motor_speed);
strafing_motor.writeMicroseconds(strafing_motor_speed);
front_left_vertical_motor.writeMicroseconds(front_left_vertical_motor_speed);
front_right_vertical_motor.writeMicroseconds(front_right_vertical_motor_speed);
rear_vertical_motor.writeMicroseconds(rear_vertical_motor_speed);
delay(20);
#if MONITOR == 1
Serial.println("Stopped.");
#endif
armed = false;
}
/****************************************************************
End Stop Module
****************************************************************/
/****************************************************************
Serial Event Module
Used to implement polling between the MEGA and the IMU
****************************************************************/
void serialEvent1()
{
new_IMU_data_present = true;
}
/****************************************************************
End Serial Event Module
****************************************************************/
/****************************************************************
User Interface Interrupt
Used to allow the user to drive the system
****************************************************************/
void serialEvent()
{
new_commands_present = true;
}
/****************************************************************
End Serial Event Module
****************************************************************/
/****************************************************************
Battery Voltage Monitoring Module
Used to ensure the battery does not fall below a damaging
charge level
INPUT: Charge threshold to check against
OUTPUT: Boolean that is true if battery is in danger
****************************************************************/
boolean check_battery_voltage(float threshold)
{
/***************
This function requires voltage dividers!
Make sure that the threashold is a float!!!
This function requires A0
****************/
// read the input on batt_pin (analog 0):
int cell_1_raw = analogRead(batt_pin);
// Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
float cell_1_voltage = ((float)cell_1_raw / 1023.0 ) * 4.98;
// total voltage is divided by 3 in order to check raw value
// multiplying by 3 reports the total voltage
total_voltage = cell_1_voltage * 3.0;
// print out the value you
return total_voltage <= threshold;
}
/****************************************************************
End Battery Checking Module
****************************************************************/
/****************************************************************
Internal Temp and Humidity Sensor Module
Used to report the Sub internal air temp and humidity
****************************************************************/
void dht22()
{
DHT22_ERROR_t errorCode;
errorCode = myDHT22.readData();
switch(errorCode)
{
case DHT_ERROR_NONE:
// put values into float variables so they can be communicated to UI
internal_temp = myDHT22.getTemperatureC();
internal_humidity = myDHT22.getHumidity();
if ( internal_humidity >= 90)
{
water_leak = true;
}
else {
water_leak = false;
}
break;
default:
break;
}
}
/****************************************************************
End Internal Temp and Humidity Sensor Module
****************************************************************/
/****************************************************************
External Temp Sensor Module
Used to report the external water temperature
****************************************************************/
float get_water_temp()
{
uint8_t i;
float average;
// take N samples in a row, with a slight delay
for (i=0; i< NUMSAMPLES; i++)
{
samples[i] = analogRead(THERMISTORPIN);
delay(5);
}
// average all the samples out
average = 0;
for (i=0; i< NUMSAMPLES; i++)
{
average += samples[i];
}
average /= NUMSAMPLES;
// convert the value to resistance
average = 1023 / average - 1;
average = SERIESRESISTOR / average;
float temperature;
temperature = average / THERMISTORNOMINAL; // (R/Ro)
temperature = log(temperature); // ln(R/Ro)
temperature /= BCOEFFICIENT; // 1/B * ln(R/Ro)
temperature += 1.0 / (TEMPERATURENOMINAL + 273.15); // + (1/To)
temperature = 1.0 / temperature; // Invert
temperature -= 273.15; // convert to C
return temperature;
}
/****************************************************************
End External Temp Sensor Module
****************************************************************/
/****************************************************************
Water Depth Detection Module
****************************************************************/
float get_depth()
{
/* depth is calculated by dividing the analog read value by 1023 which is
the resolution of the Arduino, multiplying by 0.004 and adding 10 are
parts of the transfer function given in the sensor data sheet. The last
number is a conversion factor for feet per units of pressure. This can
be selected as fresh or salt water by the user */
float depth = (((float)analogRead(A2) / (1023.0 * 0.004) + 10)) / depth_conversion;
return depth;
}
/****************************************************************
End Water Depth Detection Module
****************************************************************/
/****************************************************************
New Commands Module
Used to read new command packets from the user
****************************************************************/
void new_commands() {
if( new_commands_present && !returning_to_surface)
{
new_commands_present = false;
byte length = Serial.read();
if (length == 8)
{
for( int i = 0; i < length; i++)
{
while( Serial.available() < 1)
{
}
commands[i] = Serial.read();
}
if (!armed)
{
commands[2] = 127;
commands[3] = 127;
commands[4] = 127;
commands[5] = 127;
commands[6] = 127;
commands[7] = 127;
}
if (commands[1] == 1 && commands[0] == 0 && !armed && !water_leak) //If user wants it to arm, and there are no errors, and its not already armed
{
ESCArm();
} else if (commands[1] == 0 && !water_leak ) //if the user wants it to disarm
{
Stop();
} else if ( commands[0] == 1 || water_leak) //if there are errors
{
if(!armed) ESCArm();
//return_to_surface();
}
}
}
}
/****************************************************************
End New Commands Module
****************************************************************/
/****************************************************************
Send New Data Module
Used to send new data packets to user
****************************************************************/
void send_data()
{
float data_to_user[8];
data_to_user[0] = parsed_IMU_data[0];
data_to_user[1] = parsed_IMU_data[1];
data_to_user[2] = parsed_IMU_data[2];
data_to_user[3] = water_temp;
data_to_user[4] = internal_temp;
data_to_user[5] = internal_humidity;
data_to_user[6] = water_depth;
data_to_user[7] = total_voltage;
Serial.print("$$$");
Serial.print(data_to_user[0]);
Serial.print(',');
Serial.print(data_to_user[1]);
Serial.print(',');
Serial.print(data_to_user[2]);
Serial.print(',');
Serial.print(data_to_user[3]);
Serial.print(',');
Serial.print(data_to_user[4]);
Serial.print(',');
Serial.print(data_to_user[5]);
Serial.print(',');
Serial.print(data_to_user[6]);
Serial.print(',');
Serial.print(data_to_user[7]);
Serial.print('#');
}
/****************************************************************
End Send New Data Module
****************************************************************/
/****************************************************************
New IMU Data Receiving Module
Used to manage incoming IMU data
****************************************************************/
void new_IMU_data_received()
{
if( new_IMU_data_present)
{
new_IMU_data_present = false;
String valid_chars = ".,:-1234567890";
if( IMU_input_string.length() == 0)
{
char in_char;
do
{
in_char = Serial1.read();
} while( in_char != '!');
while( in_char != '*')
{
in_char = Serial1.read();
for( int i = 0; i < valid_chars.length(); i++)
{
if( in_char == valid_chars[i])
{
IMU_input_string += in_char;
break;
}
}
if( in_char == '!')
{
break;
}
}
}
}
}
/****************************************************************
End New IMU Data Receiving Module
****************************************************************/
/****************************************************************
Return to Surface Module
Used to bring the Sub to the surface in case of emergency
****************************************************************/
void return_to_surface()
{
returning_to_surface = true;
left_axial_motor.writeMicroseconds(1500);
right_axial_motor.writeMicroseconds(1500);
strafing_motor.writeMicroseconds(1500);
front_left_vertical_motor.writeMicroseconds(1625);
front_right_vertical_motor.writeMicroseconds(1625);
rear_vertical_motor.writeMicroseconds(1750);
}
/****************************************************************
End Return to Surface Module
****************************************************************/
| [
"[email protected]"
]
| |
282707e74ab40c0b4ed62ea83e553331f6054b34 | 68fc47bcf985b2b2c352f98b513aa0110d1d668a | /Plante.cpp | 988d47077deef4b66f8fb2a658f681fa7d0feef8 | []
| no_license | ValentinPIVOT-LEMEEetpa/GDA_Botanique_PIVOT-LEMEE | 8325c68959a00917487851217ca1cd3a772f8936 | a7aae521b042bf8fd41a488232937f15d46537b1 | refs/heads/master | 2022-07-04T10:52:53.416014 | 2020-05-11T15:54:55 | 2020-05-11T15:54:55 | 262,794,200 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 967 | cpp | #ifndef PLANTE_CPP
#define PLANTE_CPP
#include <iostream>
#include "Plante.h"
#include "Vege.h"
void Plante::maturite(){
_mature += 1;
_arrosage -=10;
_taille +=1;
if(_mature > 20) //mort
}
void Plante::angrais(){
_angrais -= 1;
if(_angrais <0) _angrais = 0;
_mature -= 1;
_taille += 1;
}
void Plante::pousse(int eau){
eau += 2;
if( eau >10) _mature -= 1;
}
void Plante::coupe(int _taille);{
_taille -= 2;
if(_taille >4 && _taille < 8) _mature -=1;
}
void Plante::afficher(){
std::cout << _nom <<" est une plante de type plante. Sa maturité est de "
<<_mature<<"/20, son niveau d'eau est de " <<_arrosage<<"/10, sa taille est de "
<<_taille<<" ,si elle est en dessous de 4 il faut la nourrire, si elle est au dessus de 8 il faut la tailler"<< std::endl;
if(_mature<0) _mature = 0;
} | [
"[email protected]"
]
| |
475ac29011d51482155bbadf13bd5a4ae59ababf | c44e52880af2528055441630fe3850bea2cb4c37 | /C++/uva10300.cpp | b0d37017a5ee0dfc2ac5f245705df9590abb0325 | [
"MIT"
]
| permissive | MrinmoiHossain/Uva-Solution | f89df917eb608243e621f43f3e8e9ec9b6c69c76 | 85602085b7c8e1d4711e679b8f5636678459b2c5 | refs/heads/master | 2021-01-19T19:39:40.880868 | 2018-12-28T17:26:15 | 2018-12-28T17:26:15 | 88,434,419 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 366 | cpp | #include <bits/stdc++.h>
using namespace std;
#define LL long long int
int main(void)
{
int n;
cin >> n;
int f;
for(int i = 0; i < n; i++){
cin >> f;
LL con = 0, a, b, c;
for(int j = 0; j < f; j++){
cin >> a >> b >> c;
con += (a * c);
}
cout << con << endl;
}
return 0;
}
| [
"[email protected]"
]
| |
f99dd6ae8dc68069881fb1fe204ea1e79a0554bc | d0fb46aecc3b69983e7f6244331a81dff42d9595 | /servicemesh/src/model/CreateServiceMeshRequest.cc | 690f7ddb49cd6f8e9cc8eb3746bf00f6c641c29f | [
"Apache-2.0"
]
| permissive | aliyun/aliyun-openapi-cpp-sdk | 3d8d051d44ad00753a429817dd03957614c0c66a | e862bd03c844bcb7ccaa90571bceaa2802c7f135 | refs/heads/master | 2023-08-29T11:54:00.525102 | 2023-08-29T03:32:48 | 2023-08-29T03:32:48 | 115,379,460 | 104 | 82 | NOASSERTION | 2023-09-14T06:13:33 | 2017-12-26T02:53:27 | C++ | UTF-8 | C++ | false | false | 11,634 | cc | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/servicemesh/model/CreateServiceMeshRequest.h>
using AlibabaCloud::Servicemesh::Model::CreateServiceMeshRequest;
CreateServiceMeshRequest::CreateServiceMeshRequest() :
RpcServiceRequest("servicemesh", "2020-01-11", "CreateServiceMesh")
{
setMethod(HttpRequest::Method::Post);
}
CreateServiceMeshRequest::~CreateServiceMeshRequest()
{}
std::string CreateServiceMeshRequest::getProxyRequestCPU()const
{
return proxyRequestCPU_;
}
void CreateServiceMeshRequest::setProxyRequestCPU(const std::string& proxyRequestCPU)
{
proxyRequestCPU_ = proxyRequestCPU;
setBodyParameter("ProxyRequestCPU", proxyRequestCPU);
}
std::string CreateServiceMeshRequest::getOPALimitCPU()const
{
return oPALimitCPU_;
}
void CreateServiceMeshRequest::setOPALimitCPU(const std::string& oPALimitCPU)
{
oPALimitCPU_ = oPALimitCPU;
setBodyParameter("OPALimitCPU", oPALimitCPU);
}
bool CreateServiceMeshRequest::getOpenAgentPolicy()const
{
return openAgentPolicy_;
}
void CreateServiceMeshRequest::setOpenAgentPolicy(bool openAgentPolicy)
{
openAgentPolicy_ = openAgentPolicy;
setBodyParameter("OpenAgentPolicy", openAgentPolicy ? "true" : "false");
}
bool CreateServiceMeshRequest::getOpaEnabled()const
{
return opaEnabled_;
}
void CreateServiceMeshRequest::setOpaEnabled(bool opaEnabled)
{
opaEnabled_ = opaEnabled;
setBodyParameter("OpaEnabled", opaEnabled ? "true" : "false");
}
std::string CreateServiceMeshRequest::getProxyLimitMemory()const
{
return proxyLimitMemory_;
}
void CreateServiceMeshRequest::setProxyLimitMemory(const std::string& proxyLimitMemory)
{
proxyLimitMemory_ = proxyLimitMemory;
setBodyParameter("ProxyLimitMemory", proxyLimitMemory);
}
bool CreateServiceMeshRequest::getCustomizedPrometheus()const
{
return customizedPrometheus_;
}
void CreateServiceMeshRequest::setCustomizedPrometheus(bool customizedPrometheus)
{
customizedPrometheus_ = customizedPrometheus;
setBodyParameter("CustomizedPrometheus", customizedPrometheus ? "true" : "false");
}
bool CreateServiceMeshRequest::getStrictMTLS()const
{
return strictMTLS_;
}
void CreateServiceMeshRequest::setStrictMTLS(bool strictMTLS)
{
strictMTLS_ = strictMTLS;
setBodyParameter("StrictMTLS", strictMTLS ? "true" : "false");
}
bool CreateServiceMeshRequest::getAccessLogEnabled()const
{
return accessLogEnabled_;
}
void CreateServiceMeshRequest::setAccessLogEnabled(bool accessLogEnabled)
{
accessLogEnabled_ = accessLogEnabled;
setBodyParameter("AccessLogEnabled", accessLogEnabled ? "true" : "false");
}
std::string CreateServiceMeshRequest::getOPALogLevel()const
{
return oPALogLevel_;
}
void CreateServiceMeshRequest::setOPALogLevel(const std::string& oPALogLevel)
{
oPALogLevel_ = oPALogLevel;
setBodyParameter("OPALogLevel", oPALogLevel);
}
std::string CreateServiceMeshRequest::getExcludeIPRanges()const
{
return excludeIPRanges_;
}
void CreateServiceMeshRequest::setExcludeIPRanges(const std::string& excludeIPRanges)
{
excludeIPRanges_ = excludeIPRanges;
setBodyParameter("ExcludeIPRanges", excludeIPRanges);
}
std::string CreateServiceMeshRequest::getIstioVersion()const
{
return istioVersion_;
}
void CreateServiceMeshRequest::setIstioVersion(const std::string& istioVersion)
{
istioVersion_ = istioVersion;
setBodyParameter("IstioVersion", istioVersion);
}
bool CreateServiceMeshRequest::getTracing()const
{
return tracing_;
}
void CreateServiceMeshRequest::setTracing(bool tracing)
{
tracing_ = tracing;
setBodyParameter("Tracing", tracing ? "true" : "false");
}
std::string CreateServiceMeshRequest::getIncludeIPRanges()const
{
return includeIPRanges_;
}
void CreateServiceMeshRequest::setIncludeIPRanges(const std::string& includeIPRanges)
{
includeIPRanges_ = includeIPRanges;
setBodyParameter("IncludeIPRanges", includeIPRanges);
}
std::string CreateServiceMeshRequest::getExcludeInboundPorts()const
{
return excludeInboundPorts_;
}
void CreateServiceMeshRequest::setExcludeInboundPorts(const std::string& excludeInboundPorts)
{
excludeInboundPorts_ = excludeInboundPorts;
setBodyParameter("ExcludeInboundPorts", excludeInboundPorts);
}
std::string CreateServiceMeshRequest::getOPALimitMemory()const
{
return oPALimitMemory_;
}
void CreateServiceMeshRequest::setOPALimitMemory(const std::string& oPALimitMemory)
{
oPALimitMemory_ = oPALimitMemory;
setBodyParameter("OPALimitMemory", oPALimitMemory);
}
std::string CreateServiceMeshRequest::getPrometheusUrl()const
{
return prometheusUrl_;
}
void CreateServiceMeshRequest::setPrometheusUrl(const std::string& prometheusUrl)
{
prometheusUrl_ = prometheusUrl;
setBodyParameter("PrometheusUrl", prometheusUrl);
}
std::string CreateServiceMeshRequest::getVSwitches()const
{
return vSwitches_;
}
void CreateServiceMeshRequest::setVSwitches(const std::string& vSwitches)
{
vSwitches_ = vSwitches;
setBodyParameter("VSwitches", vSwitches);
}
bool CreateServiceMeshRequest::getCADisableSecretAutoGeneration()const
{
return cADisableSecretAutoGeneration_;
}
void CreateServiceMeshRequest::setCADisableSecretAutoGeneration(bool cADisableSecretAutoGeneration)
{
cADisableSecretAutoGeneration_ = cADisableSecretAutoGeneration;
setBodyParameter("CADisableSecretAutoGeneration", cADisableSecretAutoGeneration ? "true" : "false");
}
std::string CreateServiceMeshRequest::getCAListenedNamespaces()const
{
return cAListenedNamespaces_;
}
void CreateServiceMeshRequest::setCAListenedNamespaces(const std::string& cAListenedNamespaces)
{
cAListenedNamespaces_ = cAListenedNamespaces;
setBodyParameter("CAListenedNamespaces", cAListenedNamespaces);
}
std::string CreateServiceMeshRequest::getProxyLimitCPU()const
{
return proxyLimitCPU_;
}
void CreateServiceMeshRequest::setProxyLimitCPU(const std::string& proxyLimitCPU)
{
proxyLimitCPU_ = proxyLimitCPU;
setBodyParameter("ProxyLimitCPU", proxyLimitCPU);
}
std::string CreateServiceMeshRequest::getProxyRequestMemory()const
{
return proxyRequestMemory_;
}
void CreateServiceMeshRequest::setProxyRequestMemory(const std::string& proxyRequestMemory)
{
proxyRequestMemory_ = proxyRequestMemory;
setBodyParameter("ProxyRequestMemory", proxyRequestMemory);
}
std::string CreateServiceMeshRequest::getName()const
{
return name_;
}
void CreateServiceMeshRequest::setName(const std::string& name)
{
name_ = name;
setBodyParameter("Name", name);
}
bool CreateServiceMeshRequest::getTelemetry()const
{
return telemetry_;
}
void CreateServiceMeshRequest::setTelemetry(bool telemetry)
{
telemetry_ = telemetry;
setBodyParameter("Telemetry", telemetry ? "true" : "false");
}
std::string CreateServiceMeshRequest::getOPARequestCPU()const
{
return oPARequestCPU_;
}
void CreateServiceMeshRequest::setOPARequestCPU(const std::string& oPARequestCPU)
{
oPARequestCPU_ = oPARequestCPU;
setBodyParameter("OPARequestCPU", oPARequestCPU);
}
std::string CreateServiceMeshRequest::getOPARequestMemory()const
{
return oPARequestMemory_;
}
void CreateServiceMeshRequest::setOPARequestMemory(const std::string& oPARequestMemory)
{
oPARequestMemory_ = oPARequestMemory;
setBodyParameter("OPARequestMemory", oPARequestMemory);
}
bool CreateServiceMeshRequest::getEnableAudit()const
{
return enableAudit_;
}
void CreateServiceMeshRequest::setEnableAudit(bool enableAudit)
{
enableAudit_ = enableAudit;
setBodyParameter("EnableAudit", enableAudit ? "true" : "false");
}
std::string CreateServiceMeshRequest::getClusterDomain()const
{
return clusterDomain_;
}
void CreateServiceMeshRequest::setClusterDomain(const std::string& clusterDomain)
{
clusterDomain_ = clusterDomain;
setBodyParameter("ClusterDomain", clusterDomain);
}
std::string CreateServiceMeshRequest::getRegionId()const
{
return regionId_;
}
void CreateServiceMeshRequest::setRegionId(const std::string& regionId)
{
regionId_ = regionId;
setBodyParameter("RegionId", regionId);
}
bool CreateServiceMeshRequest::getLocalityLoadBalancing()const
{
return localityLoadBalancing_;
}
void CreateServiceMeshRequest::setLocalityLoadBalancing(bool localityLoadBalancing)
{
localityLoadBalancing_ = localityLoadBalancing;
setBodyParameter("LocalityLoadBalancing", localityLoadBalancing ? "true" : "false");
}
bool CreateServiceMeshRequest::getApiServerPublicEip()const
{
return apiServerPublicEip_;
}
void CreateServiceMeshRequest::setApiServerPublicEip(bool apiServerPublicEip)
{
apiServerPublicEip_ = apiServerPublicEip;
setBodyParameter("ApiServerPublicEip", apiServerPublicEip ? "true" : "false");
}
float CreateServiceMeshRequest::getTraceSampling()const
{
return traceSampling_;
}
void CreateServiceMeshRequest::setTraceSampling(float traceSampling)
{
traceSampling_ = traceSampling;
setBodyParameter("TraceSampling", std::to_string(traceSampling));
}
std::string CreateServiceMeshRequest::getAppNamespaces()const
{
return appNamespaces_;
}
void CreateServiceMeshRequest::setAppNamespaces(const std::string& appNamespaces)
{
appNamespaces_ = appNamespaces;
setBodyParameter("AppNamespaces", appNamespaces);
}
bool CreateServiceMeshRequest::getKialiEnabled()const
{
return kialiEnabled_;
}
void CreateServiceMeshRequest::setKialiEnabled(bool kialiEnabled)
{
kialiEnabled_ = kialiEnabled;
setBodyParameter("KialiEnabled", kialiEnabled ? "true" : "false");
}
bool CreateServiceMeshRequest::getPilotPublicEip()const
{
return pilotPublicEip_;
}
void CreateServiceMeshRequest::setPilotPublicEip(bool pilotPublicEip)
{
pilotPublicEip_ = pilotPublicEip;
setBodyParameter("PilotPublicEip", pilotPublicEip ? "true" : "false");
}
std::string CreateServiceMeshRequest::getAuditProject()const
{
return auditProject_;
}
void CreateServiceMeshRequest::setAuditProject(const std::string& auditProject)
{
auditProject_ = auditProject;
setBodyParameter("AuditProject", auditProject);
}
std::string CreateServiceMeshRequest::getOutboundTrafficPolicy()const
{
return outboundTrafficPolicy_;
}
void CreateServiceMeshRequest::setOutboundTrafficPolicy(const std::string& outboundTrafficPolicy)
{
outboundTrafficPolicy_ = outboundTrafficPolicy;
setBodyParameter("OutboundTrafficPolicy", outboundTrafficPolicy);
}
std::string CreateServiceMeshRequest::getVpcId()const
{
return vpcId_;
}
void CreateServiceMeshRequest::setVpcId(const std::string& vpcId)
{
vpcId_ = vpcId;
setBodyParameter("VpcId", vpcId);
}
std::string CreateServiceMeshRequest::getExcludeOutboundPorts()const
{
return excludeOutboundPorts_;
}
void CreateServiceMeshRequest::setExcludeOutboundPorts(const std::string& excludeOutboundPorts)
{
excludeOutboundPorts_ = excludeOutboundPorts;
setBodyParameter("ExcludeOutboundPorts", excludeOutboundPorts);
}
| [
"[email protected]"
]
| |
a8cba13826d5a717411c4b5d964d9e72f3ede68f | 4bb59a04ce5821980460e0f974419d14626aef5e | /08.TestSet/src/04.UI/Ctrl/XTHtmlCtrl.h | 7e5669e55361aa43339807160d7e16e20de34eca | []
| no_license | xt9852/TestSet | 587d5251e234ffc8fc477426dd9ff4b0cecce1eb | 5d0dcb72ab9867e488ad9bfd437aef782a5abca7 | refs/heads/master | 2021-01-10T01:20:27.906424 | 2016-03-16T09:11:49 | 2016-03-16T09:11:49 | 44,855,424 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 971 | h |
#pragma once
#include "XTRichEdit.h"
#include "afxhtml.h"
//#include <boost/regex.hpp>
//using namespace boost;
enum {FILE_GIF = 1, FILE_JPG, FILE_BMP, FILE_DOC};
class CXTHtmlCtrl : public CHtmlView
{
DECLARE_DYNCREATE(CXTHtmlCtrl)
public:
CXTHtmlCtrl();
virtual ~CXTHtmlCtrl();
HWND m_hParentWnd;
public:
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
protected:
virtual void DoDataExchange(CDataExchange* pDX);
virtual void PostNcDestroy();
DECLARE_MESSAGE_MAP()
afx_msg int OnMouseActivate(CWnd* pDesktopWnd, UINT nHitTest, UINT message);
afx_msg void OnSize(UINT nType, int cx, int cy);
afx_msg void OnDestroy();
public:
BOOL CreateFromCtrl(UINT nID, CWnd* pParent);
BOOL CreateFromCtrl(CRect rcCtrl, CWnd* pParent);
void OnBeforeNavigate2(LPCTSTR lpszURL, DWORD nFlags, LPCTSTR lpszTargetFrameName,
CByteArray& baPostedData, LPCTSTR lpszHeaders, BOOL* pbCancel);
};
| [
"[email protected]"
]
| |
ed073af425c729e876039860c68434bf68c900a3 | d0c8a21694ee0d608248eca851b8da953e6bd29e | /Data/Json/RapidjsonCanvas.cpp | 40ac5f8d3649c4c547f014afdfcc739af7d7e4d3 | []
| no_license | isaacselement/modules-cocos2dx | 80d7247fab6b58e9c6044850b361cd3ad6003f4a | a6e7047a48fcf6f9db50051c412ba2b5f2bbdb71 | refs/heads/master | 2020-12-25T08:42:34.207747 | 2016-08-25T03:43:30 | 2016-08-25T03:43:30 | 65,530,673 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 299 | cpp | #include "RapidjsonCanvas.h"
#include "RapidjsonValues.h"
#include "FrameTranslater.h"
Size RapidjsonCanvas::parseSize(rapidjson::Value &value)
{
return CanvasCGSize(rParseSize(value));
}
Vec2 RapidjsonCanvas::parseVec2(rapidjson::Value &value)
{
return CanvasCGVec2(rParseVec2(value));
} | [
"[email protected]"
]
| |
53f8c4ede4563a12da1e3e66d941802688b38d29 | 6b59be05366f5224549580abd03288b8a72fca4c | /main.cpp | 8ccbdc01e96da001b4540eb750813df91244dc77 | []
| no_license | utec-computer-science/cs3102-btree-bdiaz22 | 2bbd8380ed0fe3c806220c786f1c1d9f869cdcb4 | 7a6359967932e0364a06871cf99bb49f75333d7b | refs/heads/master | 2021-05-25T22:45:05.688760 | 2020-05-08T01:00:44 | 2020-05-08T01:00:44 | 253,952,751 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 733 | cpp | #include <iostream>
#include "Tree.h"
using namespace std;
int main()
{
typedef BNode<float> b_node;
typedef Tree<b_node> b_tree;
b_tree btree(4);
btree.insert(10);
btree.insert(2);
btree.insert(4);
btree.insert(41);
btree.insert(15);
btree.insert(26);
btree.insert(19);
btree.insert(11);
cout << btree.find(10) << endl;
cout << btree.find(2) << endl;
cout << btree.find(4) << endl;
cout << btree.find(41) << endl;
cout << btree.find(15) << endl;
cout << btree.find(26) << endl;
cout << btree.find(19) << endl;
cout << btree.find(11) << endl;
cout << btree.find(22) << endl;
cout << btree.find(10.2) << endl;
cout << btree.find(0) << endl;
cout << btree << endl;
return 0;
} | [
"[email protected]"
]
| |
709737b2aecaef4e0c65eb289d947bdcd2497620 | 133d0f38b3da2c51bf52bcdfa11d62978b94d031 | /testAutocad/vendor/ifc-sdk/include/ifc2x3/IfcRelDecomposes.h | c5674323e8aaf909d3393555b4cd9add8741725f | []
| no_license | Aligon42/ImportIFC | 850404f1e1addf848e976b0351d9e217a72f868a | 594001fc0942d356eb0d0472c959195151510493 | refs/heads/master | 2023-08-15T08:00:14.056542 | 2021-07-05T13:49:28 | 2021-07-05T13:49:28 | 361,410,709 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 6,090 | h | // IFC SDK : IFC2X3 C++ Early Classes
// Copyright (C) 2009 CSTB
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// The full license is in Licence.txt file included with this
// distribution or is available at :
// http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
#ifndef IFC2X3_IFCRELDECOMPOSES_H
#define IFC2X3_IFCRELDECOMPOSES_H
#include <ifc2x3/DefinedTypes.h>
#include <ifc2x3/Export.h>
#include <ifc2x3/IfcRelationship.h>
#include <Step/BaseVisitor.h>
#include <Step/ClassType.h>
#include <Step/Referenced.h>
#include <Step/SPFData.h>
#include <stdexcept>
#include <string>
namespace ifc2x3 {
class IfcObjectDefinition;
class IfcRelDecomposes;
/**
* Inverse aggregate helper that keeps track of the owner for inverse operations.
*
*/
class Inverted_IfcRelDecomposes_RelatedObjects_type : public Set_IfcObjectDefinition_1_n {
public:
/**
*/
typedef Set_IfcObjectDefinition_1_n::size_type size_type;
/**
*/
Inverted_IfcRelDecomposes_RelatedObjects_type();
/**
* Insert a value in the aggregate.
*
* @param value The object to act upon.
*/
virtual void insert(const Step::RefPtr< IfcObjectDefinition > &value) throw(std::out_of_range);
/**
* Remove a value from the aggregate.
*
* @param value The object to act upon.
*/
virtual size_type erase(const Step::RefPtr< IfcObjectDefinition > &value);
/**
* Remove all values from the aggregate.
*
*/
void clear();
friend class IfcRelDecomposes;
protected:
/**
* The owner of this inverted aggregate.
*
*/
IfcRelDecomposes *mOwner;
/**
* @param owner The owner of this inverted aggregate.
*/
void setOwner(IfcRelDecomposes *owner);
};
class CopyOp;
/**
* Generated class for the IfcRelDecomposes Entity.
*
*/
class IFC2X3_EXPORT IfcRelDecomposes : public IfcRelationship {
public:
/**
* Accepts a read/write Step::BaseVisitor.
*
* @param visitor the read/write Step::BaseVisitor to accept
*/
virtual bool acceptVisitor(Step::BaseVisitor *visitor);
/**
* Returns the class type as a human readable std::string.
*
*/
virtual const std::string &type() const;
/**
* Returns the Step::ClassType of this specific class. Useful to compare with the isOfType method for example.
*
*/
static const Step::ClassType &getClassType();
/**
* Returns the Step::ClassType of the instance of this class. (might be a subtype since it is virtual and overloaded).
*
*/
virtual const Step::ClassType &getType() const;
/**
* Compares this instance's Step::ClassType with the one passed as parameter. Checks the type recursively (to the mother classes).
*
* @param t
*/
virtual bool isOfType(const Step::ClassType &t) const;
/**
* Gets the value of the explicit attribute 'RelatingObject'.
*
*/
virtual IfcObjectDefinition *getRelatingObject();
/**
* (const) Returns the value of the explicit attribute 'RelatingObject'.
*
* @return the value of the explicit attribute 'RelatingObject'
*/
virtual const IfcObjectDefinition *getRelatingObject() const;
/**
* Sets the value of the explicit attribute 'RelatingObject'.
*
* @param value
*/
virtual void setRelatingObject(const Step::RefPtr< IfcObjectDefinition > &value);
/**
* unset the attribute 'RelatingObject'.
*
*/
virtual void unsetRelatingObject();
/**
* Test if the attribute 'RelatingObject' is set.
*
* @return true if set, false if unset
*/
virtual bool testRelatingObject() const;
/**
* Gets the value of the explicit attribute 'RelatedObjects'.
*
*/
virtual Set_IfcObjectDefinition_1_n &getRelatedObjects();
/**
* (const) Returns the value of the explicit attribute 'RelatedObjects'.
*
* @return the value of the explicit attribute 'RelatedObjects'
*/
virtual const Set_IfcObjectDefinition_1_n &getRelatedObjects() const;
/**
* unset the attribute 'RelatedObjects'.
*
*/
virtual void unsetRelatedObjects();
/**
* Test if the attribute 'RelatedObjects' is set.
*
* @return true if set, false if unset
*/
virtual bool testRelatedObjects() const;
friend class ExpressDataSet;
protected:
/**
* @param id
* @param args
*/
IfcRelDecomposes(Step::Id id, Step::SPFData *args);
virtual ~IfcRelDecomposes();
/**
*/
virtual bool init();
/**
* @param obj
* @param copyop
*/
virtual void copy(const IfcRelDecomposes &obj, const CopyOp ©op);
private:
/**
*/
static Step::ClassType s_type;
/**
*/
Step::RefPtr< IfcObjectDefinition > m_relatingObject;
/**
*/
Inverted_IfcRelDecomposes_RelatedObjects_type m_relatedObjects;
};
}
#endif // IFC2X3_IFCRELDECOMPOSES_H
| [
"[email protected]"
]
| |
d58a58ae09b4b5019222526ff697af4cdcfba0c6 | 83bda3089c314c3e25e621b4190ce5ff3496b5c9 | /Refactoring_StudyServer/GameProtocol.cpp | ce750512d763f84e8fd593c4cb1ff63e1118403f | []
| no_license | CodeByKim/GunShootingGame-Server | ed09ac44507f013d7a5547bcd4ab27fcab1cc439 | d7b96f1181dbc8f3eab416ff4538b870281bc33b | refs/heads/master | 2020-04-04T10:45:41.789722 | 2018-11-03T15:48:58 | 2018-11-03T15:48:58 | 155,849,917 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 20,300 | cpp | #include "Protocol.h"
#include "UserDB.h"
#include "Player.h"
#include "PlayerManager.h"
#include "Lobby.h"
#include "Utils.h"
#include "Network.h"
#include "GamePacketData.h"
#include "TestPacketData.h"
#include "PacketFactory.h"
#include "Game.h"
#include "GameManager.h"
VOID HEART_BEAT(Player* player, TcpPacket* packet)
{
player->GetNetworkSession()->CheckHeartBeat();
Utils::GetInstance()->LogSucc(L"HEART BEAT", L"하트비트 체크");
}
VOID GAME_START(Player* player, TcpPacket* packet)
{
CLIENTtoSERVER_GameStartPacketData clientToServerData;
clientToServerData.Deserialize(packet);
if (PlayerManager::GetInstance()->FindPlayer(clientToServerData.playerKey))
{
Game* game = GameManager::GetInstance()->FindGame(clientToServerData.gameKey);
if (game != NULL)
{
GamePlayer* gamePlayer = PlayerManager::GetInstance()->GetGamePlayer(player);
gamePlayer->CompleteLoading();
if (game->IsAllPlayerCompleteLoading())
{
Utils::GetInstance()->LogSucc(L"GAME START", L"모든 플레이어의 로딩이 끝남, 게임 시작");
vector<Package*> gamePackages;
vector<GamePlayer*>& gamePlayers = game->GetPlayers();
vector<Package*> lobbyPackages;
vector<Player*>& lobbyPlayers = Lobby::GetInstance()->GetPlayers();
SERVERtoCLIENT_GameStartPacketData broadcastData;
SERVERtoCLIENT_OtherGameStartPacketData otherGameStartData;
Room* room = game->GetReturnRoom();
otherGameStartData.WriteData(room->GetName(), room->GetRoomID());
for (INT i = 0; i < (INT)gamePlayers.size(); i++)
{
TcpPacket* packet = PacketFactory::GetInstance()->GetPacketPool()->Pop();
broadcastData.Serialize(packet, PROTOCOL::GAME_START, EXTRA::SUCCESS);
Package* package = new Package();
package->packet = packet;
package->player = gamePlayers[i]->GetPlayer();
gamePackages.push_back(package);
}
for (INT i = 0; i < (INT)lobbyPlayers.size(); i++)
{
TcpPacket* packet = PacketFactory::GetInstance()->GetPacketPool()->Pop();
otherGameStartData.Serialize(packet, PROTOCOL::OTHER_GAME_START, EXTRA::SUCCESS);
Package* package = new Package();
package->packet = packet;
package->player = lobbyPlayers[i];
lobbyPackages.push_back(package);
}
Network::GetInstance()->BroadCastPacket(gamePackages);
Network::GetInstance()->BroadCastPacket(lobbyPackages);
}
}
}
}
VOID GAME_END(Player* player, TcpPacket* packet)
{
CLIENTtoSERVER_GameEndPacketData clientToServerData;
clientToServerData.Deserialize(packet);
if (PlayerManager::GetInstance()->FindPlayer(clientToServerData.playerKey))
{
Game* game = GameManager::GetInstance()->FindGame(clientToServerData.gameKey);
if (game != NULL)
{
GameManager::GetInstance()->RemoveGame(game);
GamePlayer* gamePlayer = PlayerManager::GetInstance()->GetGamePlayer(player);
vector<GamePlayer*>& players = game->GetPlayers();
for (INT i = 0; i < (INT)players.size(); i++)
PlayerManager::GetInstance()->RemoveGamePlayer(players[i]->GetPlayer());
Room* room = game->GetReturnRoom();
room->EndGame();
Utils::GetInstance()->LogSucc(L"GAME END", L"게임 종료");
vector<Package*> gamePackages;
vector<GamePlayer*>& gamePlayers = game->GetPlayers();
vector<Package*> lobbyPackages;
vector<Player*>& lobbyPlayers = Lobby::GetInstance()->GetPlayers();
SERVERtoCLIENT_GameEndPacketData serverToClientData;
serverToClientData.WriteData(room->GetName(), room->GetRoomID(), room->GetJoinedPlayerCount(), room->GetJoinedPlayers());
SERVERtoCLIENT_OtherGameEndPacketData otherGameEndData;
otherGameEndData.WriteData(room->GetName(), room->GetRoomID());
for (INT i = 0; i < (INT)gamePlayers.size(); i++)
{
TcpPacket* packet = PacketFactory::GetInstance()->GetPacketPool()->Pop();
serverToClientData.Serialize(packet, PROTOCOL::GAME_END, EXTRA::SUCCESS);
Package* package = new Package();
package->packet = packet;
package->player = gamePlayers[i]->GetPlayer();
gamePackages.push_back(package);
}
for (INT i = 0; i < (INT)lobbyPlayers.size(); i++)
{
TcpPacket* packet = PacketFactory::GetInstance()->GetPacketPool()->Pop();
otherGameEndData.Serialize(packet, PROTOCOL::OTHER_GAME_END, EXTRA::SUCCESS);
Package* package = new Package();
package->packet = packet;
package->player = lobbyPlayers[i];
lobbyPackages.push_back(package);
}
Network::GetInstance()->BroadCastPacket(gamePackages);
Network::GetInstance()->BroadCastPacket(lobbyPackages);
}
}
}
VOID GAME_PLAYER_MOVE(Player* player, TcpPacket* packet)
{
if (packet->header.extra == (INT)EXTRA::CLIENT_TO_SERVER)
{
CLIENTtoSERVER_GamePlayerMovePacketData clientToServerData;
clientToServerData.Deserialize(packet);
if (PlayerManager::GetInstance()->FindPlayer(clientToServerData.playerKey))
{
Game* game = GameManager::GetInstance()->FindGame(clientToServerData.gameKey);
if (game != NULL)
{
GamePlayer* gamePlayer = PlayerManager::GetInstance()->GetGamePlayer(player);
GamePlayer* leader = game->GetLeader();
TcpPacket* sendPacket = PacketFactory::GetInstance()->GetPacketPool()->Pop();
SERVERtoHOST_GamePlayerMovePacketData serverToHostData;
serverToHostData.WriteData(clientToServerData.playerKey, clientToServerData.playerPosition, clientToServerData.playerRotation);
serverToHostData.Serialize(sendPacket, PROTOCOL::GAME_PLAYER_MOVE, EXTRA::SUCCESS);
leader->GetPlayer()->GetNetworkSession()->PushSendPacketToPacketQueue(sendPacket);
}
}
}
else if (packet->header.extra == (INT)EXTRA::HOST_TO_SERVER)
{
CLIENTtoSERVER_GamePlayerMovePacketData hostToServerData;
hostToServerData.Deserialize(packet);
if (PlayerManager::GetInstance()->FindPlayer(hostToServerData.playerKey))
{
Game* game = GameManager::GetInstance()->FindGame(hostToServerData.gameKey);
if (game != NULL)
{
GamePlayer* gamePlayer = PlayerManager::GetInstance()->GetGamePlayer(player);
if (gamePlayer->IsLeader())
{
Player* findPlayer = PlayerManager::GetInstance()->FindPlayerFromKey(hostToServerData.playerKey);
vector<Package*> gamePackages;
vector<GamePlayer*>& gamePlayers = game->GetPlayers();
SERVERtoCLIENT_GamePlayerMovePacketData serverToClientData;
serverToClientData.WriteData(findPlayer->GetPlayerID(), hostToServerData.playerPosition, hostToServerData.playerRotation);
for (INT i = 0; i < (INT)gamePlayers.size(); i++)
{
TcpPacket* packet = PacketFactory::GetInstance()->GetPacketPool()->Pop();
serverToClientData.Serialize(packet, PROTOCOL::OTHER_GAME_PLAYER_MOVE, EXTRA::SUCCESS);
Package* package = new Package();
package->packet = packet;
package->player = gamePlayers[i]->GetPlayer();
gamePackages.push_back(package);
}
Network::GetInstance()->BroadCastPacket(gamePackages, findPlayer);
}
}
}
}
}
VOID GAME_PLAYER_ATTACK(Player* player, TcpPacket* packet)
{
if (packet->header.extra == (INT)EXTRA::CLIENT_TO_SERVER)
{
CLIENTtoSERVER_GamePlayerAttackPacketData clientToServerData;
clientToServerData.Deserialize(packet);
if (PlayerManager::GetInstance()->FindPlayer(clientToServerData.playerKey))
{
Game* game = GameManager::GetInstance()->FindGame(clientToServerData.gameKey);
if (game != NULL)
{
GamePlayer* gamePlayer = PlayerManager::GetInstance()->GetGamePlayer(player);
GamePlayer* leader = game->GetLeader();
TcpPacket* sendPacket = PacketFactory::GetInstance()->GetPacketPool()->Pop();
SERVERtoHOST_GamePlayerAttackPacketData serverToHostData;
serverToHostData.WriteData(clientToServerData.playerKey);
serverToHostData.Serialize(sendPacket, PROTOCOL::GAME_PLAYER_ATTACK, EXTRA::SUCCESS);
leader->GetPlayer()->GetNetworkSession()->PushSendPacketToPacketQueue(sendPacket);
}
}
}
else if (packet->header.extra == (INT)EXTRA::HOST_TO_SERVER)
{
CLIENTtoSERVER_GamePlayerAttackPacketData hostToServerData;
hostToServerData.Deserialize(packet);
if (PlayerManager::GetInstance()->FindPlayer(hostToServerData.playerKey))
{
Game* game = GameManager::GetInstance()->FindGame(hostToServerData.gameKey);
if (game != NULL)
{
GamePlayer* gamePlayer = PlayerManager::GetInstance()->GetGamePlayer(player);
if (gamePlayer->IsLeader())
{
Player* findPlayer = PlayerManager::GetInstance()->FindPlayerFromKey(hostToServerData.playerKey);
vector<Package*> gamePackages;
vector<GamePlayer*>& gamePlayers = game->GetPlayers();
SERVERtoCLIENT_GamePlayerAttackPacketData serverToClientData;
serverToClientData.WriteData(findPlayer->GetPlayerID());
for (INT i = 0; i < (INT)gamePlayers.size(); i++)
{
TcpPacket* packet = PacketFactory::GetInstance()->GetPacketPool()->Pop();
serverToClientData.Serialize(packet, PROTOCOL::OTHER_GAME_PLAYER_ATTACK, EXTRA::SUCCESS);
Package* package = new Package();
package->packet = packet;
package->player = gamePlayers[i]->GetPlayer();
gamePackages.push_back(package);
}
Network::GetInstance()->BroadCastPacket(gamePackages, findPlayer);
}
}
}
}
}
VOID GAME_PLAYER_DAMAGED(Player* player, TcpPacket* packet)
{
CLIENTtoSERVER_GamePlayerDamagedPacketData clientToServerData;
clientToServerData.Deserialize(packet);
if (PlayerManager::GetInstance()->FindPlayer(clientToServerData.playerKey))
{
Game* game = GameManager::GetInstance()->FindGame(clientToServerData.gameKey);
if (game != NULL)
{
GamePlayer* gamePlayer = PlayerManager::GetInstance()->GetGamePlayer(player);
vector<Package*> gamePackages;
vector<GamePlayer*>& gamePlayers = game->GetPlayers();
SERVERtoCLIENT_GamePlayerDamagedPacketData serverToClientData;
serverToClientData.WriteData(clientToServerData.playerID, clientToServerData.hp);
for (INT i = 0; i < (INT)gamePlayers.size(); i++)
{
TcpPacket* packet = PacketFactory::GetInstance()->GetPacketPool()->Pop();
serverToClientData.Serialize(packet, PROTOCOL::GAME_PLAYER_DAMAGED, EXTRA::SUCCESS);
Package* package = new Package();
package->packet = packet;
package->player = gamePlayers[i]->GetPlayer();
gamePackages.push_back(package);
}
Network::GetInstance()->BroadCastPacket(gamePackages, player);
}
}
}
VOID GAME_PLAYER_DIE(Player* player, TcpPacket* packet)
{
CLIENTtoSERVER_GamePlayerDiePacketData clientToServerData;
clientToServerData.Deserialize(packet);
if (PlayerManager::GetInstance()->FindPlayer(clientToServerData.playerKey))
{
Game* game = GameManager::GetInstance()->FindGame(clientToServerData.gameKey);
if (game != NULL)
{
wstring message = L"";
message.append(L"ID : ").append(player->GetPlayerID());
Utils::GetInstance()->LogSucc(L"GAME PLAYER DIE", message);
GamePlayer* gamePlayer = PlayerManager::GetInstance()->GetGamePlayer(player);
vector<Package*> gamePackages;
vector<GamePlayer*>& gamePlayers = game->GetPlayers();
SERVERtoCLIENT_GamePlayerDiePacketData serverToClientData;
serverToClientData.WriteData(clientToServerData.playerID);
for (INT i = 0; i < (INT)gamePlayers.size(); i++)
{
TcpPacket* packet = PacketFactory::GetInstance()->GetPacketPool()->Pop();
serverToClientData.Serialize(packet, PROTOCOL::GAME_PLAYER_DIE, EXTRA::SUCCESS);
Package* package = new Package();
package->packet = packet;
package->player = gamePlayers[i]->GetPlayer();
gamePackages.push_back(package);
}
Network::GetInstance()->BroadCastPacket(gamePackages, player);
}
}
}
VOID ENEMY_SPAWN(Player* player, TcpPacket* packet)
{
CLIENTtoSERVER_EnemySpawnPacketData clientToServerData;
clientToServerData.Deserialize(packet);
if (PlayerManager::GetInstance()->FindPlayer(clientToServerData.playerKey))
{
Game* game = GameManager::GetInstance()->FindGame(clientToServerData.gameKey);
if (game != NULL)
{
Utils::GetInstance()->LogSucc(L"ENEMY SPAWN", L"몬스터 생성 됨");
GamePlayer* gamePlayer = PlayerManager::GetInstance()->GetGamePlayer(player);
vector<Package*> gamePackages;
vector<GamePlayer*>& gamePlayers = game->GetPlayers();
SERVERtoCLIENT_EnemySpawnPacketData serverToClientData;
serverToClientData.WriteData(clientToServerData.enemyID, clientToServerData.position);
for (INT i = 0; i < (INT)gamePlayers.size(); i++)
{
TcpPacket* packet = PacketFactory::GetInstance()->GetPacketPool()->Pop();
serverToClientData.Serialize(packet, PROTOCOL::ENEMY_SPAWN, EXTRA::SUCCESS);
Package* package = new Package();
package->packet = packet;
package->player = gamePlayers[i]->GetPlayer();
gamePackages.push_back(package);
}
Network::GetInstance()->BroadCastPacket(gamePackages, player);
}
}
}
VOID ENEMY_MOVE(Player* player, TcpPacket* packet)
{
CLIENTtoSERVER_EnemyMovePacketData clientToServerData;
clientToServerData.Deserialize(packet);
if (PlayerManager::GetInstance()->FindPlayer(clientToServerData.playerKey))
{
Game* game = GameManager::GetInstance()->FindGame(clientToServerData.gameKey);
GamePlayer* gamePlayer = PlayerManager::GetInstance()->GetGamePlayer(player);
if (game != NULL)
{
vector<Package*> gamePackages;
vector<GamePlayer*>& gamePlayers = game->GetPlayers();
SERVERtoCLIENT_EnemyMovePacketData serverToClientData;
serverToClientData.WriteData(clientToServerData.enemyID, clientToServerData.position, clientToServerData.rotation);
for (INT i = 0; i < (INT)gamePlayers.size(); i++)
{
TcpPacket* packet = PacketFactory::GetInstance()->GetPacketPool()->Pop();
serverToClientData.Serialize(packet, PROTOCOL::ENEMY_MOVE, EXTRA::SUCCESS);
Package* package = new Package();
package->packet = packet;
package->player = gamePlayers[i]->GetPlayer();
gamePackages.push_back(package);
}
Network::GetInstance()->BroadCastPacket(gamePackages, player);
}
}
}
VOID ENEMY_DAMAGED(Player* player, TcpPacket* packet)
{
CLIENTtoSERVER_EnemyDamagedPacketData clientToServerData;
clientToServerData.Deserialize(packet);
if (PlayerManager::GetInstance()->FindPlayer(clientToServerData.playerKey))
{
Game* game = GameManager::GetInstance()->FindGame(clientToServerData.gameKey);
GamePlayer* gamePlayer = PlayerManager::GetInstance()->GetGamePlayer(player);
if (game != NULL)
{
vector<Package*> gamePackages;
vector<GamePlayer*>& gamePlayers = game->GetPlayers();
SERVERtoCLIENT_EnemyDamagedPacketData serverToClientData;
serverToClientData.WriteData(clientToServerData.enemyID);
for (INT i = 0; i < (INT)gamePlayers.size(); i++)
{
TcpPacket* packet = PacketFactory::GetInstance()->GetPacketPool()->Pop();
serverToClientData.Serialize(packet, PROTOCOL::ENEMY_DAMAGED, EXTRA::SUCCESS);
Package* package = new Package();
package->packet = packet;
package->player = gamePlayers[i]->GetPlayer();
gamePackages.push_back(package);
}
Network::GetInstance()->BroadCastPacket(gamePackages, player);
}
}
}
VOID ENEMY_ATTACK(Player* player, TcpPacket* packet)
{
CLIENTtoSERVER_EnemyAttackPacketData clientToServerData;
clientToServerData.Deserialize(packet);
if (PlayerManager::GetInstance()->FindPlayer(clientToServerData.playerKey))
{
Game* game = GameManager::GetInstance()->FindGame(clientToServerData.gameKey);
if (game != NULL)
{
GamePlayer* gamePlayer = PlayerManager::GetInstance()->GetGamePlayer(player);
vector<Package*> gamePackages;
vector<GamePlayer*>& gamePlayers = game->GetPlayers();
SERVERtoCLIENT_EnemyAttackPacketData serverToClientData;
serverToClientData.WriteData(clientToServerData.enemyID);
for (INT i = 0; i < (INT)gamePlayers.size(); i++)
{
TcpPacket* packet = PacketFactory::GetInstance()->GetPacketPool()->Pop();
serverToClientData.Serialize(packet, PROTOCOL::ENEMY_ATTACK, EXTRA::SUCCESS);
Package* package = new Package();
package->packet = packet;
package->player = gamePlayers[i]->GetPlayer();
gamePackages.push_back(package);
}
Network::GetInstance()->BroadCastPacket(gamePackages, player);
}
}
}
VOID ENEMY_DIE(Player* player, TcpPacket* packet)
{
CLIENTtoSERVER_EnemyDiePacketData clientToServerData;
clientToServerData.Deserialize(packet);
if (PlayerManager::GetInstance()->FindPlayer(clientToServerData.playerKey))
{
Game* game = GameManager::GetInstance()->FindGame(clientToServerData.gameKey);
if (game != NULL)
{
GamePlayer* gamePlayer = PlayerManager::GetInstance()->GetGamePlayer(player);
vector<Package*> gamePackages;
vector<GamePlayer*>& gamePlayers = game->GetPlayers();
SERVERtoCLIENT_EnemyDiePacketData serverToClientData;
serverToClientData.WriteData(clientToServerData.enemyID);
for (INT i = 0; i < (INT)gamePlayers.size(); i++)
{
TcpPacket* packet = PacketFactory::GetInstance()->GetPacketPool()->Pop();
serverToClientData.Serialize(packet, PROTOCOL::ENEMY_DIE, EXTRA::SUCCESS);
Package* package = new Package();
package->packet = packet;
package->player = gamePlayers[i]->GetPlayer();
gamePackages.push_back(package);
}
Network::GetInstance()->BroadCastPacket(gamePackages, player);
}
}
}
VOID POTION_SPAWN(Player* player, TcpPacket* packet)
{
CLIENTtoSERVER_PotionSpawnPacketData clientToServerData;
clientToServerData.Deserialize(packet);
if (PlayerManager::GetInstance()->FindPlayer(clientToServerData.playerKey))
{
Game* game = GameManager::GetInstance()->FindGame(clientToServerData.gameKey);
if (game != NULL)
{
Utils::GetInstance()->LogSucc(L"POTION SPAWN", L"포션 생성 됨");
GamePlayer* gamePlayer = PlayerManager::GetInstance()->GetGamePlayer(player);
vector<Package*> gamePackages;
vector<GamePlayer*>& gamePlayers = game->GetPlayers();
SERVERtoCLIENT_PotionSpawnPacketData serverToClientData;
serverToClientData.WriteData(clientToServerData.potionID, clientToServerData.position);
for (INT i = 0; i < (INT)gamePlayers.size(); i++)
{
TcpPacket* packet = PacketFactory::GetInstance()->GetPacketPool()->Pop();
serverToClientData.Serialize(packet, PROTOCOL::POTION_SPAWN, EXTRA::SUCCESS);
Package* package = new Package();
package->packet = packet;
package->player = gamePlayers[i]->GetPlayer();
gamePackages.push_back(package);
}
Network::GetInstance()->BroadCastPacket(gamePackages, player);
}
}
}
VOID POTION_PICKUP(Player* player, TcpPacket* packet)
{
CLIENTtoSERVER_PotionPickupPacketData clientToServerData;
clientToServerData.Deserialize(packet);
if (PlayerManager::GetInstance()->FindPlayer(clientToServerData.playerKey))
{
Game* game = GameManager::GetInstance()->FindGame(clientToServerData.gameKey);
if (game != NULL)
{
wstring message = L"";
message.append(L"ID : ").append(player->GetPlayerID());
Utils::GetInstance()->LogSucc(L"POTION PICKUP", message);
GamePlayer* gamePlayer = PlayerManager::GetInstance()->GetGamePlayer(player);
vector<Package*> gamePackages;
vector<GamePlayer*>& gamePlayers = game->GetPlayers();
SERVERtoCLIENT_PotionPickupPacketData serverToClientData;
serverToClientData.WriteData(clientToServerData.playerID, clientToServerData.potionID, clientToServerData.hp);
for (INT i = 0; i < (INT)gamePlayers.size(); i++)
{
TcpPacket* packet = PacketFactory::GetInstance()->GetPacketPool()->Pop();
serverToClientData.Serialize(packet, PROTOCOL::POTION_PICKUP, EXTRA::SUCCESS);
Package* package = new Package();
package->packet = packet;
package->player = gamePlayers[i]->GetPlayer();
gamePackages.push_back(package);
}
Network::GetInstance()->BroadCastPacket(gamePackages, player);
}
}
} | [
"[email protected]"
]
| |
1bb312279de2042eed94d47d0301276591b3f3aa | 4a1d0fd0d64416fc4454567143d7b960a68b0bd2 | /Chapter-9/test.cc | fd73e7db90f1a0c1e7c6143a5a089dee5de310c9 | []
| no_license | power321/ProgrammerInterview | bf393cd4da8ba949709015e2bf132dffd1e5cdd9 | 33b1e9e70c74f7e6ff9c4ed940363f27984fa9b2 | refs/heads/master | 2021-01-10T05:18:26.711167 | 2017-02-26T13:55:41 | 2017-02-26T13:55:41 | 52,147,851 | 0 | 0 | null | 2016-02-23T11:07:11 | 2016-02-20T10:19:42 | C++ | UTF-8 | C++ | false | false | 424 | cc | #include <iostream>
using namespace std;
template <typename AnyType>
void Swap(AnyType &a, AnyType &b)
{
AnyType temp;
temp = a;
a = b;
b = temp;
}
int main()
{
int a=2, b=3;
double f1=1.2, f2=2.3;
cout << "a=" << a << " b=" << b << endl;
Swap(a,b);
cout << "a=" << a << " b=" << b << endl;
cout << "f1=" << f1 << " f2=" << f2 << endl;
Swap(f1,f2);
cout << "f1=" << f1 << " f2=" << f2 << endl;
return 0;
}
| [
"[email protected]"
]
| |
ecbfa1bbf0668eb709cfe98cd4cbd11127412b90 | b19f30140cef064cbf4b18e749c9d8ebdd8bf27f | /D3DGame_180730_005_TextureCoord/Program.cpp | 53228c99a67125830f1d4c4bfed7df05fdc622c9 | []
| no_license | evehour/SGADHLee | 675580e199991916cf3134e7c61749b0a0bfa070 | 0ebbedf5d0692b782e2e5f9a372911c65f98ddc4 | refs/heads/master | 2020-03-25T13:22:42.597811 | 2019-01-03T07:05:54 | 2019-01-03T07:05:54 | 143,822,128 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,786 | cpp | #include "stdafx.h"
#include "Program.h"
//#include "./Executes/ExeTriangle.h"
//#include "./Executes/ExeRect.h"
//#include "./Executes/ExeTexture.h"
#include "./Executes/ExeTextureCoord.h"
Program::Program()
{
States::Create();
D3DDesc desc;
D3D::GetDesc(&desc);
values = new ExecuteValues();
values->ViewProjection = new ViewProjectionBuffer();
values->Perspective = new Perspective(desc.Width, desc.Height);
values->Viewport = new Viewport(desc.Width, desc.Height);
D3DXVECTOR3 position(0, 0, -5);
D3DXVECTOR3 forward(0, 0, 1);
D3DXVECTOR3 right(1, 0, 0);
D3DXVECTOR3 up(0, 1, 0);
D3DXMatrixLookAtLH(&view, &position, &(position + forward), &up);
//executes.push_back(new ExeTriangle(values));
//executes.push_back(new ExeTexture(values));
executes.push_back(new ExeTextureCoord(values));
}
Program::~Program()
{
for (Execute* exe : executes)
SAFE_DELETE(exe);
SAFE_DELETE(values->ViewProjection);
SAFE_DELETE(values->Perspective);
SAFE_DELETE(values->Viewport);
SAFE_DELETE(values);
States::Delete();
}
void Program::Update()
{
for (Execute* exe : executes)
exe->Update();
}
void Program::PreRender()
{
}
void Program::Render()
{
D3DXMATRIX projection;
values->Perspective->GetMatrix(&projection);
values->ViewProjection->SetView(view);
values->ViewProjection->SetProjection(projection);
values->ViewProjection->SetVSBuffer(0);
for (Execute* exe : executes)
exe->Render();
}
void Program::PostRender()
{
for (Execute* exe : executes)
exe->PostRender();
ImGui::Text("Fps : %f", Time::Get()->FPS());
}
void Program::ResizeScreen()
{
D3DDesc desc;
D3D::GetDesc(&desc);
values->Perspective->Set(desc.Width, desc.Height);
values->Viewport->Set(desc.Width, desc.Height);
for (Execute* exe : executes)
exe->ResizeScreen();
} | [
"[email protected]"
]
| |
ec54e51ff5c330a6fabd55440be5690cac2e8dc2 | 183d423b1ca9fbaabc455e0ddc76730ca2d1c15d | /MFC/ExtensionDll/RoundButton.cpp | be8e6cadc7a901eab181a468787a9fb2fe8c1672 | []
| no_license | leihtg/cproject | 8c0bf5fe04986faacdd4a48320860bf7c92c1ba2 | f1ef52ce3092add39216cec8da7d89f03a3db633 | refs/heads/master | 2022-02-16T00:20:41.200444 | 2019-08-25T13:59:01 | 2019-08-25T13:59:01 | 109,554,174 | 2 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 642 | cpp | // RoundButton.cpp : implementation file
//
#include "stdafx.h"
#include "RoundButton.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CRoundButton
CRoundButton::CRoundButton()
{
}
CRoundButton::~CRoundButton()
{
}
BEGIN_MESSAGE_MAP(CRoundButton, CButton)
//{{AFX_MSG_MAP(CRoundButton)
// NOTE - the ClassWizard will add and remove mapping macros here.
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CRoundButton message handlers
| [
"[email protected]"
]
| |
7a7c8073e515dac8e5c57767e111ead4bac33a98 | 473e535cfb52a99abbb2a1f7193226e14d0147b7 | /test_m4ri_2.cpp | ba00758dfb33f2929ccd5c209f70d5a942994c71 | []
| no_license | skramm/m4ri-expe | 4175e65d5fcca40ea5a1a280d34f2ab006280ba0 | 24731f417f3028595f72720a7f2acec99632e86d | refs/heads/master | 2022-04-17T23:16:10.951802 | 2020-04-11T16:22:19 | 2020-04-11T16:22:19 | 254,894,208 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,116 | cpp |
/**
\file
\brief test of m4ri
*/
#include <iostream>
#include "wrapper_m4ri.hpp"
#include "binary_mat.hpp"
#include "convert.hpp"
//-------------------------------------------------------------------
int main( int argc, char** argv )
{
int r = 10;
int c = 20;
if( argc == 3 )
{
r = std::stoi( argv[1] );
c = std::stoi( argv[2] );
}
MatM4ri m(r,c);
m.randomize();
std::cout << " start:\n" << m;
BinaryMatrix bmat1 = convertFromM4ri( m );
size_t iter=0;
// bmat1.print( std::cout, "bmat1" );
auto bmat2 = gaussianElim( bmat1, iter );
bmat2.print( std::cout, "gaussianElim" );
MatM4ri mine = convertToM4ri( bmat2 );
MatM4ri m2(m);
std::cout << "mzd_echelonize_naive( m._data, 0 );\n";
mzd_echelonize_naive( m._data, 0 );
std::cout << m;
std::cout << ( mzd_equal( mine._data, m._data ) ? " -equal\n" : " -diff\n" );
m = m2;
std::cout << "mzd_echelonize_naive( m._data, 1 );\n";
mzd_echelonize_naive( m._data, 1 );
std::cout << m;
std::cout << ( mzd_equal( mine._data, m._data ) ? " -equal\n" : " -diff\n" );
}
//-------------------------------------------------------------------
| [
"[email protected]"
]
| |
2344716c66572a4e9591ad41c24638b3e71e9c38 | 27d8086114736e4d441bd73408cb5666ba19e8b9 | /src/patcher/function_hooks.cpp | 88f589f060ea0b90bedac9dfe52ce869d01dd50c | [
"MIT"
]
| permissive | dragonbane0/AutoSplitter-WiiU | 17ad6d40dda6e659c1e8e615f0c8701b475fbfa7 | fe304ede1b51ec8bb8b92d09738218c5542f27b3 | refs/heads/master | 2021-07-20T00:54:09.444364 | 2020-04-14T14:00:07 | 2020-04-14T14:00:07 | 130,211,584 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 26,140 | cpp | /****************************************************************************
* Copyright (C) 2016 Maschell
*
* 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/>.
****************************************************************************/
#include <stdio.h>
#include <malloc.h>
#include <string.h>
#include <stdarg.h>
#include <gctypes.h>
#include "function_hooks.h"
#include "dynamic_libs/aoc_functions.h"
#include "dynamic_libs/ax_functions.h"
#include "dynamic_libs/fs_functions.h"
#include "dynamic_libs/gx2_functions.h"
#include "dynamic_libs/os_functions.h"
#include "dynamic_libs/padscore_functions.h"
#include "dynamic_libs/socket_functions.h"
#include "dynamic_libs/sys_functions.h"
#include "dynamic_libs/vpad_functions.h"
#include "dynamic_libs/acp_functions.h"
#include "dynamic_libs/syshid_functions.h"
#include "kernel/kernel_functions.h"
#include "utils/logger.h"
#include "common/common.h"
#include "autoSplitter.h"
#include "autoSplitterSystem.h"
#include "main.h"
#define LIB_CODE_RW_BASE_OFFSET 0xC1000000
#define CODE_RW_BASE_OFFSET 0x00000000
#define DEBUG_LOG_DYN 0
#define USE_EXTRA_LOG_FUNCTIONS 0
#define DECL(res, name, ...) \
res (* real_ ## name)(__VA_ARGS__) __attribute__((section(".data"))); \
res my_ ## name(__VA_ARGS__)
#define PRINT_TEXT1(x, y, str) { OSScreenPutFontEx(1, x, y, str); OSScreenPutFontEx(0, x, y, str); }
#define PRINT_TEXT2(x, y, _fmt, ...) { __os_snprintf(msg, 80, _fmt, __VA_ARGS__); OSScreenPutFontEx(0, x, y, msg);OSScreenPutFontEx(1, x, y, msg); }
//DKC Vars
char dkc_currentLevelName[4];
u32 dkc_currentIslandID = 0;
u8 dkc_splitGate = 0;
//Gets called whenever the system polls a generic controller (high level)
DECL(s32, KPADRead, s32 chan, KPADData *data, u32 size)
{
s32 result = real_KPADRead(chan, data, size); //Read the actual inputs from the real function
if (result == 0)
{
if (data->device_type > 1)
{
g_proControllerChannel = chan;
g_currentInputDataKPAD = *data;
}
else
{
if (chan == g_proControllerChannel)
g_proControllerChannel = -1;
}
}
else
{
if (chan == g_proControllerChannel)
g_proControllerChannel = -1;
}
//log_printf("read kpad channel: %i", chan);
return result;
}
//Gets called whenever the system polls a generic controller (low level)
DECL(void, WPADRead, s32 chan, KPADData *data)
{
real_WPADRead(chan, data);
if (chan == g_proControllerChannel)
g_currentInputDataKPAD = *data;
//log_printf("read wpad channel: %i", chan);
}
//Test if controller is connected
DECL(s32, WPADProbe, s32 chan, u32 *pad_type)
{
s32 result = real_WPADProbe(chan, pad_type);
if (result == 0)
{
if (*pad_type == 2) //Classic/Pro Controller
{
g_proControllerChannel = chan;
}
else
{
if (chan == g_proControllerChannel)
g_proControllerChannel = -1;
}
}
else
{
if (chan == g_proControllerChannel)
g_proControllerChannel = -1;
}
return result;
}
//Gets called whenever the system polls the WiiU Gamepad
DECL(int, VPADRead, int chan, VPADData *buffer, u32 buffer_size, s32 *error)
{
int result = real_VPADRead(chan, buffer, buffer_size, error); //Read the actual inputs from the real function
if (chan == 0) //Only read inputs from Controller Port 0 for now
g_currentInputData = *buffer;
return result;
}
//Re-direct socket lib finish into nothing so games can't kill the socket library and our connection by accident
DECL(int, socket_lib_finish, void)
{
return 0;
}
//Gets called on process exit
DECL(void, _Exit, void)
{
//Cleanup
DestroyAutoSplitterSystem();
real__Exit();
}
/* *****************************************************************************
* Creates function pointer array
* ****************************************************************************/
#define MAKE_MAGIC(x, lib,functionType) { (unsigned int) my_ ## x, (unsigned int) &real_ ## x, lib, # x,0,0,functionType,0}
static struct hooks_magic_t
{
const unsigned int replaceAddr;
const unsigned int replaceCall;
const unsigned int library;
const char functionName[50];
unsigned int realAddr;
unsigned int restoreInstruction;
unsigned char functionType;
unsigned char alreadyPatched;
}
method_hooks[] =
{
MAKE_MAGIC(VPADRead, LIB_VPAD,STATIC_FUNCTION),
MAKE_MAGIC(socket_lib_finish, LIB_NSYSNET,STATIC_FUNCTION),
MAKE_MAGIC(_Exit, LIB_CORE_INIT,STATIC_FUNCTION),
//MAKE_MAGIC(KPADRead, LIB_PADSCORE,STATIC_FUNCTION),
//MAKE_MAGIC(WPADRead, LIB_PADSCORE,STATIC_FUNCTION),
//MAKE_MAGIC(WPADProbe, LIB_PADSCORE,DYNAMIC_FUNCTION),
};
//! buffer to store our 7 instructions needed for our replacements
//! the code will be placed in the address of that buffer - CODE_RW_BASE_OFFSET
//! avoid this buffer to be placed in BSS and reset on start up
volatile unsigned int dynamic_method_calls[sizeof(method_hooks) / sizeof(struct hooks_magic_t) * 7] __attribute__((section(".data")));
/*
*Patches a function that is loaded at the start of each application. Its not required to restore, at least when they are really dynamic.
* "normal" functions should be patch with the normal patcher. Current Code by Maschell with the help of dimok.
*/
void PatchMethodHooks(void)
{
/* Patch branches to it. */
volatile unsigned int *space = &dynamic_method_calls[0];
int method_hooks_count = sizeof(method_hooks) / sizeof(struct hooks_magic_t);
u32 skip_instr = 1;
u32 my_instr_len = 6;
u32 instr_len = my_instr_len + skip_instr;
u32 flush_len = 4*instr_len;
for(int i = 0; i < method_hooks_count; i++)
{
log_printf("Patching %s ...",method_hooks[i].functionName);
if(method_hooks[i].functionType == STATIC_FUNCTION && method_hooks[i].alreadyPatched == 1){
if(isDynamicFunction((u32)OSEffectiveToPhysical((void*)method_hooks[i].realAddr))){
log_printf(" The function %s is a dynamic function. Please fix that <3 ... ", method_hooks[i].functionName);
method_hooks[i].functionType = DYNAMIC_FUNCTION;
}else{
log_printf(" skipped. Its already patched\n", method_hooks[i].functionName);
space += instr_len;
continue;
}
}
u32 physical = 0;
unsigned int repl_addr = (unsigned int)method_hooks[i].replaceAddr;
unsigned int call_addr = (unsigned int)method_hooks[i].replaceCall;
unsigned int real_addr = GetAddressOfFunction(method_hooks[i].functionName,method_hooks[i].library);
if(!real_addr){
log_printf("Error. OSDynLoad_FindExport failed for %s\n", method_hooks[i].functionName);
space += instr_len;
continue;
}
if(DEBUG_LOG_DYN)log_printf("%s is located at %08X!\n", method_hooks[i].functionName,real_addr);
physical = (u32)OSEffectiveToPhysical((void*)real_addr);
if(!physical){
log_printf("Error. Something is wrong with the physical address\n");
space += instr_len;
continue;
}
if(DEBUG_LOG_DYN)log_printf("%s physical is located at %08X!\n", method_hooks[i].functionName,physical);
bat_table_t my_dbat_table;
if(DEBUG_LOG_DYN)log_printf("Setting up DBAT\n");
KernelSetDBATsForDynamicFuction(&my_dbat_table,physical);
//log_printf("Setting call_addr to %08X\n",(unsigned int)(space) - CODE_RW_BASE_OFFSET);
*(volatile unsigned int *)(call_addr) = (unsigned int)(space) - CODE_RW_BASE_OFFSET;
// copy instructions from real function.
u32 offset_ptr = 0;
for(offset_ptr = 0;offset_ptr<skip_instr*4;offset_ptr +=4){
if(DEBUG_LOG_DYN)log_printf("(real_)%08X = %08X\n",space,*(volatile unsigned int*)(physical+offset_ptr));
*space = *(volatile unsigned int*)(physical+offset_ptr);
space++;
}
//Only works if skip_instr == 1
if(skip_instr == 1){
// fill the restore instruction section
method_hooks[i].realAddr = real_addr;
method_hooks[i].restoreInstruction = *(volatile unsigned int*)(physical);
}else{
log_printf("Error. Can't save %s for restoring!\n", method_hooks[i].functionName);
}
//adding jump to real function
/*
90 61 ff e0 stw r3,-32(r1)
3c 60 12 34 lis r3,4660
60 63 56 78 ori r3,r3,22136
7c 69 03 a6 mtctr r3
80 61 ff e0 lwz r3,-32(r1)
4e 80 04 20 bctr*/
*space = 0x9061FFE0;
space++;
*space = 0x3C600000 | (((real_addr + (skip_instr * 4)) >> 16) & 0x0000FFFF); // lis r3, real_addr@h
space++;
*space = 0x60630000 | ((real_addr + (skip_instr * 4)) & 0x0000ffff); // ori r3, r3, real_addr@l
space++;
*space = 0x7C6903A6; // mtctr r3
space++;
*space = 0x8061FFE0; // lwz r3,-32(r1)
space++;
*space = 0x4E800420; // bctr
space++;
DCFlushRange((void*)(space - instr_len), flush_len);
ICInvalidateRange((unsigned char*)(space - instr_len), flush_len);
//setting jump back
unsigned int replace_instr = 0x48000002 | (repl_addr & 0x03fffffc);
*(volatile unsigned int *)(physical) = replace_instr;
ICInvalidateRange((void*)(real_addr), 4);
//restore my dbat stuff
KernelRestoreDBATs(&my_dbat_table);
method_hooks[i].alreadyPatched = 1;
log_printf("done!\n");
}
log_print("Done with patching all functions!\n");
}
/* ****************************************************************** */
/* RESTORE ORIGINAL INSTRUCTIONS */
/* ****************************************************************** */
void RestoreInstructions(void)
{
bat_table_t table;
log_printf("Restore functions!\n");
int method_hooks_count = sizeof(method_hooks) / sizeof(struct hooks_magic_t);
for(int i = 0; i < method_hooks_count; i++)
{
log_printf("Restoring %s ...",method_hooks[i].functionName);
if(method_hooks[i].restoreInstruction == 0 || method_hooks[i].realAddr == 0){
log_printf("Error. I dont have the information for the restore =( skip\n");
continue;
}
unsigned int real_addr = GetAddressOfFunction(method_hooks[i].functionName,method_hooks[i].library);
if(!real_addr){
//log_printf("Error. OSDynLoad_FindExport failed for %s\n", method_hooks[i].functionName);
continue;
}
u32 physical = (u32)OSEffectiveToPhysical((void*)real_addr);
if(!physical){
log_printf("Error. Something is wrong with the physical address\n");
continue;
}
if(isDynamicFunction(physical)){
log_printf("Error. Its a dynamic function. We don't need to restore it! %s\n",method_hooks[i].functionName);
}else{
KernelSetDBATs(&table);
*(volatile unsigned int *)(LIB_CODE_RW_BASE_OFFSET + method_hooks[i].realAddr) = method_hooks[i].restoreInstruction;
DCFlushRange((void*)(LIB_CODE_RW_BASE_OFFSET + method_hooks[i].realAddr), 4);
ICInvalidateRange((void*)method_hooks[i].realAddr, 4);
log_printf(" done\n");
KernelRestoreDBATs(&table);
}
method_hooks[i].alreadyPatched = 0; // In case a
}
KernelRestoreInstructions();
log_print("Done with restoring all functions!\n");
}
int isDynamicFunction(unsigned int physicalAddress){
if((physicalAddress & 0x80000000) == 0x80000000){
return 1;
}
return 0;
}
unsigned int GetAddressOfFunction(const char * functionName,unsigned int library){
unsigned int real_addr = 0;
unsigned int rpl_handle = 0;
if (library == LIB_CORE_INIT) {
if (DEBUG_LOG_DYN)log_printf("FindExport of %s! From LIB_CORE_INIT\n", functionName);
if (coreinit_handle == 0) { log_print("LIB_CORE_INIT not aquired\n"); return 0; }
rpl_handle = coreinit_handle;
}
else if (library == LIB_NSYSNET) {
if (DEBUG_LOG_DYN)log_printf("FindExport of %s! From LIB_NSYSNET\n", functionName);
if (nsysnet_handle == 0) { log_print("LIB_NSYSNET not aquired\n"); return 0; }
rpl_handle = nsysnet_handle;
}
else if (library == LIB_GX2) {
if (DEBUG_LOG_DYN)log_printf("FindExport of %s! From LIB_GX2\n", functionName);
if (gx2_handle == 0) { log_print("LIB_GX2 not aquired\n"); return 0; }
rpl_handle = gx2_handle;
}
else if (library == LIB_AOC) {
if (DEBUG_LOG_DYN)log_printf("FindExport of %s! From LIB_AOC\n", functionName);
if (aoc_handle == 0) { log_print("LIB_AOC not aquired\n"); return 0; }
rpl_handle = aoc_handle;
}
else if (library == LIB_AX) {
if (DEBUG_LOG_DYN)log_printf("FindExport of %s! From LIB_AX\n", functionName);
if (sound_handle == 0) { log_print("LIB_AX not aquired\n"); return 0; }
rpl_handle = sound_handle;
}
else if (library == LIB_FS) {
if (DEBUG_LOG_DYN)log_printf("FindExport of %s! From LIB_FS\n", functionName);
if (coreinit_handle == 0) { log_print("LIB_FS not aquired\n"); return 0; }
rpl_handle = coreinit_handle;
}
else if (library == LIB_OS) {
if (DEBUG_LOG_DYN)log_printf("FindExport of %s! From LIB_OS\n", functionName);
if (coreinit_handle == 0) { log_print("LIB_OS not aquired\n"); return 0; }
rpl_handle = coreinit_handle;
}
else if (library == LIB_PADSCORE) {
if (DEBUG_LOG_DYN)log_printf("FindExport of %s! From LIB_PADSCORE\n", functionName);
if (padscore_handle == 0) { log_print("LIB_PADSCORE not aquired\n"); return 0; }
rpl_handle = padscore_handle;
}
else if (library == LIB_SOCKET) {
if (DEBUG_LOG_DYN)log_printf("FindExport of %s! From LIB_SOCKET\n", functionName);
if (nsysnet_handle == 0) { log_print("LIB_SOCKET not aquired\n"); return 0; }
rpl_handle = nsysnet_handle;
}
else if (library == LIB_SYS) {
if (DEBUG_LOG_DYN)log_printf("FindExport of %s! From LIB_SYS\n", functionName);
if (sysapp_handle == 0) { log_print("LIB_SYS not aquired\n"); return 0; }
rpl_handle = sysapp_handle;
}
else if (library == LIB_VPAD) {
if (DEBUG_LOG_DYN)log_printf("FindExport of %s! From LIB_VPAD\n", functionName);
if (vpad_handle == 0) { log_print("LIB_VPAD not aquired\n"); return 0; }
rpl_handle = vpad_handle;
}
else if (library == LIB_NN_ACP) {
if (DEBUG_LOG_DYN)log_printf("FindExport of %s! From LIB_NN_ACP\n", functionName);
if (acp_handle == 0) { log_print("LIB_NN_ACP not aquired\n"); return 0; }
rpl_handle = acp_handle;
}
else if (library == LIB_SYSHID) {
if (DEBUG_LOG_DYN)log_printf("FindExport of %s! From LIB_SYSHID\n", functionName);
if (syshid_handle == 0) { log_print("LIB_SYSHID not aquired\n"); return 0; }
rpl_handle = syshid_handle;
}
else if (library == LIB_VPADBASE) {
if (DEBUG_LOG_DYN)log_printf("FindExport of %s! From LIB_VPADBASE\n", functionName);
if (vpadbase_handle == 0) { log_print("LIB_VPADBASE not aquired\n"); return 0; }
rpl_handle = vpadbase_handle;
}
if(!rpl_handle){
log_printf("Failed to find the RPL handle for %s\n", functionName);
return 0;
}
OSDynLoad_FindExport(rpl_handle, 0, functionName, &real_addr);
if(!real_addr){
log_printf("OSDynLoad_FindExport failed for %s\n", functionName);
return 0;
}
if((u32)(*(volatile unsigned int*)(real_addr) & 0xFF000000) == 0x48000000){
real_addr += (u32)(*(volatile unsigned int*)(real_addr) & 0x0000FFFF);
if((u32)(*(volatile unsigned int*)(real_addr) & 0xFF000000) == 0x48000000){
return 0;
}
}
return real_addr;
}
//DKC Tropical Freeze Functions
DECL(void, DKC_LoadingFinished, void *CStateManager1, void *CStateManager2) //set loading to 0
{
log_printf("LoadingFinished call");
g_isLoading = 0;
real_DKC_LoadingFinished(CStateManager1, CStateManager2);
}
DECL(u32, DKC_LaunchLevel, void *CArchitectureQueue1, void *CArchitectureQueue2) //use this to determine newRun via island id (=1) and the last island short name (=l01) after it returns
{
u32 gameStatePtr = real_DKC_LaunchLevel(CArchitectureQueue1, CArchitectureQueue2);
log_printf("LaunchLevel call finished! Game State Ptr: 0x%X", gameStatePtr);
if (dkc_currentIslandID == 1)
{
if (!strcmp(dkc_currentLevelName, "l01"))
{
g_newRun = 1;
}
}
return gameStatePtr;
}
DECL(int, DKC_ShowLoadingScreen, u8 ELoadDirection, void *CGameStateManager, void *CArchitectureQueue, void *IObjectStore, void *CResourceFactory) //set current island id here and loading = 1, reset gate
{
u32 Ptr = 0;
memcpy(&Ptr, (u32*)CGameStateManager, 4);
memcpy(&Ptr, (u32*)(Ptr + 4), 4);
memcpy(&dkc_currentIslandID, (u32*)Ptr, 4);
if (ELoadDirection == 1)
{
log_printf("Load Selection Map - Island ID: %i", dkc_currentIslandID);
}
else if (ELoadDirection == 0)
{
log_printf("Load Level - Island ID: %i", dkc_currentIslandID);
}
g_isLoading = 1;
dkc_splitGate = 0;
int ret = real_DKC_ShowLoadingScreen(ELoadDirection, CGameStateManager, CArchitectureQueue, IObjectStore, CResourceFactory);
return ret;
}
DECL(const char*, DKC_GetLocalizedShortName, const void *callingClass, const char* name) //save current level short name
{
log_printf("Localized area short name call - request: %s", name);
if (strlen(name) > 3)
{
memcpy(&dkc_currentLevelName, name, 3);
dkc_currentLevelName[3] = 0;
if (!strcmp(dkc_currentLevelName, "l01"))
{
log_printf("This is Level 01!");
}
}
const char* string = real_DKC_GetLocalizedShortName(callingClass, name);
return string;
}
DECL(void, DKC_StartTransition, int ETransitionType) //check for boss level here (=b00) and if transition type = 10 set split flag1
{
log_printf("Graphical Transition Started: %i", ETransitionType);
if (ETransitionType == 10)
{
if (!strcmp(dkc_currentLevelName, "b00"))
{
dkc_splitGate = 1;
}
}
real_DKC_StartTransition(ETransitionType);
}
DECL(void, DKC_BeatUpHandler_AcceptScriptMsg, void *CStateManager1, void *CStateManager2, const void *CScriptMsg) //if split flag1 and 0x49413036 then send Split. If final boss (islandID = 6) send runEnd
{
u32 MsgID = 0;
memcpy(&MsgID, (unsigned char*)CScriptMsg + 0x40, 4);
log_printf("[BeatUpHandler] Accept Script Msg: 0x%X", MsgID);
if (dkc_splitGate == 1 && MsgID == 0x49413036) //A boss was beatup (StopDetectionAndSetBeatup_0)
{
dkc_splitGate = 0;
if (dkc_currentIslandID == 6) //Final boss was beatup
g_endRun = 1;
else //Some other boss was beatup
g_doSplit = 1;
}
real_DKC_BeatUpHandler_AcceptScriptMsg(CStateManager1, CStateManager2, CScriptMsg);
}
DECL(void, DKC_BarrelBalloon_AcceptScriptMsg, void *CStateManager1, void *CStateManager2, const void *CScriptMsg) //if 0x49413037 and level is not boss level (!=b00) send Split
{
u32 MsgID = 0;
memcpy(&MsgID, (unsigned char*)CScriptMsg + 0x40, 4);
log_printf("[BarrelBalloon] Accept Script Msg: 0x%X", MsgID);
if (MsgID == 0x49413037) //Level End Barrel hit (AddToInventory)
{
if (strcmp(dkc_currentLevelName, "b00")) //confirm its not a boss level
{
g_doSplit = 1;
}
}
real_DKC_BarrelBalloon_AcceptScriptMsg(CStateManager1, CStateManager2, CScriptMsg);
}
hooks_magic_t dkc_hooks[] = //DKC Tropical Freeze
{
MAKE_MAGIC(DKC_LoadingFinished, LIB_GAME,DYNAMIC_FUNCTION),
MAKE_MAGIC(DKC_LaunchLevel, LIB_GAME,DYNAMIC_FUNCTION),
MAKE_MAGIC(DKC_ShowLoadingScreen, LIB_GAME,DYNAMIC_FUNCTION),
MAKE_MAGIC(DKC_GetLocalizedShortName, LIB_GAME,DYNAMIC_FUNCTION),
MAKE_MAGIC(DKC_StartTransition, LIB_GAME,DYNAMIC_FUNCTION),
MAKE_MAGIC(DKC_BeatUpHandler_AcceptScriptMsg, LIB_GAME,DYNAMIC_FUNCTION),
MAKE_MAGIC(DKC_BarrelBalloon_AcceptScriptMsg, LIB_GAME,DYNAMIC_FUNCTION),
};
volatile unsigned int dynamic_dkc_calls[sizeof(dkc_hooks) / sizeof(struct hooks_magic_t) * 7] __attribute__((section(".data")));
static const int totalGameHookArrays = 1;
/*
*Patches a game function
*/
void PatchGameHooks(void)
{
hooks_magic_t *currentHooks = 0;
int sizeHookArray = 0;
volatile unsigned int *space = 0; //Patch branches to it
if (OSGetTitleID() != 0 && (OSGetTitleID() == 0x0005000010137F00 || OSGetTitleID() == 0x0005000010138300 || OSGetTitleID() == 0x0005000010144800)) //DKC Tropical Freeze
{
currentHooks = &dkc_hooks[0];
sizeHookArray = sizeof(dkc_hooks);
space = &dynamic_dkc_calls[0];
log_printf("Patch game functions for DKC!\n");
}
else
{
log_printf("Game doesn't need function patching!\n");
return;
}
int method_hooks_count = sizeHookArray / sizeof(struct hooks_magic_t);
u32 skip_instr = 1;
u32 my_instr_len = 6;
u32 instr_len = my_instr_len + skip_instr;
u32 flush_len = 4 * instr_len;
for (int i = 0; i < method_hooks_count; i++)
{
log_printf("Patching %s ...", currentHooks[i].functionName);
u32 physical = 0;
unsigned int repl_addr = (unsigned int)currentHooks[i].replaceAddr;
unsigned int call_addr = (unsigned int)currentHooks[i].replaceCall;
unsigned int real_addr = GetGameAddressOfFunction(currentHooks[i].functionName);
if (!real_addr) {
log_printf("Error. Didnt find address for %s\n", currentHooks[i].functionName);
space += instr_len;
continue;
}
if (DEBUG_LOG_DYN)log_printf("%s is located at %08X!\n", currentHooks[i].functionName, real_addr);
physical = (u32)OSEffectiveToPhysical((void*)real_addr);
if (!physical) {
log_printf("Error. Something is wrong with the physical address\n");
space += instr_len;
continue;
}
if (DEBUG_LOG_DYN)log_printf("%s physical is located at %08X!\n", currentHooks[i].functionName, physical);
bat_table_t my_dbat_table;
if (DEBUG_LOG_DYN)log_printf("Setting up DBAT\n");
KernelSetDBATsForDynamicFuction(&my_dbat_table, physical);
//log_printf("Setting call_addr to %08X\n",(unsigned int)(space) - CODE_RW_BASE_OFFSET);
*(volatile unsigned int *)(call_addr) = (unsigned int)(space)-CODE_RW_BASE_OFFSET;
// copy instructions from real function.
u32 offset_ptr = 0;
for (offset_ptr = 0; offset_ptr<skip_instr * 4; offset_ptr += 4) {
if (DEBUG_LOG_DYN)log_printf("(real_)%08X = %08X\n", space, *(volatile unsigned int*)(physical + offset_ptr));
*space = *(volatile unsigned int*)(physical + offset_ptr);
space++;
}
//Only works if skip_instr == 1
if (skip_instr == 1) {
// fill the restore instruction section
currentHooks[i].realAddr = real_addr;
currentHooks[i].restoreInstruction = *(volatile unsigned int*)(physical);
}
else {
log_printf("Error. Can't save %s for restoring!\n", currentHooks[i].functionName);
}
//adding jump to real function
/*
90 61 ff e0 stw r3,-32(r1)
3c 60 12 34 lis r3,4660
60 63 56 78 ori r3,r3,22136
7c 69 03 a6 mtctr r3
80 61 ff e0 lwz r3,-32(r1)
4e 80 04 20 bctr*/
*space = 0x9061FFE0;
space++;
*space = 0x3C600000 | (((real_addr + (skip_instr * 4)) >> 16) & 0x0000FFFF); // lis r3, real_addr@h
space++;
*space = 0x60630000 | ((real_addr + (skip_instr * 4)) & 0x0000ffff); // ori r3, r3, real_addr@l
space++;
*space = 0x7C6903A6; // mtctr r3
space++;
*space = 0x8061FFE0; // lwz r3,-32(r1)
space++;
*space = 0x4E800420; // bctr
space++;
DCFlushRange((void*)(space - instr_len), flush_len);
ICInvalidateRange((unsigned char*)(space - instr_len), flush_len);
//setting jump back
unsigned int replace_instr = 0x48000002 | (repl_addr & 0x03fffffc);
*(volatile unsigned int *)(physical) = replace_instr;
ICInvalidateRange((void*)(real_addr), 4);
//restore my dbat stuff
KernelRestoreDBATs(&my_dbat_table);
currentHooks[i].alreadyPatched = 1;
log_printf("done!\n");
}
log_print("Done with patching all game functions!\n");
}
void RestoreGameInstructions(void)
{
log_printf("Restore all game functions!\n");
for (int n = 0; n < totalGameHookArrays; n++)
{
hooks_magic_t *currentHooks = 0;
int sizeHookArray = 0;
if (n == 0) //DKC Tropical Freeze
{
currentHooks = &dkc_hooks[0];
sizeHookArray = sizeof(dkc_hooks);
}
int method_hooks_count = sizeHookArray / sizeof(struct hooks_magic_t);
for (int i = 0; i < method_hooks_count; i++)
{
log_printf("Restoring %s ...", currentHooks[i].functionName);
if (currentHooks[i].restoreInstruction == 0 || currentHooks[i].realAddr == 0) {
log_printf("Error. I dont have the information for the restore =( skip\n");
continue;
}
currentHooks[i].alreadyPatched = 0;
}
}
log_print("Done with restoring all game functions!\n");
}
unsigned int GetGameAddressOfFunction(const char *functionName)
{
unsigned int real_addr = 0;
//DKC Section
if (!strcmp(functionName, "DKC_LoadingFinished"))
{
real_addr = 0x0ECB6A60;
return real_addr;
}
if (!strcmp(functionName, "DKC_LaunchLevel"))
{
real_addr = 0x0EF7B044;
return real_addr;
}
if (!strcmp(functionName, "DKC_ShowLoadingScreen"))
{
real_addr = 0x0EF7F29C;
return real_addr;
}
if (!strcmp(functionName, "DKC_GetLocalizedShortName"))
{
real_addr = 0x0EC3C804;
return real_addr;
}
if (!strcmp(functionName, "DKC_StartTransition"))
{
real_addr = 0x0EB44B04;
return real_addr;
}
if (!strcmp(functionName, "DKC_BeatUpHandler_AcceptScriptMsg"))
{
real_addr = 0x0EFEBBF0;
return real_addr;
}
if (!strcmp(functionName, "DKC_BarrelBalloon_AcceptScriptMsg"))
{
real_addr = 0x0EFE7270;
return real_addr;
}
return 0;
} | [
"[email protected]"
]
| |
54ac2ccdc9721ed7c335c3b67515d6438b6b6672 | fa9abaa16838c52af01affa4d5246a812f9cb232 | /lc_liked_110.cpp | 370a7c82e25160b10e87529181dbdc5855593ca6 | []
| no_license | mcc12357/acm- | fcbfa1d6fc5011d9c8c22f2186d44bcd0f1ceb98 | 114d386353e6cb31f6ba0d121591005bf42e2bed | refs/heads/master | 2020-04-03T17:37:35.742867 | 2019-01-06T01:32:00 | 2019-01-06T01:32:00 | 155,452,881 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,327 | cpp |
#include<iostream>
using namespace std;
#include<stdio.h>
#include<string>
#include<vector>
#include<set>
#include<map>
#include<algorithm>
#include<queue>
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
int max(int x,int y) {return x>y;}
int min(int x,int y) {return x<y;}
void FindMaxMinDepth(TreeNode* root,int cur_depth,int &max_depth,int &min_depth)
{
if(!(root->left) || !(root->right))
{
max_depth = max(max_depth,cur_depth);
min_depth = min(min_depth,cur_depth);
}
if(root->left) FindMaxMinDepth(root->left,cur_depth+1,max_depth,min_depth);
if(root->right) FindMaxMinDepth(root->right,cur_depth+1,max_depth,min_depth);
}
bool isBalanced(TreeNode* root) {
if(!root) return true;
int max_depth = 0,min_depth = 0x7fffffff;
FindMaxMinDepth(root,0,max_depth,min_depth);
cout<<max_depth<<' '<<min_depth<<endl;
if(max_depth-min_depth>1) return false;
return true;
}
};
int main()
{
Solution a;
TreeNode* root = new TreeNode(1);
TreeNode* x1 = new TreeNode(2);
TreeNode* x2 = new TreeNode(3);
root->right = x1;
x1->right = x2;
if(a.isBalanced(root)) cout<<"yes"<<endl;
} | [
"[email protected]"
]
| |
e25968d4baeabeac6b12175599b83de34c02eaa7 | 37f1efec9d084919fb200c2116d54c821501e25b | /server/游戏服务/TableFrame.cpp | 96533206aaef5d78478434ed097913f9f955c487 | []
| no_license | WesternCivilization/netfox | d9a7fa562b2bb957974b21c240e155faa4f615d3 | eb374dd1f7efea01da51b96405a8a0aec4bbe756 | refs/heads/master | 2021-06-11T16:43:32.675127 | 2017-02-01T01:05:53 | 2017-02-01T01:05:53 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 58,783 | cpp | #include "StdAfx.h"
#include "TableFrame.h"
//////////////////////////////////////////////////////////////////////////
//定时器 ID
#define IDI_OFFLINE (IDI_MAX_TIME_ID+1) //断线定时器
//////////////////////////////////////////////////////////////////////////
//构造函数
CTableFrame::CTableFrame()
{
//属性变量
m_wChairCount=0;
m_wTableID=INVALID_TABLE;
//状态变量
m_bTableLocked=false;
m_bGameStarted=false;
//状态变量
m_dwTimeStart=0L;
m_bGameStatus=GS_FREE;
ZeroMemory(m_szPassword,sizeof(m_szPassword));
//分数信息
m_lGameTaxScore=0L;
ZeroMemory(m_ScoreInfo,sizeof(m_ScoreInfo));
ZeroMemory(m_dwPlayerID,sizeof(m_dwPlayerID));
//用户信息
ZeroMemory(m_pIUserItem,sizeof(m_pIUserItem));
ZeroMemory(m_bAllowLookon,sizeof(m_bAllowLookon));
ZeroMemory(m_wOffLineCount,sizeof(m_wOffLineCount));
//配置变量
m_pGameServiceAttrib=NULL;
m_pGameServiceOption=NULL;
//接口变量
m_pITableFrameSink=NULL;
m_pITableUserAction=NULL;
m_pIGameServiceFrame=NULL;
return;
}
//析构函数
CTableFrame::~CTableFrame()
{
//释放对象
if (m_pITableFrameSink!=NULL)
{
m_pITableFrameSink->Release();
m_pITableFrameSink=NULL;
}
return;
}
//接口查询
void * __cdecl CTableFrame::QueryInterface(const IID & Guid, DWORD dwQueryVer)
{
QUERYINTERFACE(ITableFrame,Guid,dwQueryVer);
QUERYINTERFACE(ITableFrameManager,Guid,dwQueryVer);
QUERYINTERFACE(ITableFrameControl,Guid,dwQueryVer);
QUERYINTERFACE_IUNKNOWNEX(ITableFrameManager,Guid,dwQueryVer);
return NULL;
}
//初始化
bool __cdecl CTableFrame::InitTableFrame(WORD wTableID, tagTableFrameParameter * pTableFrameParameter)
{
//效验参数
ASSERT(pTableFrameParameter!=NULL);
//辅助变量
m_ClientReadyUser.RemoveAll();
//设置变量
m_wTableID=wTableID;
m_pGameServiceAttrib=pTableFrameParameter->pGameServiceAttrib;
m_pGameServiceOption=pTableFrameParameter->pGameServiceOption;
m_wChairCount=pTableFrameParameter->pGameServiceAttrib->wChairCount;
//查询接口
m_pIGameServiceFrame=QUERY_OBJECT_PTR_INTERFACE(pTableFrameParameter->pIGameServiceFrame,IGameServiceFrame);
//错误判断
if (m_pIGameServiceFrame==NULL)
{
ASSERT(FALSE);
return false;
}
//创建桌子
IGameServiceManager * pIGameServiceManager=QUERY_OBJECT_PTR_INTERFACE(pTableFrameParameter->pIGameServiceManager,IGameServiceManager);
m_pITableFrameSink=(ITableFrameSink *)pIGameServiceManager->CreateTableFrameSink(IID_ITableFrameSink,VER_ITableFrameSink);
//错误判断
if (m_pITableFrameSink==NULL)
{
ASSERT(FALSE);
return false;
}
//设置接口
IUnknownEx * pIUnknownEx=QUERY_ME_INTERFACE(IUnknownEx);
if (m_pITableFrameSink->InitTableFrameSink(pIUnknownEx)==false) return false;
//扩展接口
m_pITableUserAction=QUERY_OBJECT_PTR_INTERFACE(m_pITableFrameSink,ITableUserAction);
return true;
}
//游戏状态
bool __cdecl CTableFrame::IsUserPlaying(IServerUserItem * pIServerUserItem)
{
//游戏状态
if (m_bGameStarted==false) return false;
//用户状态
BYTE cbUserStatus=pIServerUserItem->GetUserStatus();
if ((cbUserStatus!=US_PLAY)&&(cbUserStatus!=US_OFFLINE)) return false;
//逻辑判断
WORD wChairID=pIServerUserItem->GetChairID();
return m_pITableFrameSink->IsUserPlaying(wChairID);
}
//离开动作
bool __cdecl CTableFrame::PerformStandUpAction(IServerUserItem * pIServerUserItem)
{
//效验参数
ASSERT(pIServerUserItem!=NULL);
ASSERT(pIServerUserItem->GetTableID()==m_wTableID);
ASSERT(pIServerUserItem->GetChairID()<m_wChairCount);
//变量定义
WORD wChairID=pIServerUserItem->GetChairID();
BYTE cbUserStatus=pIServerUserItem->GetUserStatus();
IServerUserItem * pITableUserItem=GetServerUserItem(wChairID);
//用户处理
if (pITableUserItem==pIServerUserItem)
{
//变量定义
bool bTableLocked=IsTableLocked();
bool bGameStarted=IsGameStarted();
//设置变量
m_bAllowLookon[wChairID]=false;
m_ClientReadyUser.RemoveKey(pIServerUserItem->GetUserID());
//结束游戏
if (IsUserPlaying(pIServerUserItem)==true)
{
//结束游戏
m_pITableFrameSink->OnEventGameEnd(wChairID,pIServerUserItem,GER_USER_LEFT);
//离开判断
tagServerUserData * pUserData=pIServerUserItem->GetUserData();
if ((pUserData->wTableID==INVALID_TABLE)||(pUserData->wChairID==INVALID_CHAIR)) return true;
}
//变量定义
CMD_GF_LookonControl LookonControl;
ZeroMemory(&LookonControl,sizeof(LookonControl));
//设置变量
LookonControl.dwUserID=0L;
LookonControl.bAllowLookon=FALSE;
//发送消息
for (INT_PTR i=0;i<m_LookonUserItemPtr.GetCount();i++)
{
//获取用户
IServerUserItem * pILookonUserItem=m_LookonUserItemPtr[i];
//发送消息
if ((pILookonUserItem->GetChairID()==wChairID)&&(IsClientReady(pILookonUserItem)==true))
{
m_pIGameServiceFrame->SendData(pILookonUserItem,MDM_GF_FRAME,SUB_GF_LOOKON_CONTROL,&LookonControl,sizeof(LookonControl));
}
}
//设置用户
m_pIUserItem[wChairID]=NULL;
pIServerUserItem->SetUserStatus(US_FREE,INVALID_TABLE,INVALID_CHAIR);
m_pIGameServiceFrame->SendUserStatus(pIServerUserItem);
//统计人数
WORD wUserCount=0;
for (WORD i=0;i<m_wChairCount;i++)
{
if (m_pIUserItem[i]!=NULL) wUserCount++;
}
//设置密码
if (wUserCount==0)
{
m_bTableLocked=false;
ZeroMemory(m_szPassword,sizeof(m_szPassword));
}
//踢走旁观
if (wUserCount==0)
{
for (INT_PTR i=0;i<m_LookonUserItemPtr.GetCount();i++)
{
SendGameMessage(m_LookonUserItemPtr[i],TEXT("此游戏桌的所有玩家已经离开了!"),SMT_CLOSE_GAME|SMT_EJECT|SMT_INFO);
}
}
//发送状态
if ((bTableLocked!=IsTableLocked())||(bGameStarted!=IsGameStarted()))
{
m_pIGameServiceFrame->SendTableStatus(m_wTableID);
}
//起立处理
if (m_pITableUserAction!=NULL) m_pITableUserAction->OnActionUserStandUp(wChairID,pIServerUserItem,false);
//变量定义
bool bMatchServer=((m_pGameServiceOption->wServerType&GAME_GENRE_MATCH)!=0);
bool bControlStart=((bMatchServer==true)&&m_pGameServiceOption->cbControlStart==TRUE);
//开始判断
if ((bControlStart==false)&&(StartVerdict()==true))
{
StartGame();
return true;
}
}
else
{
//旁观用户
for (INT_PTR i=0;i<m_LookonUserItemPtr.GetCount();i++)
{
if (pIServerUserItem==m_LookonUserItemPtr[i])
{
//设置变量
m_ClientReadyUser.RemoveKey(pIServerUserItem->GetUserID());
//设置用户
m_LookonUserItemPtr.RemoveAt(i);
pIServerUserItem->SetUserStatus(US_FREE,INVALID_TABLE,INVALID_CHAIR);
m_pIGameServiceFrame->SendUserStatus(pIServerUserItem);
//起立处理
if (m_pITableUserAction!=NULL) m_pITableUserAction->OnActionUserStandUp(wChairID,pIServerUserItem,true);
return true;
}
}
}
return true;
}
//旁观动作
bool __cdecl CTableFrame::PerformLookonAction(WORD wChairID, IServerUserItem * pIServerUserItem,LPCTSTR szPassword)
{
//效验参数
ASSERT(pIServerUserItem!=NULL);
ASSERT(wChairID<m_wChairCount);
ASSERT(pIServerUserItem->GetTableID()==INVALID_TABLE);
ASSERT(pIServerUserItem->GetChairID()==INVALID_CHAIR);
//变量定义
DWORD dwUserRight=pIServerUserItem->GetUserData()->dwUserRight;
BYTE cbMasterOrder=pIServerUserItem->GetUserData()->cbMasterOrder;
//权限判断
if (CUserRight::CanLookon(dwUserRight)==false)
{
//发送消息
SendSitFailedPacket(pIServerUserItem,TEXT("抱歉,你没有进行旁观游戏的权限,若需要帮助,请联系游戏客服咨询!"));
return false;
}
//关闭查询
if ((cbMasterOrder==0L)&&(m_pIGameServiceFrame->IsShallClose()==true))
{
SendSitFailedPacket(pIServerUserItem,TEXT("由于此游戏房间即将暂停服务,玩家不允许再进入游戏桌!"));
return false;
}
//禁止查询
if ((cbMasterOrder==0L)&&(m_pIGameServiceFrame->IsAllowEnterGame()==false))
{
SendSitFailedPacket(pIServerUserItem,TEXT("抱歉,此游戏桌现在不允许玩家进入!"));
return false;
}
//位置判断
if (m_pIUserItem[wChairID]==NULL)
{
SendSitFailedPacket(pIServerUserItem,TEXT("所请求旁观的位置已经没有玩家了,不能旁观!"));
return false;
}
//密码效验
if ((m_bTableLocked==true)&&(cbMasterOrder==0L))
{
//密码效验
if (szPassword==NULL || lstrcmp(m_szPassword,szPassword)!=0)
{
LPCTSTR pszDescribe=TEXT("密码错误,不能加入游戏!");
SendSitFailedPacket(pIServerUserItem,pszDescribe);
return false;
}
}
//状态判断
if ((m_bGameStarted==false)&&(cbMasterOrder==0L))
{
SendSitFailedPacket(pIServerUserItem,TEXT("游戏还没有开始,暂时不能旁观!"));
return false;
}
//设置玩家
m_LookonUserItemPtr.Add(pIServerUserItem);
pIServerUserItem->SetUserStatus(US_LOOKON,m_wTableID,wChairID);
m_pIGameServiceFrame->SendUserStatus(pIServerUserItem);
//旁观处理
if (m_pITableUserAction!=NULL) m_pITableUserAction->OnActionUserSitDown(wChairID,pIServerUserItem,true);
return true;
}
//坐下动作
bool __cdecl CTableFrame::PerformSitDownAction(WORD wChairID, IServerUserItem * pIServerUserItem, LPCTSTR szPassword)
{
//效验参数
ASSERT(pIServerUserItem!=NULL);
ASSERT(wChairID<m_wChairCount);
ASSERT(pIServerUserItem->GetTableID()==INVALID_TABLE);
ASSERT(pIServerUserItem->GetChairID()==INVALID_CHAIR);
//变量定义
const tagUserScore * pUserScore=pIServerUserItem->GetUserScore();
const tagUserRule * pUserRule=pIServerUserItem->GetUserRule(),* pTableUserRule=NULL;
tagServerUserData * pUserData=pIServerUserItem->GetUserData(),* pTableUserData=NULL;
//关闭查询
if ((pUserData->dwMasterRight==0L)&&(m_pIGameServiceFrame->IsShallClose()==true))
{
SendSitFailedPacket(pIServerUserItem,TEXT("由于此游戏房间即将暂停服务,玩家不允许再进入游戏桌!"));
return false;
}
//禁止查询
if ((pUserData->dwMasterRight==0L)&&(m_pIGameServiceFrame->IsAllowEnterGame()==false))
{
SendSitFailedPacket(pIServerUserItem,TEXT("抱歉,此游戏桌现在不允许玩家进入!"));
return false;
}
//位置判断
if (m_pIUserItem[wChairID]!=NULL)
{
//存在判断
if ((m_pIUserItem[wChairID]->GetChairID()==wChairID)&&(m_pIUserItem[wChairID]->GetTableID()==m_wTableID))
{
//发送消息
TCHAR szDescribe[128]=TEXT("");
pTableUserData=m_pIUserItem[wChairID]->GetUserData();
_snprintf(szDescribe,sizeof(szDescribe),TEXT("椅子已经被 [ %s ] 捷足先登了,下次动作要快点了!"),pTableUserData->szAccounts);
SendSitFailedPacket(pIServerUserItem,szDescribe);
}
else
{
ASSERT(FALSE);
}
return false;
}
//游戏状态
if ((m_bGameStarted==true)&&(m_pGameServiceAttrib->cbJoinInGame==FALSE))
{
SendSitFailedPacket(pIServerUserItem,TEXT("游戏已经开始了,暂时不能进入游戏桌!"));
return false;
}
//比赛判断
if (m_pGameServiceOption->wServerType==GAME_GENRE_MATCH)
{
/*if(m_pGameServiceOption->wKindID==)
{
}*/
//比赛权限
if (CUserRight::IsMatchUser(pUserData->dwUserRight)==false)
{
TCHAR szDescribe[128]=TEXT("");
lstrcpyn(szDescribe,TEXT("这是游戏比赛房间,你不是比赛选手,不能坐到此位置上! "),CountArray(szDescribe));
SendSitFailedPacket(pIServerUserItem,szDescribe);
return false;
}
//地址效验
DWORD dwUserIP=pIServerUserItem->GetClientIP();
for (WORD i=0;i<m_wChairCount;i++)
{
if ((m_pIUserItem[i]!=NULL)&&(m_pIUserItem[i]->GetClientIP()==dwUserIP))
{
if (pUserRule->bCheckSameIP)
{
LPCTSTR pszDescribe=TEXT("你设置了不跟相同 IP 地址的玩家游戏,此游戏桌存在与你 IP 地址相同的玩家,不能加入游戏!");
SendSitFailedPacket(pIServerUserItem,pszDescribe);
return false;
}
else
{
LPCTSTR pszDescribe=TEXT("此桌设置了不跟相同 IP 地址的玩家游戏,此游戏桌存在与你 IP 地址相同的玩家,不能加入游戏!");
SendSitFailedPacket(pIServerUserItem,pszDescribe);
return false;
}
}
}
for (WORD i=0;i<m_wChairCount-1;i++)
{
if (m_pIUserItem[i]!=NULL)
{
for (WORD j=i+1;j<m_wChairCount;j++)
{
if ((m_pIUserItem[j]!=NULL)&&(m_pIUserItem[i]->GetClientIP()==m_pIUserItem[j]->GetClientIP()))
{
LPCTSTR pszDescribe=TEXT("你设置了不跟相同 IP 地址的玩家游戏,此游戏桌存在 IP 地址相同的玩家,不能加入游戏!");
SendSitFailedPacket(pIServerUserItem,pszDescribe);
return false;
}
}
}
}
//对局局数
if (m_pGameServiceOption->lMatchDraw>0)
{
LONG lPlayCount=pUserData->UserScoreInfo.lWinCount+pUserData->UserScoreInfo.lLostCount+pUserData->UserScoreInfo.lDrawCount;
if (lPlayCount>=m_pGameServiceOption->lMatchDraw)
{
TCHAR szDescribe[128]=TEXT("");
lstrcpyn(szDescribe,TEXT("恭喜您,您的比赛局数已经完成了,不需要再继续比赛,请耐心等待赛果公布! "),CountArray(szDescribe));
SendSitFailedPacket(pIServerUserItem,szDescribe);
return false;
}
}
}
else
{
//权限判断
if (CUserRight::CanPlay(pUserData->dwUserRight)==false)
{
//发送消息
LPCTSTR pszMessage=TEXT("抱歉,你没有进行游戏的权限,若需要帮助,请联系游戏客服咨询!");
SendSitFailedPacket(pIServerUserItem,pszMessage);
return true;
}
//积分限制//修改
LONG lMaxScore=m_pGameServiceOption->lMaxScore;
LONG lLessScore=m_pGameServiceOption->lLessScore;
if (lLessScore!=0L || lMaxScore>lLessScore)
{
if (pUserData->UserScoreInfo.lScore<lLessScore)
{
//发送消息
TCHAR szDescribe[128]=TEXT("");
if (m_pGameServiceOption->wServerType==GAME_GENRE_GOLD)
{
_snprintf(szDescribe,sizeof(szDescribe),TEXT("加入游戏至少需要 %ld 个金币,您的金币不够,不能加入!"),lLessScore);
}
else
{
_snprintf(szDescribe,sizeof(szDescribe),TEXT("加入游戏至少需要 %ld 个游戏积分,您的积分不够,不能加入!"),lLessScore);
}
SendSitFailedPacket(pIServerUserItem,szDescribe);
return false;
}
if (lMaxScore>lLessScore && lMaxScore<pUserData->UserScoreInfo.lScore)
{
//发送消息
TCHAR szDescribe[128]=TEXT("");
if (m_pGameServiceOption->wServerType==GAME_GENRE_GOLD)
{
_snprintf(szDescribe,sizeof(szDescribe),TEXT("您的金币超过本房间的最大限制额度%ld,请更换游戏房间!"),lMaxScore);
}
else
{
_snprintf(szDescribe,sizeof(szDescribe),TEXT("您的游戏积分超过本房间的最大限制额度%ld,请更换游戏房间!"),lMaxScore);
}
SendSitFailedPacket(pIServerUserItem,szDescribe);
return false;
}
}
//密码效验
if ((m_bTableLocked==true)&&(pUserData->dwMasterRight==0L))
{
if (szPassword==NULL || lstrcmp(m_szPassword,szPassword)!=0)
{
LPCTSTR pszDescribe=TEXT("密码错误,不能加入游戏!");
SendSitFailedPacket(pIServerUserItem,pszDescribe);
return false;
}
}
//积分范围
WORD wWinRate=pIServerUserItem->GetUserWinRate();
WORD wFleeRate=pIServerUserItem->GetUserFleeRate();
for (WORD i=0;i<m_wChairCount;i++)
{
if (m_pIUserItem[i]!=NULL)
{
//获取规则
pTableUserRule=m_pIUserItem[i]->GetUserRule();
//逃率效验
if ((pTableUserRule->bLimitFlee)&&(wFleeRate>pTableUserRule->wFleeRate))
{
TCHAR szDescribe[128]=TEXT("");
_snprintf(szDescribe,sizeof(szDescribe),TEXT("你的逃跑率太高,与 %s 设置的设置不符,不能加入游戏!"),m_pIUserItem[i]->GetAccounts());
SendSitFailedPacket(pIServerUserItem,szDescribe);
return false;
}
//胜率效验
if ((pTableUserRule->bLimitWin)&&(wWinRate<pTableUserRule->wWinRate))
{
TCHAR szDescribe[128]=TEXT("");
_snprintf(szDescribe,sizeof(szDescribe),TEXT("你的胜率太低,与 %s 设置的设置不符,不能加入游戏!"),m_pIUserItem[i]->GetAccounts());
SendSitFailedPacket(pIServerUserItem,szDescribe);
return false;
}
//积分效验
if (pTableUserRule->bLimitScore==true)
{
if (pUserScore->lScore>pTableUserRule->lMaxScore)
{
TCHAR szDescribe[128]=TEXT("");
_snprintf(szDescribe,sizeof(szDescribe),TEXT("你的积分太高,与 %s 设置的设置不符,不能加入游戏!"),m_pIUserItem[i]->GetAccounts());
SendSitFailedPacket(pIServerUserItem,szDescribe);
return false;
}
if (pUserScore->lScore<pTableUserRule->lLessScore)
{
TCHAR szDescribe[128]=TEXT("");
_snprintf(szDescribe,sizeof(szDescribe),TEXT("你的积分太低,与 %s 设置的设置不符,不能加入游戏!"),m_pIUserItem[i]->GetAccounts());
SendSitFailedPacket(pIServerUserItem,szDescribe);
return false;
}
}
}
}
//限制判断
if (m_pGameServiceOption->cbUnSameIPPlay==TRUE)
{
bool bPlay = true;
DWORD dwUserIP=pIServerUserItem->GetClientIP();
for (WORD i=0;i<m_wChairCount;i++)
{
if ((m_pIUserItem[i]!=NULL)&&(m_pIUserItem[i]->GetClientIP()==dwUserIP))
{
bPlay = false;
}
}
if(bPlay)
{
for (WORD i=0;i<m_wChairCount-1;i++)
{
if (m_pIUserItem[i]==NULL)continue;
for (WORD j=i+1;j<m_wChairCount;j++)
{
if ((m_pIUserItem[j]!=NULL)&&(m_pIUserItem[i]->GetClientIP()==m_pIUserItem[j]->GetClientIP()))
{
bPlay = false;
}
}
}
}
if(!bPlay)
{
LPCTSTR pszDescribe=TEXT("本房间设置了相同IP不可坐在同一桌,请选择其它坐位!");
SendSitFailedPacket(pIServerUserItem,pszDescribe);
return false;
}
}
//地址效验
bool bCheckSameIP=pUserRule->bCheckSameIP;
for (WORD i=0;i<m_wChairCount;i++)
{
if (m_pIUserItem[i]!=NULL)
{
pTableUserRule=m_pIUserItem[i]->GetUserRule();
if (pTableUserRule->bCheckSameIP==true)
{
bCheckSameIP=true;
break;
}
}
}
if (bCheckSameIP==true)
{
DWORD dwUserIP=pIServerUserItem->GetClientIP();
for (WORD i=0;i<m_wChairCount;i++)
{
if ((m_pIUserItem[i]!=NULL)&&(m_pIUserItem[i]->GetClientIP()==dwUserIP))
{
if (pUserRule->bCheckSameIP)
{
LPCTSTR pszDescribe=TEXT("你设置了不跟相同 IP 地址的玩家游戏,此游戏桌存在与你 IP 地址相同的玩家,不能加入游戏!");
SendSitFailedPacket(pIServerUserItem,pszDescribe);
return false;
}
else
{
LPCTSTR pszDescribe=TEXT("此桌设置了不跟相同 IP 地址的玩家游戏,此游戏桌存在与你 IP 地址相同的玩家,不能加入游戏!");
SendSitFailedPacket(pIServerUserItem,pszDescribe);
return false;
}
}
}
for (WORD i=0;i<m_wChairCount-1;i++)
{
if (m_pIUserItem[i]!=NULL)
{
for (WORD j=i+1;j<m_wChairCount;j++)
{
if ((m_pIUserItem[j]!=NULL)&&(m_pIUserItem[i]->GetClientIP()==m_pIUserItem[j]->GetClientIP()))
{
LPCTSTR pszDescribe=TEXT("你设置了不跟相同 IP 地址的玩家游戏,此游戏桌存在 IP 地址相同的玩家,不能加入游戏!");
SendSitFailedPacket(pIServerUserItem,pszDescribe);
return false;
}
}
}
}
}
}
//更新密码
WORD wUserCount=0;
for (WORD i=0;i<m_wChairCount;i++)
{
if (m_pIUserItem[i]!=NULL) wUserCount++;
}
if (wUserCount==0 && m_pGameServiceAttrib->wChairCount <= MAX_CHAIR_NORMAL)
{
m_bTableLocked=pUserRule->bPassword;
if (m_bTableLocked==true) lstrcpyn(m_szPassword,pUserRule->szPassword,CountArray(m_szPassword));
}
//设置玩家
m_bAllowLookon[wChairID]=false;
m_pIUserItem[wChairID]=pIServerUserItem;
pIServerUserItem->SetUserStatus(US_SIT,m_wTableID,wChairID);
//发送状态
m_pIGameServiceFrame->SendTableStatus(m_wTableID);
m_pIGameServiceFrame->SendUserStatus(pIServerUserItem);
//坐下处理
if (m_pITableUserAction!=NULL) m_pITableUserAction->OnActionUserSitDown(wChairID,pIServerUserItem,false);
return true;
}
//断线事件
bool __cdecl CTableFrame::OnUserOffLine(WORD wChairID)
{
//效验状态
ASSERT(wChairID<m_wChairCount);
ASSERT(m_pIUserItem[wChairID]!=NULL);
//设置状态
m_wOffLineCount[wChairID]++;
m_pIUserItem[wChairID]->SetUserStatus(US_OFFLINE,m_wTableID,wChairID);
m_pIGameServiceFrame->SendUserStatus(m_pIUserItem[wChairID]);
//设置用户
m_ClientReadyUser.RemoveKey(m_pIUserItem[wChairID]->GetUserID());
//断线处理
if (m_pITableUserAction!=NULL) m_pITableUserAction->OnActionUserOffLine(wChairID,m_pIUserItem[wChairID]);
//设置定时器
DWORD dwTimerID=IDI_OFFLINE+wChairID;
WPARAM wBindParam=m_pIUserItem[wChairID]->GetUserID();
m_pIGameServiceFrame->SetTableTimer(m_wTableID,dwTimerID,90000L,1,wBindParam);
//构造消息
TCHAR szMessage[512]=TEXT("");
_sntprintf(szMessage,sizeof(szMessage),TEXT("[ %s ] 断线了,请耐心等待90秒。"),m_pIUserItem[wChairID]->GetAccounts());
//发送消息
for (WORD i=0;i<MAX_CHAIR;i++)
{
if ((i!=wChairID)&&(m_pIUserItem[i]!=NULL))
{
SendGameMessage(m_pIUserItem[i],szMessage,SMT_INFO);
}
}
return true;
}
//重进事件
bool __cdecl CTableFrame::OnUserReConnect(WORD wChairID)
{
//效验状态
ASSERT(wChairID<m_wChairCount);
ASSERT(m_pIUserItem[wChairID]!=NULL);
//删除定时器
m_pIGameServiceFrame->KillTableTimer(m_wTableID,IDI_OFFLINE+wChairID);
//设置用户
m_pIUserItem[wChairID]->SetUserStatus(US_PLAY,m_wTableID,wChairID);
m_pIGameServiceFrame->SendUserStatus(m_pIUserItem[wChairID]);
//重入处理
if (m_pITableUserAction!=NULL) m_pITableUserAction->OnActionUserReConnect(wChairID,m_pIUserItem[wChairID]);
return true;
}
//请求断线
bool __cdecl CTableFrame::OnUserReqOffLine(WORD wChairID)
{
//效验参数
ASSERT(wChairID<m_wChairCount);
ASSERT(m_pIUserItem[wChairID]!=NULL);
if (wChairID>=m_wChairCount) return false;
if (m_pIUserItem[wChairID]==NULL) return false;
//比赛模式
if (m_pGameServiceOption->wServerType==GAME_GENRE_MATCH)
{
return m_wOffLineCount[wChairID]<5;
}
//常规模式
return m_wOffLineCount[wChairID]<3;
}
//定时器事件
bool __cdecl CTableFrame::OnEventTimer(DWORD dwTimerID, WPARAM wBindParam)
{
//桌子定时器
if (dwTimerID>IDI_MAX_TIME_ID)
{
//断线处理
if ((dwTimerID>=IDI_OFFLINE)&&(dwTimerID<(DWORD)(IDI_OFFLINE+m_wChairCount)))
{
//效验状态
ASSERT(m_bGameStarted==true);
if (m_bGameStarted==false) return false;
//变量定义
WORD wChairID=(WORD)(dwTimerID-IDI_OFFLINE);
IServerUserItem * pIServerUserItem=m_pIUserItem[wChairID];
//断线处理
if (pIServerUserItem!=NULL)
{
//状态判断
if (pIServerUserItem->GetUserID()!=wBindParam) return false;
if (pIServerUserItem->GetUserStatus()!=US_OFFLINE) return false;
//用户起来
PerformStandUpAction(pIServerUserItem);
//清理用户
if (pIServerUserItem->IsActive()==true)
{
m_pIGameServiceFrame->DeleteUserItem(pIServerUserItem);
}
return true;
}
return false;
}
return false;
}
//游戏定时器
return m_pITableFrameSink->OnTimerMessage((WORD)dwTimerID,wBindParam);
}
//游戏事件处理
bool __cdecl CTableFrame::OnEventSocketGame(WORD wSubCmdID, const void * pDataBuffer, WORD wDataSize, IServerUserItem * pIServerUserItem)
{
//效验参数
ASSERT(pIServerUserItem!=NULL);
ASSERT(m_pITableFrameSink!=NULL);
//消息处理
return m_pITableFrameSink->OnGameMessage(wSubCmdID,pDataBuffer,wDataSize,pIServerUserItem);
}
//框架事件处理
bool __cdecl CTableFrame::OnEventSocketFrame(WORD wSubCmdID, const void * pDataBuffer, WORD wDataSize, IServerUserItem * pIServerUserItem)
{
//效验参数
ASSERT(pIServerUserItem!=NULL);
ASSERT(m_pITableFrameSink!=NULL);
//消息处理
bool bSuccess=m_pITableFrameSink->OnFrameMessage(wSubCmdID,pDataBuffer,wDataSize,pIServerUserItem);
if (bSuccess==false)
{
switch (wSubCmdID)
{
case SUB_GF_INFO: //游戏信息
{
//效验参数
ASSERT(wDataSize==sizeof(CMD_GF_Info));
if (wDataSize<sizeof(CMD_GF_Info)) return false;
//变量定义
CMD_GF_Info * pInfo=(CMD_GF_Info *)pDataBuffer;
tagServerUserData * pUserData=pIServerUserItem->GetUserData();
bool bLookonUser=(pUserData->cbUserStatus==US_LOOKON);
//效验状态
ASSERT(pUserData->wChairID<m_wChairCount);
if (pUserData->wChairID>=m_wChairCount) return false;
//设置用户
m_ClientReadyUser[pUserData->dwUserID]=pUserData->dwUserID;
//设置变量
if (bLookonUser==false) m_bAllowLookon[pUserData->wChairID]=pInfo->bAllowLookon?true:false;
//发送配置
CMD_GF_Option Option;
Option.bGameStatus=m_bGameStatus;
Option.bAllowLookon=m_bAllowLookon[pUserData->wChairID]?TRUE:FALSE;
m_pIGameServiceFrame->SendData(pIServerUserItem,MDM_GF_FRAME,SUB_GF_OPTION,&Option,sizeof(Option));
//发送场景
bool bSendSecret=((bLookonUser==false)||(m_bAllowLookon[pUserData->wChairID]==true));
return m_pITableFrameSink->SendGameScene(pUserData->wChairID,pIServerUserItem,m_bGameStatus,bSendSecret);
}
case SUB_GF_USER_READY: //用户同意
{
//变量定义
tagServerUserData * pUserData=pIServerUserItem->GetUserData();
bool bLookonUser=(pUserData->cbUserStatus==US_LOOKON);
//状态效验
ASSERT(bLookonUser==false);
ASSERT(m_pIUserItem[pUserData->wChairID]==pIServerUserItem);
if (bLookonUser==true) return false;
if (pUserData->cbUserStatus>=US_PLAY) return true;
//设置变量
pUserData->cbUserStatus=US_READY;
//同意处理
if (m_pITableUserAction!=NULL)
{
m_pITableUserAction->OnActionUserReady(pUserData->wChairID,m_pIUserItem[pUserData->wChairID],(VOID *)pDataBuffer,wDataSize);
}
//变量定义
bool bMatchServer=((m_pGameServiceOption->wServerType&GAME_GENRE_MATCH)!=0);
bool bControlStart=((bMatchServer==true)&&m_pGameServiceOption->cbControlStart==TRUE);
//开始判断
if ((bControlStart==false)&&(StartVerdict()==true))
{
StartGame();
return true;
}
//发送状态
m_pIGameServiceFrame->SendUserStatus(pIServerUserItem);
return true;
}
case SUB_GF_USER_CHAT: //用户聊天
{
//效验参数
CMD_GF_UserChat * pUserChat=(CMD_GF_UserChat *)pDataBuffer;
ASSERT(wDataSize>=(sizeof(CMD_GF_UserChat)-sizeof(pUserChat->szChatMessage)));
ASSERT(wDataSize==(sizeof(CMD_GF_UserChat)-sizeof(pUserChat->szChatMessage)+pUserChat->wChatLength));
if (wDataSize<(sizeof(CMD_GF_UserChat)-sizeof(pUserChat->szChatMessage))) return false;
if (wDataSize!=(sizeof(CMD_GF_UserChat)-sizeof(pUserChat->szChatMessage)+pUserChat->wChatLength)) return false;
//变量定义
bool bMatchServer=((m_pGameServiceOption->wServerType&GAME_GENRE_MATCH)!=0);
bool bControlStart=((bMatchServer==true)&&m_pGameServiceOption->cbControlStart==TRUE);
//命令过虑
const tagServerUserData * pUserData=pIServerUserItem->GetUserData();
if (pUserData->dwMasterRight!=0L)
{
//比赛开始
if ((bMatchServer==true)&&(bControlStart=true)&&(lstrcmp(pUserChat->szChatMessage,TEXT("/:StartGame"))==0))
{
if (StartVerdict()==true) StartGame();
return true;
}
//游戏解散
if (lstrcmp(pUserChat->szChatMessage,TEXT("/:DismissGame"))==0)
{
DismissGame();
return true;
}
}
//比赛旁观
if (pUserData->dwMasterRight==0L)
{
if ((bMatchServer==true)&&(pIServerUserItem->GetUserStatus()==US_LOOKON))
{
LPCTSTR pszMessage=TEXT("为了不影响比赛选手比赛,旁观的用户禁止发言!");
SendGameMessage(pIServerUserItem,pszMessage,SMT_EJECT|SMT_INFO);
return true;
}
}
//权限判断
if (CUserRight::CanGameChat(pIServerUserItem->GetUserData()->dwUserRight)==false)
{
LPCTSTR pszMessage=TEXT("你暂时没有发送房间消息的权限,只能与管理员私聊!");
SendGameMessage(pIServerUserItem,pszMessage,SMT_EJECT|SMT_INFO);
return true;
}
//状态查询
if ((pUserData->dwMasterRight==0L)&&(m_pIGameServiceFrame->IsAllowGameChat()==false))
{
LPCTSTR pszMessage=TEXT("抱歉,本游戏房间不允许发送聊天信息!");
SendGameMessage(pIServerUserItem,pszMessage,SMT_EJECT|SMT_INFO);
return true;
}
//游戏玩家
for (WORD i=0;i<m_wChairCount;i++)
{
if ((m_pIUserItem[i]!=NULL)&&(IsClientReady(m_pIUserItem[i])==true))
{
m_pIGameServiceFrame->SendData(m_pIUserItem[i],MDM_GF_FRAME,SUB_GF_USER_CHAT,pUserChat,wDataSize);
}
}
//旁观玩家
for (INT_PTR i=0;i<m_LookonUserItemPtr.GetCount();i++)
{
if (IsClientReady(m_LookonUserItemPtr[i])==true)
{
m_pIGameServiceFrame->SendData(m_LookonUserItemPtr[i],MDM_GF_FRAME,SUB_GF_USER_CHAT,pUserChat,wDataSize);
}
}
return true;
}
case SUB_GF_LOOKON_CONTROL: //旁观控制
{
//效验参数
ASSERT(wDataSize==sizeof(CMD_GF_LookonControl));
if (wDataSize<sizeof(CMD_GF_LookonControl)) return false;
//用户效验
tagServerUserData * pUserData=pIServerUserItem->GetUserData();
if (pUserData->cbUserStatus==US_LOOKON) return false;
//变量定义
CMD_GF_LookonControl * pLookonControl=(CMD_GF_LookonControl *)pDataBuffer;
//旁观处理
if (pLookonControl->dwUserID!=0L)
{
for (INT_PTR i=0;i<m_LookonUserItemPtr.GetCount();i++)
{
//获取用户
IServerUserItem * pILookonUserItem=m_LookonUserItemPtr[i];
if (pILookonUserItem->GetUserID()!=pLookonControl->dwUserID) continue;
if (pILookonUserItem->GetChairID()!=pIServerUserItem->GetChairID()) continue;
//构造消息
CMD_GF_LookonControl LookonControl;
LookonControl.dwUserID=pLookonControl->dwUserID;
LookonControl.bAllowLookon=pLookonControl->bAllowLookon;
//发送消息
if (IsClientReady(pILookonUserItem)==true)
{
m_pIGameServiceFrame->SendData(pILookonUserItem,MDM_GF_FRAME,SUB_GF_LOOKON_CONTROL,&LookonControl,sizeof(LookonControl));
}
break;
}
}
else
{
//设置判断
bool bAllowLookon=(pLookonControl->bAllowLookon==TRUE)?true:false;
if (bAllowLookon==m_bAllowLookon[pUserData->wChairID]) return true;
//设置变量
m_bAllowLookon[pUserData->wChairID]=bAllowLookon;
//构造消息
CMD_GF_LookonControl LookonControl;
LookonControl.dwUserID=pLookonControl->dwUserID;
LookonControl.bAllowLookon=pLookonControl->bAllowLookon;
//发送消息
for (INT_PTR i=0;i<m_LookonUserItemPtr.GetCount();i++)
{
//获取用户
IServerUserItem * pILookonUserItem=m_LookonUserItemPtr[i];
if (pILookonUserItem->GetChairID()!=pIServerUserItem->GetChairID()) continue;
//发送消息
if (IsClientReady(pILookonUserItem)==true)
{
m_pIGameServiceFrame->SendData(pILookonUserItem,MDM_GF_FRAME,SUB_GF_LOOKON_CONTROL,&LookonControl,sizeof(LookonControl));
}
}
}
return true;
}
case SUB_GF_KICK_TABLE_USER: //踢走用户
{
//效验参数
ASSERT(wDataSize==sizeof(CMD_GF_KickTableUser));
if (wDataSize!=sizeof(CMD_GF_KickTableUser)) return false;
//效验用户
tagServerUserData * pUserData=pIServerUserItem->GetUserData();
if((pUserData->cbMemberOrder==0)&&(pUserData->cbMasterOrder==0)) return false;
//游戏判断
if ( pUserData->cbMasterOrder==0 && m_pGameServiceAttrib->wChairCount > MAX_CHAIR_NORMAL )
{
SendGameMessage(pIServerUserItem, TEXT("对不起,此房间不可以踢人!"), SMT_EJECT|SMT_INFO);
return true;
}
//变量定义
CMD_GF_KickTableUser * pKickTableUser=(CMD_GF_KickTableUser *)pDataBuffer;
//查找用户
IServerUserItem * pIKickUserItem=NULL;
for (WORD i=0;i<m_wChairCount;i++)
{
if ((m_pIUserItem[i]!=NULL)&&(m_pIUserItem[i]->GetUserID()==pKickTableUser->dwUserID))
{
pIKickUserItem=m_pIUserItem[i];
break;
}
}
if (pIKickUserItem==NULL)
{
IServerUserItem * pTempUserItem=NULL;
for (INT_PTR i=0;i<m_LookonUserItemPtr.GetCount();i++)
{
pTempUserItem=m_LookonUserItemPtr[i];
if (pTempUserItem->GetUserID()==pKickTableUser->dwUserID)
{
pIKickUserItem=pTempUserItem;
break;
}
}
}
//踢走用户
if (pIKickUserItem!=NULL)
{
//变量定义
tagServerUserData * pKickUserData=pIKickUserItem->GetUserData();
tagServerUserData * pActionUserData=pIServerUserItem->GetUserData();
//状态判断
if (pKickUserData->cbUserStatus>=US_PLAY) return true;
//权限判断
bool bKickUser=false;
if (bKickUser==false) bKickUser=(pActionUserData->cbMasterOrder>pKickUserData->cbMasterOrder);
if (m_pGameServiceAttrib->wChairCount<=MAX_CHAIR_NORMAL && bKickUser==false)
bKickUser=(pActionUserData->cbMemberOrder>pKickUserData->cbMemberOrder);
if ( pActionUserData->cbMasterOrder<pKickUserData->cbMasterOrder ) bKickUser= false;
//踢走用户
if (bKickUser==true)
{
//防踢判断
tagServerUserData *pKickUserData = pIKickUserItem->GetUserData();
DWORD dwPassTime = pKickUserData->PropertyInfo[PROP_KICK].dwConsumedCount ;
DWORD dwUseableTime = pKickUserData->PropertyInfo[PROP_KICK].dwPropCount;
if ( 0 < dwUseableTime && dwPassTime <= dwUseableTime && pUserData->cbMasterOrder==0 )
{
TCHAR szDescribe[128]=TEXT("");
_snprintf(szDescribe,sizeof(szDescribe),TEXT("[ %s ] 使用了防踢卡,踢人失败!"),pKickUserData->szAccounts);
SendGameMessage(pIServerUserItem,szDescribe,SMT_EJECT|SMT_INFO);
_snprintf(szDescribe,sizeof(szDescribe),TEXT("由于您使用了防踢卡,成功阻止了[ %s ]对您的踢人动作!"),pUserData->szAccounts);
SendGameMessage(pIKickUserItem,szDescribe,SMT_EJECT|SMT_INFO);
return true;
}
TCHAR szDescribe[128]=TEXT("");
_snprintf(szDescribe,sizeof(szDescribe),TEXT("您被 [ %s ] 踢出游戏桌!"),pUserData->szAccounts);
SendGameMessage(pIKickUserItem,szDescribe,SMT_EJECT|SMT_INFO|SMT_CLOSE_GAME);
}
}
return true;
}
}
}
return bSuccess;
}
//视频事件处理
bool CTableFrame::OnEventSocketVideo(WORD wSubCmdID, const void * pDataBuffer, WORD wDataSize, IServerUserItem * pIServerUserItem)
{
switch (wSubCmdID)
{
case SUB_GF_C_VIDEO_CONFIG: //视频配置
{
//效验数据
ASSERT(wDataSize==sizeof(CMD_C_VideoConfig));
if (wDataSize!=sizeof(CMD_C_VideoConfig)) return false;
//变量定义
CMD_C_VideoConfig * pVideoConfig=(CMD_C_VideoConfig *)pDataBuffer;
//查找用户
IServerUserItem * pIRemoteUserItem=NULL;
for (WORD i=0;i<m_wChairCount;i++)
{
if ((m_pIUserItem[i]!=NULL)&&(m_pIUserItem[i]->GetUserID()==pVideoConfig->dwRemoteUserID))
{
pIRemoteUserItem=m_pIUserItem[i];
break;
}
}
//消息处理
if (pIRemoteUserItem!=NULL)
{
//变量定义
CMD_S_VideoConfig VideoConfig;
ZeroMemory(&VideoConfig,sizeof(VideoConfig));
//设置变量
VideoConfig.wNatPort=pVideoConfig->wNatPort;
VideoConfig.dwNatAddr=pVideoConfig->dwNatAddr;
VideoConfig.wLocalPort=pVideoConfig->wLocalPort;
VideoConfig.dwLocalAddr=pVideoConfig->dwLocalAddr;
VideoConfig.dwLocalUserID=pIServerUserItem->GetUserID();
//发送消息
m_pIGameServiceFrame->SendData(pIRemoteUserItem,MDM_GF_VIDEO,SUB_GF_S_VIDEO_CONFIG,&VideoConfig,sizeof(VideoConfig));
}
return true;
}
case SUB_GF_C_VIDEO_OPEN: //打开视频
{
//合法验证
WORD wOpenUserChairID=pIServerUserItem->GetChairID();
if (pIServerUserItem->GetUserStatus()==US_LOOKON) return false;
//变量定义
CMD_S_VideoOpen VideoOpen;
ZeroMemory(&VideoOpen,sizeof(VideoOpen));
//设置变量
VideoOpen.wOpenUser=wOpenUserChairID;
//发送消息
for (WORD i=0;i<m_wChairCount;i++)
{
//获取玩家
IServerUserItem * pTargetServerUserItem=GetServerUserItem(i);
if ((pTargetServerUserItem==NULL)||(pIServerUserItem==pTargetServerUserItem)) continue;
//发送消息
m_pIGameServiceFrame->SendData(pTargetServerUserItem,MDM_GF_VIDEO,SUB_GF_S_VIDEO_OPEN,&VideoOpen,sizeof(VideoOpen));
}
return true;
}
case SUB_GF_C_VIDEO_CLOSE: //关闭视频
{
//合法验证
WORD wCloseUserChairID=pIServerUserItem->GetChairID();
if (pIServerUserItem->GetUserStatus()==US_LOOKON) return false;
//变量定义
CMD_S_VideoClose VideoClose;
ZeroMemory( &VideoClose,sizeof(VideoClose));
//设置变量
VideoClose.wCloseUser=wCloseUserChairID;
//发送消息
for (WORD i=0;i<m_wChairCount;i++)
{
//获取玩家
IServerUserItem * pTargetServerUserItem=GetServerUserItem(i);
if ((pTargetServerUserItem==NULL)||(pIServerUserItem==pTargetServerUserItem)) continue;
//发送消息
m_pIGameServiceFrame->SendData(pTargetServerUserItem,MDM_GF_VIDEO,SUB_GF_S_VIDEO_CLOSE,&VideoClose,sizeof(VideoClose));
}
return true;
}
}
return true;
}
//枚举用户
IServerUserItem * __cdecl CTableFrame::EnumLookonUserItem(WORD wIndex)
{
if (wIndex>=m_LookonUserItemPtr.GetCount()) return NULL;
return m_LookonUserItemPtr[wIndex];
}
//获取用户
IServerUserItem * __cdecl CTableFrame::GetServerUserItem(WORD wChairID)
{
ASSERT(wChairID<m_wChairCount);
if (wChairID>=m_wChairCount) return NULL;
return m_pIUserItem[wChairID];
}
//设置定时器
bool __cdecl CTableFrame::SetGameTimer(DWORD dwTimerID, DWORD dwElapse, DWORD dwRepeat, WPARAM wBindParam)
{
//效验参数
ASSERT(dwTimerID<=IDI_MAX_TIME_ID);
if (dwTimerID>IDI_MAX_TIME_ID) return false;
//设置定时器
return m_pIGameServiceFrame->SetTableTimer(m_wTableID,dwTimerID,dwElapse,dwRepeat,wBindParam);
}
//删除定时器
bool __cdecl CTableFrame::KillGameTimer(DWORD dwTimerID)
{
//效验参数
ASSERT(dwTimerID<=IDI_MAX_TIME_ID);
if (dwTimerID>IDI_MAX_TIME_ID) return false;
//删除定时器
return m_pIGameServiceFrame->KillTableTimer(m_wTableID,dwTimerID);
}
//发送数据
bool __cdecl CTableFrame::SendUserData(IServerUserItem * pIServerUserItem, WORD wSubCmdID)
{
//用户判断
if (IsClientReady(pIServerUserItem)==false) return false;
//发送消息
m_pIGameServiceFrame->SendData(pIServerUserItem,MDM_GF_GAME,wSubCmdID);
return true;
}
//发送数据
bool __cdecl CTableFrame::SendUserData(IServerUserItem * pIServerUserItem, WORD wSubCmdID, void * pData, WORD wDataSize)
{
//用户判断
if (IsClientReady(pIServerUserItem)==false) return false;
//发送消息
m_pIGameServiceFrame->SendData(pIServerUserItem,MDM_GF_GAME,wSubCmdID,pData,wDataSize);
return true;
}
//发送数据
bool __cdecl CTableFrame::SendTableData(WORD wChairID, WORD wSubCmdID)
{
//群发用户
if (wChairID==INVALID_CHAIR)
{
for (WORD i=0;i<m_wChairCount;i++)
{
if ((m_pIUserItem[i]!=NULL)&&(IsClientReady(m_pIUserItem[i])==true))
{
m_pIGameServiceFrame->SendData(m_pIUserItem[i],MDM_GF_GAME,wSubCmdID);
}
}
return true;
}
//单一发送
if ((wChairID<m_wChairCount)&&(m_pIUserItem[wChairID]!=NULL))
{
if (IsClientReady(m_pIUserItem[wChairID])==true)
{
m_pIGameServiceFrame->SendData(m_pIUserItem[wChairID],MDM_GF_GAME,wSubCmdID);
return true;
}
}
return false;
}
//发送数据
bool __cdecl CTableFrame::SendTableData(WORD wChairID, WORD wSubCmdID, void * pData, WORD wDataSize)
{
//群发用户
if (wChairID==INVALID_CHAIR)
{
for (WORD i=0;i<m_wChairCount;i++)
{
if ((m_pIUserItem[i]!=NULL)&&(IsClientReady(m_pIUserItem[i])==true))
{
m_pIGameServiceFrame->SendData(m_pIUserItem[i],MDM_GF_GAME,wSubCmdID,pData,wDataSize);
}
}
return true;
}
//单一发送
if ((wChairID<m_wChairCount)&&(m_pIUserItem[wChairID]!=NULL))
{
if (IsClientReady(m_pIUserItem[wChairID])==true)
{
m_pIGameServiceFrame->SendData(m_pIUserItem[wChairID],MDM_GF_GAME,wSubCmdID,pData,wDataSize);
return true;
}
}
return false;
}
//发送数据
bool __cdecl CTableFrame::SendLookonData(WORD wChairID, WORD wSubCmdID)
{
for (INT_PTR i=0;i<m_LookonUserItemPtr.GetCount();i++)
{
//获取用户
IServerUserItem * pIServerUserItem=m_LookonUserItemPtr[i];
//发送消息
if (IsClientReady(pIServerUserItem)==true)
{
//单一发送
if (wChairID<m_wChairCount)
{
tagServerUserData * pUserData=pIServerUserItem->GetUserData();
if (pUserData->wChairID==wChairID) m_pIGameServiceFrame->SendData(pIServerUserItem,MDM_GF_GAME,wSubCmdID);
}
//批量发送
if (wChairID==INVALID_CHAIR) m_pIGameServiceFrame->SendData(pIServerUserItem,MDM_GF_GAME,wSubCmdID);
}
}
return true;
}
//发送数据
bool __cdecl CTableFrame::SendLookonData(WORD wChairID, WORD wSubCmdID, void * pData, WORD wDataSize)
{
for (INT_PTR i=0;i<m_LookonUserItemPtr.GetCount();i++)
{
//获取用户
IServerUserItem * pIServerUserItem=m_LookonUserItemPtr[i];
//发送消息
if (IsClientReady(pIServerUserItem)==true)
{
//单一发送
if (wChairID<m_wChairCount)
{
tagServerUserData * pUserData=pIServerUserItem->GetUserData();
if (pUserData->wChairID==wChairID) m_pIGameServiceFrame->SendData(pIServerUserItem,MDM_GF_GAME,wSubCmdID,pData,wDataSize);
}
//批量发送
if (wChairID==INVALID_CHAIR) m_pIGameServiceFrame->SendData(pIServerUserItem,MDM_GF_GAME,wSubCmdID,pData,wDataSize);
}
}
return true;
}
//发送房间消息
bool __cdecl CTableFrame::SendRoomMessage(IServerUserItem * pIServerUserItem, LPCTSTR lpszMessage, WORD wMessageType)
{
//用户判断
if (IsClientReady(pIServerUserItem)==false) return false;
//构造数据包
CMD_GR_Message Message;
Message.wMessageType=wMessageType;
lstrcpyn(Message.szContent,lpszMessage,CountArray(Message.szContent));
Message.wMessageLength=CountStringBuffer(Message.szContent);
//发送数据
WORD wSendSize=sizeof(Message)-sizeof(Message.szContent)+Message.wMessageLength*sizeof(TCHAR);
m_pIGameServiceFrame->SendData(pIServerUserItem,MDM_GR_SYSTEM,SUB_GR_MESSAGE,&Message,wSendSize);
return true;
}
//发送游戏消息
bool __cdecl CTableFrame::SendGameMessage(IServerUserItem * pIServerUserItem, LPCTSTR lpszMessage, WORD wMessageType)
{
//用户判断
if (IsClientReady(pIServerUserItem)==false) return false;
//构造数据包
CMD_GF_Message Message;
Message.wMessageType=wMessageType;
lstrcpyn(Message.szContent,lpszMessage,CountArray(Message.szContent));
Message.wMessageLength=CountStringBuffer(Message.szContent);
//发送数据
WORD wSendSize=sizeof(Message)-sizeof(Message.szContent)+Message.wMessageLength*sizeof(TCHAR);
m_pIGameServiceFrame->SendData(pIServerUserItem,MDM_GF_FRAME,SUB_GF_MESSAGE,&Message,wSendSize);
return true;
}
//解散游戏
bool __cdecl CTableFrame::DismissGame()
{
//状态判断
ASSERT(m_bGameStarted==true);
if (m_bGameStarted==false) return false;
//结束游戏
if ((m_bGameStarted==true)&&(m_pITableFrameSink->OnEventGameEnd(INVALID_CHAIR,NULL,GER_DISMISS)==false))
{
ASSERT(FALSE);
return false;
}
//设置状态
if (m_bGameStarted==false)
{
//设置变量
m_bGameStarted=false;
//发送状态
m_pIGameServiceFrame->SendTableStatus(m_wTableID);
}
return true;
}
//结束游戏
bool __cdecl CTableFrame::ConcludeGame()
{
//设置状态
m_bGameStarted=false;
m_bGameStatus=GS_FREE;
//设置变量
m_dwTimeStart=0L;
ZeroMemory(m_wOffLineCount,sizeof(m_wOffLineCount));
//分数信息
m_lGameTaxScore=0L;
ZeroMemory(m_ScoreInfo,sizeof(m_ScoreInfo));
ZeroMemory(m_dwPlayerID,sizeof(m_dwPlayerID));
//重置桌子
m_pITableFrameSink->RepositTableFrameSink();
//设置用户
for (WORD i=0;i<m_wChairCount;i++)
{
if (m_pIUserItem[i]!=NULL)
{
tagServerUserData * pUserData=m_pIUserItem[i]->GetUserData();
if (pUserData->cbUserStatus!=US_OFFLINE) pUserData->cbUserStatus=US_SIT;
}
}
//断线处理
for (WORD i=0;i<m_wChairCount;i++)
{
if (m_pIUserItem[i]!=NULL)
{
//获取用户
IServerUserItem * pIServerUserItem=m_pIUserItem[i];
if (pIServerUserItem->GetUserStatus()!=US_OFFLINE) continue;
//删除定时器
DWORD dwTimerID=IDI_OFFLINE+i;
m_pIGameServiceFrame->KillTableTimer(m_wTableID,dwTimerID);
//用户离开
PerformStandUpAction(pIServerUserItem);
//清理用户
if (pIServerUserItem->IsActive()==true)
{
m_pIGameServiceFrame->DeleteUserItem(pIServerUserItem);
}
}
}
//赛局判断
if ((m_pGameServiceOption->wServerType&GAME_GENRE_MATCH)&&(m_pGameServiceOption->lMatchDraw>0))
{
for (WORD i=0;i<m_wChairCount;i++)
{
if (m_pIUserItem[i]!=NULL)
{
//变量定义
IServerUserItem * pIServerUserItem=m_pIUserItem[i];
tagServerUserData * pUserData=pIServerUserItem->GetUserData();
LONG lPlayCount=pUserData->UserScoreInfo.lWinCount+pUserData->UserScoreInfo.lLostCount+pUserData->UserScoreInfo.lDrawCount;
//比赛判断
if (lPlayCount>=m_pGameServiceOption->lMatchDraw)
{
//发送消息
TCHAR szDescribe[256]=TEXT("");
lstrcpyn(szDescribe,TEXT("恭喜你,你的比赛局数已经完成了,不需要再继续比赛,请耐心等待赛果公布! "),CountArray(szDescribe));
SendGameMessage(pIServerUserItem,szDescribe,SMT_EJECT|SMT_INFO|SMT_CLOSE_GAME);
//用户起立
PerformStandUpAction(pIServerUserItem);
}
}
}
}
//检测积分//修改
LONG lMaxScore=m_pGameServiceOption->lMaxScore;
LONG lLessScore=m_pGameServiceOption->lLessScore;
if (lLessScore!=0L || lMaxScore>lLessScore)
{
for (WORD i=0;i<m_wChairCount;i++)
{
if (m_pIUserItem[i]!=NULL)
{
//获取用户
IServerUserItem * pIServerUserItem=m_pIUserItem[i];
tagServerUserData * pUserData=pIServerUserItem->GetUserData();
//最少判断
if (pUserData->UserScoreInfo.lScore<lLessScore)
{
//发送信息
TCHAR szDescribe[256]=TEXT("");
if (m_pGameServiceOption->wServerType==GAME_GENRE_GOLD)
{
_snprintf(szDescribe,sizeof(szDescribe),TEXT("您的金币少于 %ld,不能继续游戏!"),lLessScore);
}
else
{
_snprintf(szDescribe,sizeof(szDescribe),TEXT("您的游戏积分少于 %ld,不能继续游戏!"),lLessScore);
}
SendGameMessage(pIServerUserItem,szDescribe,SMT_EJECT|SMT_INFO|SMT_CLOSE_GAME);
//弹起用户
PerformStandUpAction(pIServerUserItem);
}
//最大判断
else if (lMaxScore>lLessScore && lMaxScore<pUserData->UserScoreInfo.lScore)
{
//发送信息
TCHAR szDescribe[256]=TEXT("");
if (m_pGameServiceOption->wServerType==GAME_GENRE_GOLD)
{
_snprintf(szDescribe,sizeof(szDescribe),TEXT("您的金币超过本房间的最大限制额度%ld,请更换游戏房间!"),lMaxScore);
}
else
{
_snprintf(szDescribe,sizeof(szDescribe),TEXT("您的游戏积分超过本房间的最大限制额度%ld,请更换游戏房间!"),lMaxScore);
}
SendGameMessage(pIServerUserItem,szDescribe,SMT_EJECT|SMT_INFO|SMT_CLOSE_GAME);
//弹起用户
PerformStandUpAction(pIServerUserItem);
}
}
}
}
//关闭判断
if ((m_pIGameServiceFrame->IsAllowEnterGame()==false)||(m_pIGameServiceFrame->IsShallClose()==true))
{
for (WORD i=0;i<m_wChairCount;i++)
{
if (m_pIUserItem[i]!=NULL)
{
//获取用户
IServerUserItem * pIServerUserItem=m_pIUserItem[i];
tagServerUserData * pUserData=pIServerUserItem->GetUserData();
//用户判断
if (pUserData->dwMasterRight==0L)
{
//用户起立
LPCTSTR pszMessage=TEXT("请注意,游戏房间即将关闭或者不允许玩家进入,请你离开游戏桌子!");
SendGameMessage(pIServerUserItem,pszMessage,SMT_EJECT|SMT_INFO|SMT_CLOSE_GAME);
PerformStandUpAction(pIServerUserItem);
continue;
}
}
}
}
//用户状态
for (WORD i=0;i<m_wChairCount;i++)
{
if (m_pIUserItem[i]!=NULL)
{
m_pIGameServiceFrame->SendUserStatus(m_pIUserItem[i]);
}
}
//发送状态
m_pIGameServiceFrame->SendTableStatus(m_wTableID);
return true;
}
//写入积分
bool __cdecl CTableFrame::WriteUserScore(WORD wChairID, LONG lScore, LONG lRevenue, enScoreKind ScoreKind, LONG lPlayTimeCount)
{
//效验参数
ASSERT(wChairID<m_wChairCount);
ASSERT(m_pIUserItem[wChairID]!=NULL);
if (wChairID>=m_wChairCount) return false;
if (m_pIUserItem[wChairID]==NULL) return false;
//设置变量
m_ScoreInfo[wChairID].lScore=lScore;
m_ScoreInfo[wChairID].lRevenue=lRevenue;
m_ScoreInfo[wChairID].ScoreKind=ScoreKind;
//写入积分
WriteUserScore(m_pIUserItem[wChairID],lScore,lRevenue,ScoreKind, lPlayTimeCount);
return true;
}
//写入积分
bool __cdecl CTableFrame::WriteUserScore(IServerUserItem * pIServerUserItem, LONG lScore, LONG lRevenue, enScoreKind ScoreKind, LONG lPlayTimeCount)
{
//效验参数
ASSERT(pIServerUserItem!=NULL);
if (pIServerUserItem==NULL) return false;
//变量定义
tagScoreInfo ScoreInfo;
ZeroMemory(&ScoreInfo,sizeof(ScoreInfo));
//道具判断
if ( m_pGameServiceOption->wServerType != GAME_GENRE_GOLD && m_pGameServiceOption->wServerType != GAME_GENRE_MATCH )
{
tagServerUserData *pServerUserData = pIServerUserItem->GetUserData();
CString strMessage;
if ( 0 < lScore )
{
DWORD lPassedTime, lUseableTime;
BYTE cbPropertyType = PROP_DOUBLE;
lPassedTime = pServerUserData->PropertyInfo[PROP_DOUBLE].dwConsumedCount;
lUseableTime = pServerUserData->PropertyInfo[PROP_DOUBLE].dwPropCount;
if ( lUseableTime == 0 || lUseableTime <= lPassedTime )
{
lPassedTime = pServerUserData->PropertyInfo[PROP_FOURDOLD].dwConsumedCount;
lUseableTime = pServerUserData->PropertyInfo[PROP_FOURDOLD].dwPropCount;
cbPropertyType = PROP_FOURDOLD;
}
if ( 0 < lUseableTime && lPassedTime <= lUseableTime )
{
if ( cbPropertyType == PROP_DOUBLE )
{
lScore *= 2;
strMessage.Format(TEXT("[ %s ] 使用了[ 双倍积分卡 ],得分翻倍!)"),
pServerUserData->szAccounts);
}
else if ( cbPropertyType == PROP_FOURDOLD )
{
lScore *= 4;
strMessage.Format(TEXT("[ %s ] 使用了[ 四倍积分卡 ],得分翻四倍!)"),
pServerUserData->szAccounts);
}
}
}
else if ( lScore < 0 )
{
DWORD lPassedTime, lUseableTime;
lPassedTime = pServerUserData->PropertyInfo[PROP_SHIELD].dwConsumedCount;
lUseableTime = pServerUserData->PropertyInfo[PROP_SHIELD].dwPropCount;
if ( 0 < lUseableTime && lPassedTime <= lUseableTime )
{
lScore = 0;
strMessage.Format(TEXT("[ %s ] 使用了[ 护身符卡 ],积分不变!"), pServerUserData->szAccounts);
}
}
if ( ! strMessage.IsEmpty() )
{
//游戏玩家
for (WORD i=0;i<m_wChairCount;i++)
{
if ((m_pIUserItem[i]!=NULL)&&(IsClientReady(m_pIUserItem[i])==true))
{
SendGameMessage(m_pIUserItem[i], strMessage, SMT_INFO);
}
}
//旁观玩家
for (INT_PTR i=0;i<m_LookonUserItemPtr.GetCount();i++)
{
if (IsClientReady(m_LookonUserItemPtr[i])==true)
{
SendGameMessage(m_LookonUserItemPtr[i], strMessage, SMT_INFO);
}
}
}
}
//设置变量
ScoreInfo.lScore=lScore;
ScoreInfo.lRevenue=lRevenue;
ScoreInfo.ScoreKind=ScoreKind;
//游戏税收
m_lGameTaxScore+=lRevenue;
//修改积分
if ( lPlayTimeCount == -1 )
{
DWORD dwPlayTimeCount=0L;
if (m_dwTimeStart!=0L) dwPlayTimeCount=(DWORD)time(NULL)-m_dwTimeStart;
pIServerUserItem->WriteScore(ScoreInfo,dwPlayTimeCount);
}
else
{
pIServerUserItem->WriteScore(ScoreInfo,DWORD(lPlayTimeCount));
}
//发送信息
m_pIGameServiceFrame->SendUserScore(pIServerUserItem);
//存储积分
if ((m_pGameServiceOption->wServerType==GAME_GENRE_GOLD)&&(m_pGameServiceOption->lRestrictScore>0L))
{
//还原积分
tagServerUserData * pServerUserData=pIServerUserItem->GetUserData();
pServerUserData->UserScoreInfo.lScore+=pServerUserData->lStorageScore;
pServerUserData->lStorageScore=0L;
//存储积分
if (pServerUserData->UserScoreInfo.lScore>m_pGameServiceOption->lRestrictScore)
{
LONG lUserScore=pServerUserData->UserScoreInfo.lScore;
pServerUserData->UserScoreInfo.lScore=m_pGameServiceOption->lRestrictScore;
pServerUserData->lStorageScore=lUserScore-m_pGameServiceOption->lRestrictScore;
}
}
return true;
}
//发送场景
bool __cdecl CTableFrame::SendGameScene(IServerUserItem * pIServerUserItem, void * pData, WORD wDataSize)
{
//系统消息
TCHAR szMessage[256]=TEXT("");
if (m_pGameServiceOption->wServerType==GAME_GENRE_MATCH)
{
_snprintf(szMessage,sizeof(szMessage),TEXT("亲爱的用户,欢迎您来到“%s”比赛游戏房间,祝比赛选手赛出水平,取得好的成绩!"),m_pGameServiceAttrib->szKindName);
SendGameMessage(pIServerUserItem,szMessage,SMT_INFO);
}
else
{
_snprintf(szMessage,sizeof(szMessage),TEXT("亲爱的用户,欢迎您来到“%s”,欢迎你多提宝贵建议!"),m_pGameServiceAttrib->szKindName);
SendGameMessage(pIServerUserItem,szMessage,SMT_INFO);
}
//安全提示
if ((pIServerUserItem->GetUserStatus()!=US_LOOKON)&&(m_bAllowLookon[pIServerUserItem->GetChairID()]==true))
{
lstrcpyn(szMessage,TEXT("请注意,您设置了允许所有玩家观看您游戏。"),CountArray(szMessage));
SendGameMessage(pIServerUserItem,szMessage,SMT_INFO);
}
//发送场景
m_pIGameServiceFrame->SendData(pIServerUserItem,MDM_GF_FRAME,SUB_GF_SCENE,pData,wDataSize);
return true;
}
//开始游戏
bool __cdecl CTableFrame::StartGame()
{
//效验状态
ASSERT(m_bGameStarted==false);
if (m_bGameStarted==true) return false;
//设置变量
m_bGameStarted=true;
m_dwTimeStart=(DWORD)time(NULL);
ZeroMemory(m_wOffLineCount,sizeof(m_wOffLineCount));
//记录分数
m_lGameTaxScore=0L;
ZeroMemory(m_ScoreInfo,sizeof(m_ScoreInfo));
ZeroMemory(m_dwPlayerID,sizeof(m_dwPlayerID));
//设置玩家
tagServerUserData * pUserData=NULL;
for (WORD i=0;i<m_wChairCount;i++)
{
if (m_pIUserItem[i]!=NULL)
{
pUserData=m_pIUserItem[i]->GetUserData();
pUserData->cbUserStatus=US_PLAY;
m_dwPlayerID[i]=pUserData->dwUserID;
}
}
//发送状态
m_pIGameServiceFrame->SendTableStatus(m_wTableID);
//用户状态
for (WORD i=0;i<m_wChairCount;i++)
{
if (m_pIUserItem[i]!=NULL)
{
m_pIGameServiceFrame->SendUserStatus(m_pIUserItem[i]);
}
}
//通知事件
m_pITableFrameSink->OnEventGameStart();
return true;
}
//判断开始
bool __cdecl CTableFrame::StartVerdict()
{
//比赛判断
if (m_bGameStarted==true) return false;
//时间模式
enStartMode StartMode=m_pITableFrameSink->GetGameStartMode();
if (StartMode==enStartMode_TimeControl) return false;
//准备人数
WORD wReadyUserCount=0;
tagServerUserData * pUserData=NULL;
for (WORD i=0;i<m_wChairCount;i++)
{
if (m_pIUserItem[i]!=NULL)
{
wReadyUserCount++;
pUserData=m_pIUserItem[i]->GetUserData();
if (pUserData->cbUserStatus!=US_READY) return false;
}
}
//条件判断
if (wReadyUserCount>1L)
{
if (StartMode==enStartMode_Symmetry)
{
if ((wReadyUserCount%2)!=0) return false;
if (wReadyUserCount==m_wChairCount) return true;
WORD wHalfCount=m_wChairCount/2;
for (WORD i=0;i<wHalfCount;i++)
{
if ((m_pIUserItem[i]==NULL)&&(m_pIUserItem[i+wHalfCount]!=NULL)) return false;
if ((m_pIUserItem[i]!=NULL)&&(m_pIUserItem[i+wHalfCount]==NULL)) return false;
}
return true;
}
else
{
if (StartMode==enStartMode_FullReady) return (wReadyUserCount==m_wChairCount);
if (StartMode==enStartMode_AllReady) return true;
}
}
//特殊判断
if ((wReadyUserCount==1)&&(m_pGameServiceAttrib->wChairCount==1)) return true;
return false;
}
//调换位置
bool __cdecl CTableFrame::SwitchUserChair(WORD wSourceID[], WORD wTargetID[], WORD wSwitchCount)
{
//效验数据
ASSERT((wSwitchCount>0)&&(wSwitchCount<m_wChairCount));
if ((wSwitchCount==0)||(wSwitchCount>=m_wChairCount)) return false;
//交换判断
WORD i=0;
for (i=0;i<wSwitchCount;i++)
{
//交换判断
WORD j=0;
for (j=0;j<wSwitchCount;j++)
{
if (wSourceID[i]==wTargetID[j]) break;
}
//错误判断
if (j==wSwitchCount)
{
ASSERT(FALSE);
return false;
}
}
//重复判断
for (WORD i=0;i<wSwitchCount;i++)
{
//数据判断
ASSERT(wSourceID[i]<m_wChairCount);
if (wSourceID[i]>=m_wChairCount) return false;
//存在判断
ASSERT(m_pIUserItem[wSourceID[i]]!=NULL);
if (m_pIUserItem[wSourceID[i]]==NULL) return false;
//重复判断
for (WORD j=0;j<wSwitchCount;j++)
{
if ((i!=j)&&(wSourceID[i]==wSourceID[j]))
{
ASSERT(FALSE);
return false;
}
}
}
//变量定义
BYTE cbUserStatus[MAX_CHAIR];
IServerUserItem * pIUserItem[MAX_CHAIR];
//用户起来
for (WORD i=0;i<wSwitchCount;i++)
{
//变量定义
WORD wSourceChairID=wSourceID[i];
//保存用户
pIUserItem[wSourceChairID]=m_pIUserItem[wSourceChairID];
cbUserStatus[wSourceChairID]=m_pIUserItem[wSourceChairID]->GetUserData()->cbUserStatus;
//设置变量
m_pIUserItem[wSourceChairID]=NULL;
pIUserItem[wSourceChairID]->SetUserStatus(US_FREE,INVALID_TABLE,INVALID_CHAIR);
//发送状态
m_pIGameServiceFrame->SendUserStatus(pIUserItem[wSourceChairID]);
}
//用户坐下
for (WORD i=0;i<wSwitchCount;i++)
{
//变量定义
WORD wSourceChairID=wSourceID[i];
WORD wTargetChairID=wTargetID[i];
//设置变量
m_pIUserItem[wTargetChairID]=pIUserItem[wSourceChairID];
pIUserItem[wSourceChairID]->SetUserStatus(cbUserStatus[wSourceChairID],m_wTableID,wTargetChairID);
//发送状态
m_pIGameServiceFrame->SendUserStatus(pIUserItem[wSourceChairID]);
}
return true;
}
//获取空位
WORD CTableFrame::GetNullChairID()
{
//椅子搜索
for (WORD i=0;i<m_wChairCount;i++)
{
if (m_pIUserItem[i]==NULL)
{
return i;
}
}
return INVALID_CHAIR;
}
//是否完毕
bool CTableFrame::IsClientReady(IServerUserItem * pIServerUserItem)
{
//用户判断
ASSERT(pIServerUserItem!=NULL);
if (pIServerUserItem==NULL) return false;
//用户判断
DWORD dwUserIDMap=0L;
DWORD dwUserID=pIServerUserItem->GetUserID();
if (m_ClientReadyUser.Lookup(dwUserID,dwUserIDMap)==FALSE) return false;
return true;
}
//发送坐下失败
void CTableFrame::SendSitFailedPacket(IServerUserItem * pIServerUserItem, LPCTSTR pszFailedDescribe)
{
//构造数据
CMD_GR_SitFailed SitFailed;
ZeroMemory(&SitFailed,sizeof(SitFailed));
lstrcpyn(SitFailed.szFailedDescribe,pszFailedDescribe,CountArray(SitFailed.szFailedDescribe));
//发送数据
WORD wSendSize=sizeof(SitFailed)-sizeof(SitFailed.szFailedDescribe)+CountStringBuffer(SitFailed.szFailedDescribe);
m_pIGameServiceFrame->SendData(pIServerUserItem,MDM_GR_USER,SUB_GR_SIT_FAILED,&SitFailed,wSendSize);
return;
}
//////////////////////////////////////////////////////////////////////////
| [
"[email protected]"
]
| |
d56b19d519c24ff1169fb609771560239bd1083b | 5fae7bac031e87dbd85d3ae03cf29aae085369f7 | /control/client/qjoystick.cpp | 4f96a158fdb6aaed2ba45d39ecd2beb0d89e57c7 | []
| no_license | cboylan/pdx-rov | 4cab37bbf0db911a236f77a7d8ce78571eda05d0 | db94162f64cce9e7676334240d3f4436378f89d3 | refs/heads/master | 2020-05-30T16:38:24.486222 | 2010-07-19T04:37:28 | 2010-07-19T04:37:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,105 | cpp | #include "qjoystick.h"
#include <QDebug>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <linux/joystick.h>
#include "qjoystick.moc"
QJoystick::QJoystick(const QString &path,
QObject *parent)
: QObject(parent)
, num_buttons(0)
, num_axis(0)
, m_path(path)
, socketNotifier(0)
{
int fd;
fd = open(path.toAscii(), O_RDONLY);
if(fd != -1)
{
socketNotifier = new QSocketNotifier(fd, QSocketNotifier::Read, this);
connect(socketNotifier, SIGNAL(activated(int)),
this, SLOT(activated(int)));
}
}
QString QJoystick::name() const
{
return "";
}
QString QJoystick::device() const
{
return "";
}
const QString &QJoystick::path() const
{
return m_path;
}
int QJoystick::numButtons() const
{
return num_buttons;
}
int QJoystick::numAxis() const
{
return num_axis;
}
void QJoystick::onEvent(int type,
unsigned char number,
unsigned int time,
short int value)
{
}
void QJoystick::setNumButtons(int num)
{
int old_count;
if(num_buttons < num)
{
old_count = num_buttons;
num_buttons = num;
emit(numButtonsChanged(old_count));
}
}
void QJoystick::setNumAxis(int num)
{
int old_count;
if(num_axis < num)
{
old_count = num_axis;
num_axis = num;
emit(numAxisChanged(old_count));
}
}
void QJoystick::activated(int fd)
{
static int len;
static struct js_event ev;
int type;
len = read(fd, &ev, sizeof(struct js_event));
if(len == -1 || len != sizeof(struct js_event))
{
qDebug() << "Invalid read length for joystick event.";
return;
}
if(ev.type & JS_EVENT_INIT)
{
ev.type = ev.type & (~JS_EVENT_INIT);
if(ev.type & JS_EVENT_BUTTON)
{
qDebug() << "Init button " << ev.number;
setNumButtons(ev.number+1);
}
if(ev.type & JS_EVENT_AXIS)
{
qDebug() << "Init axis " << ev.number;
setNumAxis(ev.number+1);
}
}
else
{
type = 0;
if(ev.type & JS_EVENT_BUTTON)
type = Button;
if(ev.type & JS_EVENT_AXIS)
type = type | Axis;
if(ev.type & JS_EVENT_INIT)
type = type | Init;
onEvent(type, ev.number, ev.time, ev.value);
emit(eventOccurred(type, ev.number, ev.time, ev.value));
}
}
| [
"[email protected]"
]
| |
dc30ed72a6f8c14e5cf758a56b97f9327692ebe2 | 397f7eb1ea15ba0bb300ba1e99681164c0421a8d | /test/zeromq_writer_test_helper.cpp | 5fdbffe831ca42e21f0053d7deaa37ce46050e6c | [
"Apache-2.0"
]
| permissive | mexicowilly/Chucho | 38a19664a2296dbe128586281d3b2cc4fe8dc531 | f4235420437eb2078ab592540c0d729b7b9a3c10 | refs/heads/develop | 2021-06-14T14:51:34.679209 | 2021-06-03T17:06:05 | 2021-06-03T17:06:05 | 67,319,394 | 4 | 4 | null | 2018-01-25T16:01:30 | 2016-09-04T01:20:42 | C++ | UTF-8 | C++ | false | false | 3,163 | cpp | /*
* Copyright 2013-2021 Will Mason
*
* 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 <chucho/zeromq_writer.hpp>
#include <chucho/formatted_message_serializer.hpp>
#include <chucho/pattern_formatter.hpp>
#include <chucho/logger.hpp>
#include <chucho/configuration.hpp>
#include <chucho/noop_compressor.hpp>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <thread>
int main(int argc, char* argv[])
{
if (argc != 5 && argc != 6)
{
std::cout << "ZeroMQ helper requires four arguments: endpoint, topic, count and message" << std::endl;
std::cout << "It also allows an optional compressor name" << std::endl;
return EXIT_FAILURE;
}
chucho::configuration::set_style(chucho::configuration::style::OFF);
std::string topic(argv[2]);
std::vector<std::uint8_t> pfx(topic.begin(), topic.end());
auto fmt = std::make_unique<chucho::pattern_formatter>("%m");
auto ser = std::make_unique<chucho::formatted_message_serializer>();
std::unique_ptr<chucho::compressor> cmp;
if (argc == 6)
{
if (std::strcmp(argv[5], "noop") == 0)
cmp = std::make_unique<chucho::noop_compressor>();
}
std::unique_ptr<chucho::zeromq_writer> wrt;
if (cmp)
{
wrt = std::make_unique<chucho::zeromq_writer>("zero",
std::move(fmt),
std::move(ser),
std::move(cmp),
argv[1],
pfx);
}
else
{
wrt = std::make_unique<chucho::zeromq_writer>("zero",
std::move(fmt),
std::move(ser),
argv[1],
pfx);
}
chucho::event evt(chucho::logger::get("zeromq_writer_test"),
chucho::level::INFO_(),
argv[4],
__FILE__,
__LINE__,
__FUNCTION__);
// Wait for the client to establish connection
std::this_thread::sleep_for(std::chrono::milliseconds(500));
auto count = std::stoul(argv[3]);
for (decltype(count) i = 0; i < count; i++)
wrt->write(evt);
wrt->flush();
// Wait for client to receive message
std::this_thread::sleep_for(std::chrono::milliseconds(500));
return EXIT_SUCCESS;
}
| [
"[email protected]"
]
| |
30ddaebad92fde1fc5e68c6589e1b213dde97cb0 | 0183fcf6f75b7d1dccb3e07c4437cfc975cb503c | /viewmdl/ViewMdl.cpp | c8593a3cb87f700bb7dfc55317a9c115e7eaa5aa | []
| no_license | ip821/model-libs | b81ee01b68935ec26599178936059012a708de7a | db150f32da76dcb9a04b71bda214e8d28ab5c883 | refs/heads/master | 2021-01-19T17:48:02.223293 | 2018-11-06T10:44:05 | 2018-11-06T10:44:05 | 37,592,383 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,933 | cpp | // ViewMdl.cpp : Implementation of DLL Exports.
#include "stdafx.h"
#include "resource.h"
#include "ViewMdl_i.h"
#include "dllmain.h"
#include "xdlldata.h"
using namespace ATL;
// Used to determine whether the DLL can be unloaded by OLE.
STDAPI DllCanUnloadNow(void)
{
#ifdef _MERGE_PROXYSTUB
HRESULT hr = PrxDllCanUnloadNow();
if (hr != S_OK)
return hr;
#endif
return _AtlModule.DllCanUnloadNow();
}
// Returns a class factory to create an object of the requested type.
STDAPI DllGetClassObject(_In_ REFCLSID rclsid, _In_ REFIID riid, _Outptr_ LPVOID* ppv)
{
#ifdef _MERGE_PROXYSTUB
HRESULT hr = PrxDllGetClassObject(rclsid, riid, ppv);
if (hr != CLASS_E_CLASSNOTAVAILABLE)
return hr;
#endif
return _AtlModule.DllGetClassObject(rclsid, riid, ppv);
}
// DllRegisterServer - Adds entries to the system registry.
STDAPI DllRegisterServer(void)
{
// registers object, typelib and all interfaces in typelib
HRESULT hr = _AtlModule.DllRegisterServer();
#ifdef _MERGE_PROXYSTUB
if (FAILED(hr))
return hr;
hr = PrxDllRegisterServer();
#endif
return hr;
}
// DllUnregisterServer - Removes entries from the system registry.
STDAPI DllUnregisterServer(void)
{
HRESULT hr = _AtlModule.DllUnregisterServer();
#ifdef _MERGE_PROXYSTUB
if (FAILED(hr))
return hr;
hr = PrxDllRegisterServer();
if (FAILED(hr))
return hr;
hr = PrxDllUnregisterServer();
#endif
return hr;
}
// DllInstall - Adds/Removes entries to the system registry per user per machine.
STDAPI DllInstall(BOOL bInstall, _In_opt_ LPCWSTR pszCmdLine)
{
HRESULT hr = E_FAIL;
static const wchar_t szUserSwitch[] = L"user";
if (pszCmdLine != NULL)
{
if (_wcsnicmp(pszCmdLine, szUserSwitch, _countof(szUserSwitch)) == 0)
{
ATL::AtlSetPerUserRegistration(true);
}
}
if (bInstall)
{
hr = DllRegisterServer();
if (FAILED(hr))
{
DllUnregisterServer();
}
}
else
{
hr = DllUnregisterServer();
}
return hr;
}
| [
"[email protected]"
]
| |
8c8d1cec381fc737e21391e1dee91a986f725c53 | 8180b65f630389e16e039a648838a9eb13d35920 | /Fibonacci.cpp | 71487761823d571de72ac464e9a96498fc65ba74 | []
| no_license | tonytam3/FibonacciCPP | 8666bee4f5f3c1ecee20d57f26aac6825ae5ed43 | 458ab487890bf0652333e4fc3c50b4d27d5fb9d3 | refs/heads/master | 2020-04-23T00:35:32.954533 | 2019-02-15T01:47:32 | 2019-02-15T01:47:32 | 170,784,964 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,422 | cpp | #include <iostream>
using namespace std;
void progWelcome();
void progNthRequest();
void printOut();
void progContinue();
void progGoodbye();
void fiboSeq(int n, long long &result);
int n;
long long result;
bool progExit = false;
void main() {
progWelcome();
do {
progNthRequest();
fiboSeq(n, result);
printOut();
progContinue();
} while (progExit == false);
progGoodbye();
}
void progWelcome() {
cout << "Welcome to Fibonacci Sequence Program\n" << endl;
}
void progNthRequest() {
do {
cout << "What is the desired Nth value for Fibonacci's Sequence?\n" << endl;
cin >> n;
cout << endl;
if (n < 0) cout << "Must be a positive number\n" << endl;
} while (n < 0);
}
void printOut() {
cout <<"The result is: "<< result << endl << endl;
}
void progContinue() {
cout << "Would you like to try a diffent Nth number?\n 1) yes\n 2) no\n" << endl;
cin >> n;
cout << endl;
switch (n) {
case 1: n = 0; break;
default: progExit = true; break;
}
}
void progGoodbye() {
cout << "Goobdye\n" << endl;
}
void fiboSeq (int n, long long &result) {
long long fiboSeq[3] = { 0,1 };
switch (n) {
case 0:
result = 0; break;
case 1:
result = 1; break;
default:
for (int x = 1; x < n; x++) {
fiboSeq[2] = fiboSeq[1] + fiboSeq[0];
fiboSeq[0] = fiboSeq[1];
fiboSeq[1] = fiboSeq[2];
};
break;
};
result = fiboSeq[2];
}
| [
"[email protected]"
]
| |
d7e5b10f152e76f286c4fafc3dae69b665f331ef | 59f9dd8d15be93b7d98ee38465510a53fc628664 | /widgetdown.cpp | a7df6d240126e67e53524c08e48c4dc8f58b9a94 | []
| no_license | tujiaw/bottom | 31a14bee227f5da5150d228f20510568dc59a42b | 88cfd6c7354789bd530168974c385a539922d20a | refs/heads/master | 2021-01-01T18:48:35.408297 | 2014-08-16T02:20:08 | 2014-08-16T02:20:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 512 | cpp | #include "widgetdown.h"
#include <QtWidgets>
WidgetDown::WidgetDown(QWidget *parent) :
QWidget(parent)
{
QPalette palette;
palette.setBrush(this->backgroundRole(), QBrush(QColor(255, 0, 0)));
this->setPalette(palette);
this->setAutoFillBackground(true);
this->setMouseTracking(true);
}
void WidgetDown::enterEvent(QEvent *event)
{
emit sigShow();
QWidget::enterEvent(event);
}
void WidgetDown::leaveEvent(QEvent *event)
{
emit sigHide();
QWidget::leaveEvent(event);
}
| [
"[email protected]"
]
| |
a7d9b089d5029bb75d878913570cd94dd4866c1e | 481b57a078cd90c5cd4fa89d22e4461936c1b1f0 | /Tubes/child.cpp | 073cc2885f52e3943b39bb1f4d09f89988968563 | []
| no_license | Yogi162/TUBES_1301174264_1301170505 | 127d852fd8bf1c35bf67a625714b8a13ee951def | a8a17b1da48719f44d03c60d84f6ef99547eeff6 | refs/heads/master | 2020-03-14T02:42:37.453221 | 2018-04-28T12:08:04 | 2018-04-28T12:08:04 | 131,404,687 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 7,966 | cpp | #include "child.h"
void createList(List &L) {
first(L)=NULL;
last(L)=NULL;
}
address allocate(infotype x) {
address P = new elmlist;
info(P) = x;
next(P)=NULL;
prev(P) = NULL;
return P;
}
void deallocate(address &P) {
delete P;
}
void insertFirst(List &L, address P) {
if (first(L)!= NULL)
{
prev(first(L)) = P;
next(P) = first(L);
first(L) = P;
}
else
{
first(L) = P;
last(L) = P;
}
}
void insertLast(List &L, address P) {
if (first(L) != NULL)
{
prev(P) = last(L);
next(last(L)) = P;
last(L) = P;
}
else
{
insertFirst(L,P);
}
}
address findElm(List L, infotype x) {
address Q = new elmlist;
bool ketemu = false;
if (first(L)!=NULL)
{
Q = first(L);
while(Q!=NULL && !ketemu)
{
if(info(Q).id_bandara == x.id_bandara)
{
return Q;
ketemu = true;
}
Q = next(Q);
}
}
else if (first(L)==NULL || !ketemu)
{
return NULL;
}
}
void deleteFirst(List &L, address &P) {
if (first(L)!=NULL)
{
if(first(L)==last(L))
{
P = first(L);
first(L) = NULL;
last(L) = NULL;
}
else
{
P = first(L);
prev(next(P)) = NULL;
first(L) = next(P);
next(P) = NULL;
}
}
else
{
cout << "Listnya sudah kosong."<< endl;
}
}
void deleteLast(List &L, address &P) {
if (first(L)!=NULL)
{
if (first(L)==last(L))
{
deleteFirst(L, P);
}
else
{
address Q = prev(last(L));
P = last(L);
prev(last(L)) = NULL;
next(Q) = NULL;
last(L) = Q;
}
}
else
{
cout << "List sudah kosong." << endl;
}
//----------------------------------------
}
void printInfo(List L) {
/**
* FS : view info of all element inside List L,
* call the view_data function from my_data.h to print the info
*/
//-------------your code here-------------
address P = new elmlist;
if (first(L)!=NULL)
{
P = first(L);
do
{
view_data(info(P));
P = next(P);
}
while(P!=NULL);
}
else
{
cout << "[Kosong]" << endl;
}
//----------------------------------------
}
void insertAfter(List &L, address Prec, address P) {
/**
* IS : Prec and P is not NULL
* FS : element pointed by P is placed behind the element
* pointed by pointer Prec
*/
//-------------your code here-------------
if (Prec!=NULL && P!=NULL)
{
if(next(Prec)!=NULL)
{
address Q = next(Prec);
next(P) = Q;
prev(Q) = P;
next(Prec) = P;
prev(P) = Prec;
}
else
{
insertLast(L, P);
}
}
//----------------------------------------
}
void deleteAfter(List &L, address Prec, address &P) {
/**
* IS : Prec is not NULL
* FS : element which was before behind an element pointed by Prec
* is removed and pointed by pointer P
*/
//-------------your code here-------------
if(Prec!=NULL)
{
if(next(next(Prec))!=NULL)
{
P = next(Prec);
address Q = next(P);
next(Prec) = Q;
prev(Q) = Prec;
next(P) = NULL;
prev(P) = NULL;
}
else
{
deleteLast(L, P);
}
}
//----------------------------------------
}
void insertAndSort(List &L, address P) {
bool ada = false;
bool ketemu = false;
address Q = new elmlist;
if (first(L)==NULL)
{
insertFirst(L, P);
ada = true;
}
else
{
Q = first(L);
while (Q !=NULL)
{
if (info(Q).id_bandara==info(P).id_bandara)
{
ada = true;
}
Q = next(Q);
}
if (!ada)
{
if (first(L)!=NULL)
{
if (info(P).id_bandara<info(first(L)).id_bandara)
{
insertFirst(L,P);
}
else
{
Q = first(L);
while(Q!=NULL && !ketemu)
{
if(next(Q)!=NULL)
{
if(info(P).id_bandara < info(next(Q)).id_bandara)
{
insertAfter(L, Q, P);
ketemu = true;
}
}
else
{
insertLast(L, P);
ketemu = true;
}
Q = next(Q);
}
}
}
}
else
{
cout << "ID yang dimasukkan telah ada! " << endl;
}
}
}
void deletebyID(List &L, infotype x) {
address P;
P = findElm(L, x);
if (P!=NULL)
{
if (P==first(L))
{
deleteFirst(L, P);
deallocate(P);
}
else
{
address Prec = new elmlist;
bool ketemu = false;
Prec = first(L);
while(Prec!=NULL && !ketemu)
{
if (next(next(Prec))==NULL)
{
deleteLast(L, P);
}
else if (next(Prec)!=NULL)
{
if(info(next(Prec)).id_bandara == info(P).id_bandara)
{
deleteAfter(L,Prec,P);
ketemu = true;
}
}
Prec = next(Prec);
}
deallocate(P);
}
}
}
child create_data(child &d) {
/**
TODO: receive input from user
and assign the value of new data
*/
// ===========================
// YOUR CODE HERE
cout<<"Masukkan Nama Bandara: "<<endl;
cin>>d.bandara;
cout<<"Masukkan Kode bandara: "<<endl;
cin>>d.id_bandara;
cout<<"Masukkan Nama daerah: "<<endl;
cin>>d.daerah;
return d;
}
void view_data(child d) {
/**
TODO: view the content of data d
*/
// ===========================
// YOUR CODE HERE
cout<<"Nama Bandara: "<<d.bandara<<endl;
cout<<"Nama Kode Bandara: "<<d.id_bandara<<endl;
cout<<"Nama Daerah: "<<d.daerah<<endl;
// ===========================
}
void edit_data(child &d) {
/**
TODO: edit the value of data d,
the ID must not be modified
*/
// ===========================
// YOUR CODE HERE
char jawaban;
cout<<"Ingin mengubah Bandara?: ";
cin>>jawaban;
if (jawaban == 'y')
{
cout<<"Masukkan Nama Bandara: "<<endl;
cin>>d.bandara;
}
cout<<"Ingin mengubah Kode Bandara?: ";
cin>>jawaban;
if (jawaban == 'y')
{
cout<<"Masukkan Kode bandara: "<<endl;
cin>>d.id_bandara;
}
cout<<"Ingin mengubah daerah?: ";
cin>>jawaban;
if (jawaban == 'y')
{
cout<<"Masukkan Nama Daerah: "<<endl;
cin>>d.daerah;
}
}
| [
"[email protected]"
]
| |
1874f3ec22a87aa1915ae364e3d5de8f20de40e5 | 86321e860641282f6afc435a9becd3db7a3d32c0 | /tags/release-0-0-8/ta-lib/excel/src/xlw/XlfOper.cpp | dae0c9bc49aa4f058cf8828c80effbffe2bc5b3f | []
| no_license | royratcliffe/ta-lib | 0207e477da8ab14dde74f39a8b7aa58275c79c6d | 272b60afa70625b84ab647fd1e0a13909735280b | refs/heads/master | 2021-01-01T16:25:04.669925 | 2012-08-24T09:23:43 | 2012-08-24T14:48:35 | 4,485,293 | 10 | 2 | null | null | null | null | ISO-8859-1 | C++ | false | false | 14,521 | cpp | /*
Copyright (C) 1998, 1999, 2001, 2002 Jérôme Lecomte
This file is part of XLW, a free-software/open-source C++ wrapper of the
Excel C API - http://xlw.sourceforge.net/
XLW is free software: you can redistribute it and/or modify it under the
terms of the XLW license. You should have received a copy of the
license along with this program; if not, please email [email protected]
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 license for more details.
*/
/*!
\file XlfOper.cpp
\brief Implements the XlfOper class.
*/
// $Id$
#include <xlw/XlfOper.h>
#include <xlw/XlfException.h>
#include <xlw/XlfRef.h>
#include <xlw/macros.h>
#include <cassert>
#include <iostream>
#include <math.h>
// Stop header precompilation
#ifdef _MSC_VER
#pragma hdrstop
#endif
#ifndef NDEBUG
#include <xlw/XlfOper.inl>
#endif
extern "C" double trio_nan(void);
/*!
This bit is currently unused by Microsoft Excel. We set it
to indicate that the LPXLOPER (passed by Excel) holds some extra
memory to be freed.
This bit is controled in ~XlfOper to know if the DLL should release
auxiliary memory or not by a call to FreeAuxiliaryMemory.
*/
int XlfOper::xlbitFreeAuxMem = 0x8000;
/*!
Shallow copy of a pointer to XLOPER.
\param lpxloper Pointer to XLOPER.
Excel or by the XLL (default is true).
*/
XlfOper::XlfOper(LPXLOPER lpxloper): lpxloper_(lpxloper)
{}
/*!
Calls Deallocate() to free the XLOPER allocated by the XLL. XLOPER allocated
by Excel remain under Excel responsability.
Calls FreeAuxiliaryMemory if the XLOPER is marked by XlfOper::Call as an
XLOPER returned by MS Excel and if the type matches one of xltypeStr,
xltypeRef, xltypeMulti, xltypeBigData.
*/
XlfOper::~XlfOper()
{
if (! lpxloper_)
return;
int type = lpxloper_->xltype;
// Only the types bellow can be flagged xlFreeAuxMem, thus the test is
// actually redundant: we don't need to re-check the type of the oper.
//
// bool canHaveAuxMem = (type & xltypeStr ||
// type & xltypeRef ||
// type & xltypeMulti ||
// type & xltypeBigData);
if (type & xlbitFreeAuxMem)
{
// switch back the bit as it was originally
lpxloper_->xltype &= ~xlbitFreeAuxMem;
FreeAuxiliaryMemory();
}
Deallocate();
return;
}
/*!
Allocates 16 bits (size of a XLOPER) on the temporary buffer
stored by XlfExcel with a call to XlfExcel::GetMemory().
\warning Each XlfOper allocation causes a call to Allocate which in turn
reserve the necessary number of bytes in the internal buffer. The
problem is that even temporary XlfOper used inside the xll function use
this internal buffer. This buffer is not freed before the next call to
the xll to ensure Excel can use the data before they are freed. This
causes a bottleneck if the function uses many temporary XlfOper (see
Deallocate()).
\return \c xlretSuccess or \c xlretInvXloper if no memory is could
be allocated.
*/
int XlfOper::Allocate()
{
lpxloper_ = (LPXLOPER)XlfExcel::Instance().GetMemory(sizeof(XLOPER));
if (!lpxloper_)
return xlretInvXloper;
lpxloper_->xltype = xltypeNil;
return xlretSuccess;
}
void XlfOper::FreeAuxiliaryMemory() const
{
int err = XlfExcel::Instance().XlfExcel::Instance().Call(xlFree, NULL, 1, (LPXLOPER)lpxloper_);
if (err != xlretSuccess)
std::cerr << __HERE__ << "Call to xlFree failed" << std::endl;
return;
}
/*!
\param type is an integer indicating the target type we want to coerce to.
\param result is the XLOPER where to store the output.
*/
int XlfOper::Coerce(short type, XlfOper& result) const
{
XlfOper xlType(type);
int xlret = XlfExcel::Instance().Call(xlCoerce, (LPXLOPER)result, 2, (LPXLOPER)lpxloper_, (LPXLOPER)xlType);
return xlret;
}
/*!
Attempts to convert the implict object to a double. If pxlret is not null
the method won't throw and the Excel return code will be returned in this
variable.
\sa XlfOper::ConvertToDouble.
*/
double XlfOper::AsDouble(int * pxlret) const
{
double d;
int xlret = ConvertToDouble(d);
if (pxlret)
*pxlret=xlret;
else
ThrowOnError(xlret);
return d;
};
int XlfOper::ConvertToDouble(double& d) const throw()
{
int xlret;
if (lpxloper_ == 0)
return xlretInvXloper;
if (lpxloper_->xltype & xltypeInt)
{
d = lpxloper_->val.w;
xlret=xlretSuccess;
}
else if (lpxloper_->xltype & xltypeNum)
{
d = lpxloper_->val.num;
xlret=xlretSuccess;
}
else if (lpxloper_->xltype & (xltypeErr|xltypeMissing|xltypeNil) )
{
d = trio_nan();
xlret=xlretSuccess;
}
else
{
// Allocates tmp on the stack to avoid filling the internal buffer.
XLOPER tmp;
// Creates a XlfOper based on tmp.
XlfOper cast(&tmp);
// Coerces to numeric type.
xlret = Coerce(xltypeNum,cast);
if( cast.IsError() || cast.IsMissing() )
{
d = trio_nan();
xlret = xlretSuccess;
}
else if (xlret == xlretSuccess)
xlret = cast.ConvertToDouble(d);
}
return xlret;
};
/*!
Attempts to convert the implict object to a vector of double. If pxlret is
not null the method won't throw and the Excel return code will be returned
in this variable.
\sa XlfOper::ConvertToDoubleVector.
*/
std::vector<double> XlfOper::AsDoubleVector(DoubleVectorConvPolicy policy, int * pxlret) const
{
std::vector<double> v;
int xlret = ConvertToDoubleVector(v, policy);
if (pxlret)
*pxlret=xlret;
else
ThrowOnError(xlret);
return v;
}
/*!
Converts the data in the range in a vector of double according to the specified policy.
\pre All values in the range should be convertible to a double.
\return xlretFailed if the policy is UniDimensional and the range is not uni dimensional
and xlretSuccess otherwise or whatever error occurs during coercing the data to double.
\sa DoubleVectorConvPolicy
*/
int XlfOper::ConvertToDoubleVector(std::vector<double>& v, DoubleVectorConvPolicy policy) const
{
XlfRef ref;
int xlret = ConvertToRef(ref);
if (xlret != xlretSuccess)
return xlret;
size_t nbRows = ref.GetNbRows();
size_t nbCols = ref.GetNbCols();
bool isUniDimRange = ( nbRows == 1 || nbCols == 1 );
if (policy == UniDimensional && ! isUniDimRange)
// not a vector we return a failure
return xlretFailed;
size_t n = nbRows*nbCols;
v.resize(n);
for (size_t i = 0; i < nbRows; ++i)
{
for (size_t j = 0; j < nbCols; ++j)
{
if (policy == RowMajor)
// C-like dense matrix storage
xlret = ref(i,j).ConvertToDouble(v[i*nbCols+j]);
else
// Fortran-like dense matrix storage. Does not matter if the policy is UniDimensional
xlret = ref(i,j).ConvertToDouble(v[j*nbRows+i]);
if (xlret != xlretSuccess)
return xlret;
}
}
return xlret;
};
/*!
Attempts to convert the implict object to a short. If pxlret is not null
the method won't throw and the Excel return code will be returned in this
variable.
\sa XlfOper::ConvertToShort.
*/
short XlfOper::AsShort(int * pxlret) const
{
short s;
int xlret = ConvertToShort(s);
if (pxlret)
*pxlret=xlret;
else
ThrowOnError(xlret);
return s;
};
int XlfOper::ConvertToShort(short& s) const throw()
{
int xlret;
if (lpxloper_ == 0)
return xlretInvXloper;
if (lpxloper_->xltype & xltypeNum)
{
s = lpxloper_->val.num;
xlret=xlretSuccess;
}
else
{
// Allocates tmp on the stack to avoid filling the internal buffer.
XLOPER tmp;
// Creates a XlfOper based on tmp.
XlfOper cast(&tmp);
// Coerces to numeric type.
xlret = Coerce(xltypeNum,cast);
if (xlret == xlretSuccess)
xlret = cast.ConvertToShort(s);
}
return xlret;
};
/*!
Attempts to convert the implict object to a bool. If pxlret is not null
the method won't throw and the Excel return code will be returned in this
variable.
\sa XlfOper::ConvertToBool.
*/
bool XlfOper::AsBool(int * pxlret) const
{
bool b;
int xlret = ConvertToBool(b);
if (pxlret)
*pxlret=xlret;
else
ThrowOnError(xlret);
return b;
};
int XlfOper::ConvertToBool(bool& b) const throw()
{
int xlret;
if (lpxloper_ == 0)
return xlretInvXloper;
if (lpxloper_->xltype & xltypeBool)
{
b = (lpxloper_->val.boolean != 0);
xlret = xlretSuccess;
}
else
{
// see ConvertToDouble
XLOPER tmp;
XlfOper cast(&tmp);
xlret = Coerce(xltypeBool,cast);
if (xlret == xlretSuccess)
xlret = cast.ConvertToBool(b);
}
return xlret;
};
/*!
Attempts to convert the implict object to a char string. If pxlret is not
null the method won't throw and the Excel return code will be returned in
this variable.
\sa XlfOper::ConvertToString.
The XLL allocates the memory on its own buffer. This buffer is automatically
freed when a function of the XLL is called again. Note that coerce to
a char string is the slowest cast of all.
*/
char * XlfOper::AsString(int * pxlret) const
{
char * s;
int xlret = ConvertToString(s);
if (pxlret)
*pxlret=xlret;
else
ThrowOnError(xlret);
return s;
};
int XlfOper::ConvertToString(char *& s) const throw()
{
int xlret;
if (lpxloper_ == 0)
return xlretInvXloper;
if (lpxloper_->xltype & xltypeStr)
{
size_t n = lpxloper_->val.str[0];
s = XlfExcel::Instance().GetMemory(n + 1);
memcpy(s, lpxloper_->val.str + 1, n);
s[n] = 0;
xlret = xlretSuccess;
}
else
{
// see AsDouble
XLOPER tmp;
// Second argument true marks XlfOper so that xlFree is called on the
// MS Excel allocated memory (the string) when XlfOper goes out of scope.
XlfOper cast(&tmp);
xlret = Coerce(xltypeStr,cast);
if (xlret == xlretSuccess)
xlret = cast.ConvertToString(s);
}
return xlret;
}
/*!
Attempts to convert the implict object to an XlfRef. If pxlret is not null
the method won't throw and the Excel return code will be returned in this
variable.
\sa XlfOper::ConvertToRef.
*/
XlfRef XlfOper::AsRef(int * pxlret) const
{
XlfRef r;
int xlret = ConvertToRef(r);
if (pxlret)
*pxlret=xlret;
else
ThrowOnError(xlret);
return r;
}
int XlfOper::ConvertToRef(XlfRef& r) const throw()
{
int xlret;
if (lpxloper_ == 0)
return xlretInvXloper;
if (lpxloper_->xltype & xltypeRef)
{
const XLREF& ref=lpxloper_->val.mref.lpmref->reftbl[0];
r = XlfRef (ref.rwFirst, // top
ref.colFirst, // left
ref.rwLast, // bottom
ref.colLast, // right
lpxloper_->val.mref.idSheet); // sheet id
xlret = xlretSuccess;
}
else
{
// see AsDouble
XLOPER tmp;
// Second argument true marks XlfOper so that xlFree is called on the
// MS Excel allocated memory (the reference array) when XlfOper goes
// out of scope.
XlfOper cast(&tmp);
xlret = Coerce(xltypeRef,cast);
if (xlret == xlretSuccess)
xlret = cast.ConvertToRef(r);
}
return xlret;
}
XlfOper& XlfOper::Set(LPXLOPER lpxloper)
{
assert(lpxloper != 0);
lpxloper_ = lpxloper;
return *this;
}
XlfOper& XlfOper::Set(double value)
{
if (lpxloper_)
{
lpxloper_->xltype = xltypeNum;
lpxloper_->val.num = value;
}
return *this;
}
XlfOper& XlfOper::Set(short value)
{
if (lpxloper_)
{
lpxloper_->xltype = xltypeInt;
lpxloper_->val.w = value;
}
return *this;
}
XlfOper& XlfOper::Set(bool value)
{
if (lpxloper_)
{
lpxloper_->xltype = xltypeBool;
lpxloper_->val.boolean = value;
}
return *this;
}
/*!
If no memory can be allocated on xlw internal buffer, the XlfOper is set
to an invalid state and the XlfRef is not copied.
*/
XlfOper& XlfOper::Set(const XlfRef& range)
{
if (lpxloper_)
{
lpxloper_->xltype = xltypeRef;
XLMREF * pmRef = reinterpret_cast<XLMREF *>(XlfExcel::Instance().GetMemory(sizeof(XLMREF)));
// if no memory is available
if (pmRef == 0)
{
// set XlfOper to an invalid state
lpxloper_=0;
}
else
{
pmRef->count=1;
pmRef->reftbl[0].rwFirst = range.GetRowBegin();
pmRef->reftbl[0].rwLast = range.GetRowEnd()-1;
pmRef->reftbl[0].colFirst = range.GetColBegin();
pmRef->reftbl[0].colLast = range.GetColEnd()-1;
lpxloper_->val.mref.lpmref = pmRef;
lpxloper_->val.mref.idSheet = range.GetSheetId();
}
}
return *this;
}
/*!
If no memory can be allocated on xlw internal buffer, the XlfOper is set
to an invalid state and the string is not copied.
\note String longer than 255 characters are truncated. A warning
is issued in debug mode.
*/
XlfOper& XlfOper::Set(const char *value)
{
if (lpxloper_)
{
lpxloper_->xltype = xltypeStr;
int n = strlen(value);
if (n >= 256)
std::cerr << __HERE__ << "String too long is truncated" << std::endl;
// One byte more for NULL terminal char (allow use of strcpy)
// and one for the std::string size (convention used by Excel)
LPSTR str = reinterpret_cast<LPSTR>(XlfExcel::Instance().GetMemory(n + 2));
if (str == 0)
{
lpxloper_=0;
}
else
{
strcpy(str + 1, value);
// the number of character include the final \0 or not ?
lpxloper_->val.str = str;
lpxloper_->val.str[0] = (BYTE)(n + 1);
}
}
return *this;
}
/*!
\sa XlfOper::Error(WORD)
*/
XlfOper& XlfOper::SetError(WORD error)
{
if (lpxloper_)
{
lpxloper_->xltype = xltypeErr;
lpxloper_->val.err = error;
}
return *this;
}
/*!
Throws an exception if the argument is anything other than xlretSuccess.
Events that require an immediate return to excel (uncalculated cell, abort,
stack overflow and invalid OPER (potential memory exhaustion)) throw an
XlfException.
Other events throw std::runtime_error.
*/
int XlfOper::ThrowOnError(int xlret) const
{
if (xlret == xlretSuccess)
return xlret;
if (xlret & xlretUncalced)
throw XlfExceptionUncalculated();
if (xlret & xlretAbort)
throw XlfExceptionAbort();
if (xlret & xlretStackOvfl)
throw XlfExceptionStackOverflow();
if (xlret & xlretInvXloper)
throw XlfException("invalid OPER structure (memory could be exhausted)");
if (xlret & xlretFailed)
throw std::runtime_error("command failed");
if (xlret & xlretInvCount)
throw std::runtime_error("invalid number of argument");
if (xlret & xlretInvXlfn)
throw std::runtime_error("invalid function number");
// should never get there.
assert(0);
return xlret;
}
| [
"(no author)@3f33b33b-d80e-0410-b78d-a637975a354c"
]
| (no author)@3f33b33b-d80e-0410-b78d-a637975a354c |
31b4e56b8311d2254e762228bea2db4207dba394 | a0ef3aa1b3118baf54dc186d89c35072b8d96d54 | /codeforces/1380/B.cpp | b632b50ff7d31e7b131c830f313bc18aa1a48b2c | []
| no_license | arjunbangari/Problem-Solving | 110398129698038660e558509c46c385e7848cc3 | 9c9760627a3fbdd97ecee8cbc02245a3ea0f7fda | refs/heads/master | 2023-02-05T17:09:40.631840 | 2019-08-10T12:02:00 | 2020-12-29T11:52:13 | 324,994,511 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 946 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
typedef long double ld;
typedef pair<ll,ll> pll;
#define endl "\n";
#define fast ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL)
ll const inf = 1e18;
ll const maxn = 1e6+5;
ll const mod = 1e9+7;
// code begins here
int main(){
fast;
ll t;
cin>>t;
while(t--){
string s;
cin>>s;
ll n = s.length();
map<char, ll> mp;
ll mx = -1;
char ch;
for(ll i=0;i<n;i++){
mp[s[i]]++;
if(mp[s[i]]>mx)
ch = s[i];
mx = max(mx, mp[s[i]]);
}
char ans;
if(ch=='R')
ans = 'P';
if(ch=='P')
ans = 'S';
if(ch=='S')
ans = 'R';
for(ll i=0;i<n;i++)
cout<<ans;
cout<<endl;
}
return 0;
} | [
"[email protected]"
]
| |
1aed41982eca610c94b15354f842e02bef50021e | 3c09d1c279c8578791dae535852c06e09efad4a1 | /Projects/Jordan Mitarov/03.Data Structures/70.ListSortTask02/main.cpp | f4a919ee8711cfb4d9764f4349a993c454f535d6 | []
| no_license | rosen90/GitHub | f00653f8a65cdffc479b70d2d7ca8f9e103d3eeb | 851d210f2f6073d818e0984fa9daab96e833b066 | refs/heads/master | 2016-09-12T23:57:19.530896 | 2016-05-04T22:09:03 | 2016-05-04T22:09:03 | 58,085,509 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 769 | cpp | /*Write a program that merges two ordered list
objects of integers into a single ordered list object of
integers.*/
#include <iostream>
using namespace std;
#include "List.h"
template <typename T>
void reverseOrder(List<T> &first,List<T>&second)
{
List<T> tempfirst(first); //create copy of first
T value;
while(!tempfirst.isEmpty())
{
tempfirst.removeFromBack(value);
second.insertAtBack(value);
}
if(!tempfirst.isEmpty())
{
do
{
tempfirst.removeFromBack(value);
second.insertAtBack(value);
}while(!tempfirst.isEmpty());
}
}
int main()
{
List<char> listOne;
List<char> listTwo;
char c;
for(c ='a';c <= 'j'; c++)
{
listOne.insertAtBack(c);
}
listOne.print();
reverseOrder(listOne,listTwo);
listTwo.print();
return 0;
}
| [
"[email protected]"
]
| |
585a390907b89cd60cb482eda0823fd51d5baf32 | 877fff5bb313ccd23d1d01bf23b1e1f2b13bb85a | /app/src/main/cpp/dir7941/dir22441/dir22442/dir22443/dir24650/dir24841/file25107.cpp | 4c7688692c8ed98218da782cf22d9bed856cb3a6 | []
| no_license | tgeng/HugeProject | 829c3bdfb7cbaf57727c41263212d4a67e3eb93d | 4488d3b765e8827636ce5e878baacdf388710ef2 | refs/heads/master | 2022-08-21T16:58:54.161627 | 2020-05-28T01:54:03 | 2020-05-28T01:54:03 | 267,468,475 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 115 | cpp | #ifndef file25107
#error "macro file25107 must be defined"
#endif
static const char* file25107String = "file25107"; | [
"[email protected]"
]
| |
cafecfae352bcf001af689d967550eb9e118982f | 7a959ea764651aed99d261f35ef060599090d43b | /MFCOpenGL/MFCOpenGL/OpenGLControl.cpp | 685593fb344fa770bd96e20c04443a5ff1e6a9cf | []
| no_license | Riverxik/dialog3d | f0ffd35445f5d4c47bb00098dd063c220944973c | d8745e7ca533c376253ff779579e84f22611c588 | refs/heads/master | 2021-01-20T05:43:39.191241 | 2017-04-30T16:43:52 | 2017-04-30T16:43:52 | 89,803,415 | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 21,090 | cpp | #include "stdafx.h"
#include "OpenGLControl.h"
COpenGLControl::COpenGLControl(void)
{
m_fPosX = 0.0f; // X position of model in camera view
m_fPosY = 0.0f; // Y position of model in camera view
m_fZoom = 5.0f; // Zoom on model in camera view
m_fRotX = 0.0f; // Rotation on model in camera view
m_fRotY = 0.0f; // Rotation on model in camera view
m_bIsMaximized = false;
m_bRayIsVisible = false; // False mean don't draw the ray
m_iNumSelectedSphere = -1;
m_start_x = 0.0f; // x coord of start point
m_start_y = 0.0f; // y coord of start point
m_start_z = 0.0f; // z coord of start point
m_length = 1.0f; // x_max coord of start point
m_width = 1.0f; // y_max coord of start point
m_height = 1.0f; // z_max coord of start point
m_scale = 1.0f; // scale
// Сферы
for(unsigned i=0; i<SELECTING_OBJECT_COUNT; i++)
obj[i]; // инициализация 8 сфер в 0,0,0
//Цвет
for(unsigned i=0; i<SELECTING_OBJECT_COUNT; i++)
{
cubeColorArray[i][0] = 1.0f;
cubeColorArray[i][1] = 1.0f;
cubeColorArray[i][2] = 1.0f;
}
//Грани
cubeIndexArray[0][0] = 0;
cubeIndexArray[0][1] = 3;
cubeIndexArray[0][2] = 2;
cubeIndexArray[0][3] = 1;
cubeIndexArray[1][0] = 0;
cubeIndexArray[1][1] = 1;
cubeIndexArray[1][2] = 5;
cubeIndexArray[1][3] = 4;
cubeIndexArray[2][0] = 7;
cubeIndexArray[2][1] = 4;
cubeIndexArray[2][2] = 5;
cubeIndexArray[2][3] = 6;
cubeIndexArray[3][0] = 3;
cubeIndexArray[3][1] = 7;
cubeIndexArray[3][2] = 6;
cubeIndexArray[3][3] = 2;
cubeIndexArray[4][0] = 1;
cubeIndexArray[4][1] = 2;
cubeIndexArray[4][2] = 6;
cubeIndexArray[4][3] = 5;
cubeIndexArray[5][0] = 0;
cubeIndexArray[5][1] = 4;
cubeIndexArray[5][2] = 7;
cubeIndexArray[5][3] = 3;
// Оси
/*
1
|
0|___2
/
/3
*/
// Точки
// axisVertex[Номер точки][Номер координаты]
axisVertex[0][0] = 0;
axisVertex[0][1] = 0;
axisVertex[0][2] = 0;
axisVertex[1][0] = 0;
axisVertex[1][1] = 1;
axisVertex[1][2] = 0;
axisVertex[2][0] = 1;
axisVertex[2][1] = 0;
axisVertex[2][2] = 0;
axisVertex[3][0] = 0;
axisVertex[3][1] = 0;
axisVertex[3][2] = 1;
// Цвета
// axisColor[Номер точки][Номер координаты] = 0;
axisColor[0][0] = 1;
axisColor[0][1] = 1;
axisColor[0][2] = 1;
axisColor[1][0] = 0;
axisColor[1][1] = 1;
axisColor[1][2] = 0;
axisColor[2][0] = 1;
axisColor[2][1] = 0;
axisColor[2][2] = 0;
axisColor[3][0] = 0;
axisColor[3][1] = 0;
axisColor[3][2] = 1;
// Линии
// axisIndex[Номер линии][Номер точки]
axisIndex[0][0] = 0;
axisIndex[0][1] = 1;
axisIndex[1][0] = 0;
axisIndex[1][1] = 2;
axisIndex[2][0] = 0;
axisIndex[2][1] = 3;
}
COpenGLControl::~COpenGLControl(void)
{
}
BEGIN_MESSAGE_MAP(COpenGLControl, CWnd)
ON_WM_PAINT()
ON_WM_SIZE()
ON_WM_CREATE()
ON_WM_TIMER()
ON_WM_MOUSEMOVE()
ON_WM_LBUTTONUP()
END_MESSAGE_MAP()
void COpenGLControl::OnPaint()
{
//CPaintDC dc(this); // device context for painting
ValidateRect(NULL);
}
void COpenGLControl::OnSize(UINT nType, int cx, int cy)
{
CWnd::OnSize(nType, cx, cy);
if (0 >= cx || 0 >= cy || nType == SIZE_MINIMIZED) return;
// Map the OpenGL coordinates.
glViewport(0, 0, cx, cy);
//int side = 0;
//(cx > cy) ? side = cx : side = cy;
//glViewport((cx - side) / 2, (cy - side) / 2, side, side);
// Projection view
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
// Set our current view perspective
gluPerspective(35.0f, (float)cx / (float)cy, 0.01f, 2000.0f);
// Model view
glMatrixMode(GL_MODELVIEW);
switch (nType)
{
// If window resize token is "maximize"
case SIZE_MAXIMIZED:
{
// Get the current window rect
GetWindowRect(m_rect);
// Move the window accordingly
MoveWindow(6, 6, cx - 14, cy - 14);
// Get the new window rect
GetWindowRect(m_rect);
// Store our old window as the new rect
m_oldWindow = m_rect;
break;
}
// If window resize token is "restore"
case SIZE_RESTORED:
{
// If the window is currently maximized
if (m_bIsMaximized)
{
// Get the current window rect
GetWindowRect(m_rect);
// Move the window accordingly (to our stored old window)
MoveWindow(m_oldWindow.left, m_oldWindow.top - 18, m_originalRect.Width() - 4, m_originalRect.Height() - 4);
// Get the new window rect
GetWindowRect(m_rect);
// Store our old window as the new rect
m_oldWindow = m_rect;
}
break;
}
}
}
int COpenGLControl::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CWnd::OnCreate(lpCreateStruct) == -1) return -1;
oglInitialize();
return 0;
}
void COpenGLControl::OnDraw(CDC *pDC)
{
// If the current view is perspective...
glLoadIdentity();
glTranslatef(0.0f, 0.0f, -m_fZoom);
glTranslatef(m_fPosX, m_fPosY, 0.0f);
glRotatef(m_fRotX, 1.0f, 0.0f, 0.0f);
glRotatef(m_fRotY, 0.0f, 1.0f, 0.0f);
glScalef(m_scale, m_scale, m_scale);
}
void COpenGLControl::OnTimer(UINT nIDEvent)
{
switch (nIDEvent)
{
case 1:
{
// Clear color and depth buffer bits
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Draw OpenGL scene
oglDrawScene();
// Swap buffers
SwapBuffers(hdc);
break;
}
default:
break;
}
CWnd::OnTimer(nIDEvent);
}
void COpenGLControl::OnMouseMove(UINT nFlags, CPoint point)
{
int diffX = (int)(point.x - m_fLastX);
int diffY = (int)(point.y - m_fLastY);
m_fLastX = (float)point.x;
m_fLastY = (float)point.y;
// Left mouse button
if (nFlags & MK_LBUTTON)
{
m_fRotX += (float)0.5f * diffY;
if ((m_fRotX > 360.0f) || (m_fRotX < -360.0f))
{
m_fRotX = 0.0f;
}
m_fRotY += (float)0.5f * diffX;
if ((m_fRotY > 360.0f) || (m_fRotY < -360.0f))
{
m_fRotY = 0.0f;
}
}
// Right mouse button
else if (nFlags & MK_RBUTTON)
{
m_fZoom -= (float)0.1f * diffY;
}
// Middle mouse button
else if (nFlags & MK_MBUTTON)
{
m_fPosX += (float)0.05f * diffX;
m_fPosY -= (float)0.05f * diffY;
}
OnDraw(NULL);
CWnd::OnMouseMove(nFlags, point);
}
void COpenGLControl::OnLButtonUp(UINT nFlags, CPoint point)
{
//Получаем координаты луча
if(nFlags && MK_CONTROL)
{
m_iNumSelectedSphere = RetrieveObjectID(point.x, point.y, p1, p2); // Задали луч
}
/*int objectID;
objectID = RetrieveObjectID(point.x, point.y);
switch (objectID)
{
case OBJECT_CUBE:
AfxMessageBox(_T("Вы попали в куб!"));
break;
case OBJECT_SPHERE_1:
AfxMessageBox(_T("Выбрана сфера №1!"));
break;
case OBJECT_SPHERE_2:
AfxMessageBox(_T("Выбрана сфера №2!"));
break;
case OBJECT_SPHERE_3:
AfxMessageBox(_T("Выбрана сфера №3!"));
break;
case OBJECT_SPHERE_4:
AfxMessageBox(_T("Выбрана сфера №4!"));
break;
case OBJECT_SPHERE_5:
AfxMessageBox(_T("Выбрана сфера №5!"));
break;
case OBJECT_SPHERE_6:
AfxMessageBox(_T("Выбрана сфера №6!"));
break;
case OBJECT_SPHERE_7:
AfxMessageBox(_T("Выбрана сфера №7!"));
break;
case OBJECT_SPHERE_8:
AfxMessageBox(_T("Выбрана сфера №8!"));
break;
default:
AfxMessageBox(_T("Ничего!"));
break;
break;
}*/
CWnd::OnLButtonUp(nFlags, point);
}
void COpenGLControl::oglCreate(CRect rect, CWnd *parent)
{
CString className = AfxRegisterWndClass(CS_HREDRAW | CS_VREDRAW | CS_OWNDC, NULL, (HBRUSH)GetStockObject(BLACK_BRUSH), NULL);
CreateEx(0, className, "OpenGL", WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, rect, parent, 0);
// Set initial variables' values
m_oldWindow = rect;
m_originalRect = rect;
hWnd = parent;
}
void COpenGLControl::oglInitialize(void)
{
// Initial Setup:
//
static PIXELFORMATDESCRIPTOR pfd =
{
sizeof(PIXELFORMATDESCRIPTOR),
1,
PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER,
PFD_TYPE_RGBA,
32, // bit depth
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
16, // z-buffer depth
0, 0, 0, 0, 0, 0, 0,
};
// Get device context only once.
hdc = GetDC()->m_hDC;
// Pixel format.
m_nPixelFormat = ChoosePixelFormat(hdc, &pfd);
SetPixelFormat(hdc, m_nPixelFormat, &pfd);
// Create the OpenGL Rendering Context.
hrc = wglCreateContext(hdc);
wglMakeCurrent(hdc, hrc);
// Basic Setup:
//
// Set color to use when clearing the background.
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClearDepth(1.0f);
// Turn on backface culling
glFrontFace(GL_CCW);
glCullFace(GL_BACK);
// Turn on depth testing
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
// Send draw request
OnDraw(NULL);
// set settings
glShadeModel(GL_FLAT);
//glEnable(GL_CULL_FACE);
// Set Vertex Array
oglRecalculate(); // считываем вершины
}
void COpenGLControl::oglDrawScene(void)
{
// Необохдимые настройки
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
// Оси
glVertexPointer(3, GL_FLOAT, 0, axisVertex);
glColorPointer(3, GL_FLOAT, 0, axisColor);
glDrawElements(GL_LINES, 6, GL_UNSIGNED_BYTE, axisIndex);
// Заготовка
glVertexPointer(3, GL_FLOAT, 0, cubeVertexArray);
glColorPointer(3, GL_FLOAT, 0, cubeColorArray);
glDrawElements(GL_QUADS, 24, GL_UNSIGNED_BYTE, cubeIndexArray);
// Луч
if(p1 != 0 && p2 !=0 && m_bRayIsVisible) //Попытка отрисовать луч
{
glColor3d(1,1,0);
glBegin(GL_LINES);
glVertex3f(p1.x,p1.y,p1.z);
glVertex3f(p2.x,p2.y,p2.z);
glEnd();
//Отображение передней части луча
/*glColor3d(1,0,0);
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glTranslatef(p1.x,p1.y,p1.z);
auxSolidSphere(0.1);
glPopMatrix();*/
}
// Сферы
for(unsigned i=0; i<SELECTING_OBJECT_COUNT; i++)
{
if(i == m_iNumSelectedSphere)
glColor3ub(100,0,0);
else
glColor3ub(0,100,200);
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glTranslatef(obj[i].x,obj[i].y,obj[i].z);
auxSolidSphere(0.1);
glPopMatrix();
}
//// Sphere 1
//glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
//glColor3ub(0,150,0);
//glMatrixMode(GL_MODELVIEW);
//glPushMatrix();
//glTranslatef(m_start_x,m_start_y,m_start_z);
//gluSphere(m_Obj[0], 0.1f*m_scale, 10, 10);
//glPopMatrix();
//// Sphere 2
//glColor3ub(0,150,0);
//glMatrixMode(GL_MODELVIEW);
//glPushMatrix();
//glTranslatef(m_start_x,m_start_y,m_start_z + m_height);
// gluSphere(m_Obj[1], 0.1f*m_scale, 10, 10);
//glPopMatrix();
//// Sphere 3
//glColor3ub(0,150,0);
//glMatrixMode(GL_MODELVIEW);
//glPushMatrix();
//glTranslatef(m_start_x,m_start_y + m_width,m_start_z + m_height);
// gluSphere(m_Obj[2], 0.1f*m_scale, 10, 10);
//glPopMatrix();
//// Sphere 4
//glColor3ub(0,150,0);
//glMatrixMode(GL_MODELVIEW);
//glPushMatrix();
//glTranslatef(m_start_x,m_start_y + m_width,m_start_z);
// gluSphere(m_Obj[3], 0.1f*m_scale, 10, 10);
//glPopMatrix();
//// Sphere 5
//glColor3ub(0,150,0);
//glMatrixMode(GL_MODELVIEW);
//glPushMatrix();
//glTranslatef(m_start_x + m_length,m_start_y,m_start_z);
//gluSphere(m_Obj[4], 0.1f*m_scale, 10, 10);
//glPopMatrix();
//// Sphere 6
//glColor3ub(0,150,0);
//glMatrixMode(GL_MODELVIEW);
//glPushMatrix();
//glTranslatef(m_start_x + m_length,m_start_y,m_start_z + m_height);
// gluSphere(m_Obj[5], 0.1f*m_scale, 10, 10);
//glPopMatrix();
//// Sphere 7
//glColor3ub(0,150,0);
//glMatrixMode(GL_MODELVIEW);
//glPushMatrix();
//glTranslatef(m_start_x + m_length,m_start_y + m_width,m_start_z + m_height);
// gluSphere(m_Obj[6], 0.1f*m_scale, 10, 10);
//glPopMatrix();
//// Sphere 8
//glColor3ub(0,150,0);
//glMatrixMode(GL_MODELVIEW);
//glPushMatrix();
//glTranslatef(m_start_x + m_length,m_start_y + m_width,m_start_z);
// gluSphere(m_Obj[7], 0.1f*m_scale, 10, 10);
//glPopMatrix();
//glBegin(GL_QUADS);
// // Front Side
// glVertex3f( m_start_x, m_start_y, m_start_z);
// glVertex3f( m_start_x, m_start_y, m_start_z+m_height);
// glVertex3f( m_start_x, m_start_y+m_width, m_start_z+m_height);
// glVertex3f( m_start_x, m_start_y+m_width, m_start_z);
// // Back Side
// glVertex3f( m_start_x+m_length, m_start_y, m_start_z);
// glVertex3f( m_start_x+m_length, m_start_y, m_start_z+m_height);
// glVertex3f( m_start_x+m_length, m_start_y+m_width, m_start_z+m_height);
// glVertex3f( m_start_x+m_length, m_start_y+m_width, m_start_z);
// // Top Side
// glVertex3f( m_start_x, m_start_y, m_start_z+m_height);
// glVertex3f( m_start_x+m_length, m_start_y, m_start_z+m_height);
// glVertex3f( m_start_x+m_length, m_start_y+m_width, m_start_z+m_height);
// glVertex3f( m_start_x, m_start_y+m_width, m_start_z+m_height);
// // Bottom Side
// glVertex3f( m_start_x, m_start_y, m_start_z);
// glVertex3f( m_start_x+m_length, m_start_y, m_start_z);
// glVertex3f( m_start_x+m_length, m_start_y+m_width, m_start_z);
// glVertex3f( m_start_x, m_start_y+m_width, m_start_z);
// // Right Side
// glVertex3f( m_start_x, m_start_y, m_start_z);
// glVertex3f( m_start_x+m_length, m_start_y, m_start_z);
// glVertex3f( m_start_x+m_length, m_start_y, m_start_z+m_height);
// glVertex3f( m_start_x, m_start_y, m_start_z+m_height);
// // Left Side
// glVertex3f( m_start_x, m_start_y+m_width, m_start_z);
// glVertex3f( m_start_x+m_length, m_start_y+m_width, m_start_z);
// glVertex3f( m_start_x+m_length, m_start_y+m_width, m_start_z+m_height);
// glVertex3f( m_start_x, m_start_y+m_width, m_start_z+m_height);
// /*
// // Front Side
// glVertex3f( 1.0f, 1.0f, 1.0f);
// glVertex3f(-1.0f, 1.0f, 1.0f);
// glVertex3f(-1.0f, -1.0f, 1.0f);
// glVertex3f( 1.0f, -1.0f, 1.0f);
// // Back Side
// glVertex3f(-1.0f, -1.0f, -1.0f);
// glVertex3f(-1.0f, 1.0f, -1.0f);
// glVertex3f( 1.0f, 1.0f, -1.0f);
// glVertex3f( 1.0f, -1.0f, -1.0f);
// // Top Side
// glVertex3f( 1.0f, 1.0f, 1.0f);
// glVertex3f( 1.0f, 1.0f, -1.0f);
// glVertex3f(-1.0f, 1.0f, -1.0f);
// glVertex3f(-1.0f, 1.0f, 1.0f);
// // Bottom Side
// glVertex3f(-1.0f, -1.0f, -1.0f);
// glVertex3f( 1.0f, -1.0f, -1.0f);
// glVertex3f( 1.0f, -1.0f, 1.0f);
// glVertex3f(-1.0f, -1.0f, 1.0f);
// // Right Side
// glVertex3f( 1.0f, 1.0f, 1.0f);
// glVertex3f( 1.0f, -1.0f, 1.0f);
// glVertex3f( 1.0f, -1.0f, -1.0f);
// glVertex3f( 1.0f, 1.0f, -1.0f);
// // Left Side
// glVertex3f(-1.0f, -1.0f, -1.0f);
// glVertex3f(-1.0f, -1.0f, 1.0f);
// glVertex3f(-1.0f, 1.0f, 1.0f);
// glVertex3f(-1.0f, 1.0f, -1.0f);
// */
//glEnd();
}
void COpenGLControl::oglFillIn(void)
{
// Вписывает объект в окно openGL
/*
1.Перемещаем объект в центр
2.Найти максимальные координаты по X & Y
3.Выбрать самое максимальное
4.Вписать по выбранной оси
*/
// Перемещаем в центр
m_fPosX = 0; // X position of model in camera view
m_fPosY = 0; // Y position of model in camera view
OnMouseMove(NULL, NULL);
//return;
//
double model[16];
double project[16];
int viewport[4];
double WinPoints[NUMBER_OF_VERTEX][3] = {0};
glGetDoublev(GL_MODELVIEW_MATRIX, model);
glGetDoublev(GL_PROJECTION_MATRIX, project);
glGetIntegerv(GL_VIEWPORT, viewport);
// Получение 2D координат точек в окне
for(unsigned i=0; i<NUMBER_OF_VERTEX; i++)
gluProject(
cubeVertexArray[i][0]
,cubeVertexArray[i][1]
,cubeVertexArray[i][2],
model,project,viewport
,&WinPoints[i][0]
,&WinPoints[i][1]
,&WinPoints[i][2]);
// Находим минимальные и максимальные значения
double maxX, maxY, minX, minY;
maxX = minX = WinPoints[0][0];
maxY = minY = WinPoints[0][1];
for(unsigned i=1; i<NUMBER_OF_VERTEX; i++)
{
if(WinPoints[i][0] > maxX) maxX = WinPoints[i][0];
if(WinPoints[i][0] < minX) minX = WinPoints[i][0];
if(WinPoints[i][1] > maxY) maxY = WinPoints[i][1];
if(WinPoints[i][1] < minY) minY = WinPoints[i][1];
}
// Масштабируем по наибольшей стороне
double objX, objY;
objX = fabs(maxX - minX);
objY = fabs(maxY - minY);
if(objX > objY)
m_fZoom = (float)(viewport[2] / objX);
else
m_fZoom = (float)(viewport[3] / objY);
OnMouseMove(NULL, NULL);
}
void COpenGLControl::oglRecalculate(void)
{
m_start_x = 0 - m_length/2;
m_start_y = 0 - m_width/2;
m_start_z = 0 - m_height/2;
cubeVertexArray[0][0] = m_start_x;
cubeVertexArray[0][1] = m_start_y;
cubeVertexArray[0][2] = m_start_z;
cubeVertexArray[1][0] = m_start_x;
cubeVertexArray[1][1] = m_start_y;
cubeVertexArray[1][2] = m_start_z + m_height;
cubeVertexArray[2][0] = m_start_x;
cubeVertexArray[2][1] = m_start_y + m_width;
cubeVertexArray[2][2] = m_start_z + m_height;
cubeVertexArray[3][0] = m_start_x;
cubeVertexArray[3][1] = m_start_y + m_width;
cubeVertexArray[3][2] = m_start_z;
cubeVertexArray[4][0] = m_start_x + m_length;
cubeVertexArray[4][1] = m_start_y;
cubeVertexArray[4][2] = m_start_z;
cubeVertexArray[5][0] = m_start_x + m_length;
cubeVertexArray[5][1] = m_start_y;
cubeVertexArray[5][2] = m_start_z + m_height;
cubeVertexArray[6][0] = m_start_x + m_length;
cubeVertexArray[6][1] = m_start_y + m_width;
cubeVertexArray[6][2] = m_start_z + m_height;
cubeVertexArray[7][0] = m_start_x + m_length;
cubeVertexArray[7][1] = m_start_y + m_width;
cubeVertexArray[7][2] = m_start_z;
// Переписать инициализацию сфер
for(unsigned i=0; i<SELECTING_OBJECT_COUNT; i++)
{
obj[i].x = cubeVertexArray[i][0];
obj[i].y = cubeVertexArray[i][1];
obj[i].z = cubeVertexArray[i][2];
}
}
int COpenGLControl::RetrieveObjectID(int x, int y, myvector &p1, myvector &p2)
{
/*
Получает объект сцены по координатам мыши
*/
double model[16];
double project[16];
double wx,wy,wz;
int viewport[4];
glGetDoublev(GL_MODELVIEW_MATRIX, model);
glGetDoublev(GL_PROJECTION_MATRIX, project);
glGetIntegerv(GL_VIEWPORT, viewport);
//Получаем ближную точку вектора
gluUnProject(x, viewport[3] - y, -1.0
, model, project, viewport
, &wx, &wy, &wz);
p1.Set((float)wx, (float)wy, (float)wz);
//Получаем дальную точку вектора
gluUnProject(x, viewport[3] - y, 1.0
, model, project, viewport
, &wx, &wy, &wz);
p2.Set((float)wx, (float)wy, (float)wz);
//Поиск точек пересечений
float c1, c2, c3,
p, q, k, R,
x1, y1, z1,
n1, n2, n3;
float D;
float t1, t2;
myvector res1[SELECTING_OBJECT_COUNT]
, res2[SELECTING_OBJECT_COUNT]; // Искомые точки пересечения луча и сфер
// Коэф. луч
c1 = p2.x - p1.x;
c2 = p2.y - p1.y;
c3 = p2.z - p1.z;
x1 = p1.x;
y1 = p1.y;
z1 = p1.z;
// Вычисляем все точки пересечения луча со всеми сферами на сцене
// res[N] - координаты пересечения со сферой [N]
// где N - номер сферы;
for(unsigned i=0; i<SELECTING_OBJECT_COUNT; i++)
{
p = obj[i].x;
q = obj[i].y;
k = obj[i].z;
R = 0.1f;
// Формулы
n1 = c1*c1 + c2*c2 + c3*c3;
n2 = -2 * (c1 * (x1 - p) + c2 * (y1 - q) + c3 * (z1 - k));
n3 = (x1 - p) * (x1 - p) + (y1 - q) * (y1 - q) + (z1 - k) * (z1 - k) - (R * R);
D = n2*n2 - 4 * n1 * n3;
if(D > 0)
{
// Луч прошел через сферу
//AfxMessageBox(_T("D > 0"));
t1 = (- n2 + sqrt(D)) / 2 * n1;
t2 = (- n2 - sqrt(D)) / 2 * n1;
res1[i].x = t1 * c1 - x1;
res1[i].y = t1 * c2 - y1;
res1[i].z = t1 * c3 - z1;
res2[i].x = t2 * c1 - x1;
res2[i].y = t2 * c2 - y1;
res2[i].z = t2 * c3 - z1;
}
else
if(D == 0)
{
// Луч прошес по касательной к сфере
//AfxMessageBox(_T("D = 0"));
t1 = (- n2 + sqrt(D)) / 2 * n1;
res1[i].x = t1 * c1 - x1;
res1[i].y = t1 * c2 - y1;
res1[i].z = t1 * c3 - z1;
}
else
{
//AfxMessageBox(_T("D < 0"));
}
}
// Выбираем наиболее ближайший к нам объект
float ResMassiv[NUMBER_OF_INTERSECTION][2];
int index_selected_sphere = 0;
float minvek;
minvek = sqrt((p2.x-p1.x)*(p2.x-p1.x) + (p2.y-p1.y) * (p2.y-p1.y) + (p2.z-p1.z) * (p2.z-p1.z));
float curvek = minvek;
int count = 0; // Количество сфер через которые прошел луч
for(unsigned i=0; i<SELECTING_OBJECT_COUNT; i++)
{
curvek = sqrt((res1[i].x-p1.x)*(res1[i].x-p1.x) + (res1[i].y-p1.y) * (res1[i].y-p1.y) + (res1[i].z-p1.z) * (res1[i].z-p1.z));
if(curvek > minvek)
{
ResMassiv[count][0] = curvek;
ResMassiv[count][1] = (float)i;
if(count < SELECTING_OBJECT_COUNT)
count++;
}
}
float min_length = ResMassiv[0][0];
index_selected_sphere = (int)ResMassiv[0][1];
for(unsigned i=1; i<NUMBER_OF_INTERSECTION; i++)
{
if(ResMassiv[i][0] > 0)
{
if(ResMassiv[i][0] < min_length)
{
min_length = ResMassiv[i][0];
index_selected_sphere = (int)ResMassiv[i][1];
}
}
}
return index_selected_sphere;
} | [
"[email protected]"
]
| |
916a8810d692fb104499c4d8a681a4267f1338c1 | a757717dbd1fcffe2cb2dc1f7accdc74e78d2396 | /Hex/Graph.cpp | 18f245b78ce7a34ca23b15b92931eb582bfec6fe | [
"Unlicense"
]
| permissive | Neuromancer2701/Hex | 299453a8f7b2299463dec57da91f83fbd2907c74 | acc950140b8b8a9f6443b2b338a32d64d7df6740 | refs/heads/master | 2021-01-19T18:06:35.537489 | 2013-11-18T01:26:24 | 2013-11-18T01:26:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,752 | cpp | /*
* Graph.cpp
*
* Created on: Oct 25, 2013
* Author: SK1033
*/
#include "Graph.h"
#include <set>
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <ctime>
#include <algorithm>
using std::find;
using std::cout;
using std::endl;
using std::multiset;
using std::ifstream;
//blank constructor
Graph::Graph(){
size = 0;
}
//
void Graph::GenerateGraph(int _size) {
Node n;
size = _size;
n.name = 0;
for(int x = 0; x < size; x++ )
{
for(int y = 0; y < size; y++ )
{
n.coords.first = x;
n.coords.second = y;
FillEdges(n);
nodes.push_back(n);
n.name++;
}
}
}
Graph::~Graph() {
// TODO Auto-generated destructor stub
}
// Is this a valid free node
bool Graph::ValidNode(int x, int y)
{
bool return_value = false;
unsigned int node_name = x * size + y;
if(node_name < nodes.size())
{
if(nodes[node_name].state == State::free)
{
return_value = true;
}
}
return return_value;
}
// Set Node to occupied by state
void Graph::Move(State state, int x, int y)
{
int node_name = x * size + y;
nodes[node_name].state = state;
}
bool Graph::Player1Winner()
{
bool return_value = false;
vector<int> start_nodes; //Top of the Hex board
vector<int> end_nodes; //Bottom Of the Hex Board
vector<int> tree;
vector<Node> openlist;
for(int i = 0; i < size; i++)
{
start_nodes.push_back(i);
end_nodes.push_back((size * size) - (i+1));
}
for( auto i : start_nodes)
{
openlist.push_back(nodes[i]);
}
//Create a tree starting Top nodes Winner when tree includes a start node and end node.
while(openlist.size() > 0)
{
if(openlist[0].state == State::X)
{
for( auto edge :openlist[0].Edges)
{
openlist.push_back(nodes[edge.destination]);
}
tree.push_back(openlist[0].name);
openlist.erase(openlist.begin());
}
else
{
openlist.erase(openlist.begin());
}
for( auto end : end_nodes)
{
if(find(tree.begin(), tree.end(), end) != tree.end() )
{
return_value = true;
}
}
}
return return_value;
}
bool Graph::Player2Winner()
{
bool return_value = false;
vector<int> start_nodes; //Left of the Hex board
vector<int> end_nodes; //Right Of the Hex Board
vector<int> tree; // Path to victor
vector<Node> openlist; //List of Nodes connected to a
for(int i = 0; i < size; i++)
{
start_nodes.push_back(i * size );
end_nodes.push_back((i * size) + size);
}
for( auto i : start_nodes)
{
openlist.push_back(nodes[i]);
}
//Create a tree starting Top nodes Winner when tree includes a start node and end node.
while(openlist.size() > 0)
{
if(openlist[0].state == State::O)
{
for( auto edge :openlist[0].Edges)
{
openlist.push_back(nodes[edge.destination]);
}
tree.push_back(openlist[0].name);
openlist.erase(openlist.begin());
}
else
{
openlist.erase(openlist.begin());
}
for( auto end : end_nodes)
{
if(find(tree.begin(), tree.end(), end) != tree.end() )
{
return_value = true;
}
}
}
return return_value;
}
// Creates Edges for each Node
void Graph::FillEdges(Node& node)
{
Edge edge;
vector<pair<int,int>> directions;
directions.push_back(std::make_pair(-1, 1));
directions.push_back(std::make_pair( 1,-1));
directions.push_back(std::make_pair( 0, 1));
directions.push_back(std::make_pair( 1, 0));
directions.push_back(std::make_pair( 0,-1));
directions.push_back(std::make_pair(-1, 0));
for( auto d : directions)
{
int x = d.first + node.coords.first; //add direction to current node coo
int y = d.second + node.coords.second;
if((x < 0) || (y < 0) || (x == size) || (y == size)) //negative and size values are not valid
continue;
edge.source = node.name;
edge.destination = x * size + y;
edge.cost = 1.0;
}
}
| [
"[email protected]"
]
| |
cff821ac42c440d16c7196e97e534de329e6c2e4 | 84808d7bb4255815f54449c62426e1b23f5c6125 | /utility.cpp | d0769a5958333694aa20cdb8a51a34daf29a0e4c | []
| no_license | codeworm96/yet_another_basic | fa14d160a7eb73e1e58f4d413bfb7473c2aa2ddc | 8a29e891d99ab3a737e3da94be509ffde72b736a | refs/heads/master | 2016-08-11T15:59:20.512459 | 2015-05-24T15:42:14 | 2015-05-24T15:42:14 | 36,179,088 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 671 | cpp | #include <iostream>
#include <sstream>
#include <string>
#include "../StanfordCPPLib/error.h"
#include "utility.h"
int str2int(std::string s)
{
std::istringstream iss(s);
int res;
iss >> res >> std::ws;
if (iss.eof()){
return res;
}else{
error("SYNTAX ERROR"); //I think this kind of error should be invalid number, but INVALID NUMBER is only for INPUT
}
}
int input_int()
{
while(true){
std::string s;
std::cout << " ? "; //prompt
std::getline(std::cin, s);
try{
return str2int(s);
}catch(...){
std::cout << "INVALID NUMBER" << std::endl;
}
}
}
| [
"[email protected]"
]
| |
680a4b3230ed02012faa1be7e6578e59d461247f | 2fba0c8ea5f69b5afe60a9a273eb18ec519059fe | /sprout/operation/fit/set.hpp | 1151f0f8b02b5622ee0f744b88933303e2799448 | [
"BSL-1.0"
]
| permissive | jwakely/Sprout | 683acb3ea214526eedf2b656a70a25a2be6e1b3a | a64938fad0a64608f22d39485bc55a1e0dc07246 | refs/heads/master | 2021-01-16T17:51:20.841753 | 2012-07-25T05:27:01 | 2012-07-25T05:27:01 | 5,179,121 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,682 | hpp | #ifndef SPROUT_OPERATION_FIT_SET_HPP
#define SPROUT_OPERATION_FIT_SET_HPP
#include <cstddef>
#include <sprout/config.hpp>
#include <sprout/container/traits.hpp>
#include <sprout/container/functions.hpp>
#include <sprout/operation/fixed/set.hpp>
#include <sprout/sub_array.hpp>
namespace sprout {
namespace fit {
namespace result_of {
//
// set
//
template<typename Container, typename T>
struct set {
public:
typedef sprout::sub_array<
typename sprout::container_traits<
typename sprout::fixed::result_of::set<Container, T>::type
>::internal_type
> type;
};
} // namespace result_of
//
// set
//
template<typename Container, typename T>
inline SPROUT_CONSTEXPR typename sprout::fit::result_of::set<Container, T>::type set(
Container const& cont,
typename sprout::container_traits<Container>::const_iterator pos,
T const& v
)
{
return sprout::sub_copy(
sprout::get_internal(sprout::fixed::set(cont, pos, v)),
sprout::internal_begin_offset(cont),
sprout::internal_end_offset(cont)
);
}
//
// set
//
template<typename Container, typename T>
inline SPROUT_CONSTEXPR typename sprout::fit::result_of::set<Container, T>::type set(
Container const& cont,
typename sprout::container_traits<Container>::difference_type pos,
T const& v
)
{
return sprout::sub_copy(
sprout::get_internal(sprout::fixed::set(cont, pos, v)),
sprout::internal_begin_offset(cont),
sprout::internal_end_offset(cont)
);
}
} // namespace fit
} // namespace sprout
#endif // #ifndef SPROUT_OPERATION_FIT_SET_HPP
| [
"[email protected]"
]
| |
b50de851e3430986f3c7050b3ac2830d7d64a2e7 | 40429db1f9185e37fab79757fafb11096e3bbd90 | /avl/funcoes.h | c6442677d6c47e902e9645b2d626210abd91ca84 | []
| no_license | gaabrielfranco/AVL | 176c3b1a4646d171cd84e0a74314e45349d87a57 | 18902361b06af3a677c4354a835c1b0e4c000a3b | refs/heads/master | 2020-03-07T19:58:33.401157 | 2018-04-02T11:38:37 | 2018-04-02T11:38:37 | 127,684,875 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 628 | h | /***************
** ARQUIVO: ArvoreBin.cpp
** GRUPO:
** Marcos Valério de Carvalho Loures - 81827
** Gabriel Vita Silva Franco - 79208
***************/
#ifndef FUNCOES_H
#define FUNCOES_H
#include <iostream>
#include <fstream>
#include <string>
#include "ArvoreAvl.h"
using namespace std;
bool leDadosSequencial(string, ArvoreAvl *, bool);
bool leDados(string, ArvoreAvl *);
void limpaTela();
int exibeMenu();
void executaOpcao(int, ArvoreAvl *, bool &);
char leChar();
int converteNum(string);
void salva(string, ArvoreAvl *);
void salvaGrafico(string, ArvoreAvl *);
string leNomeArquivo();
#endif // FUNCOES_H
| [
"[email protected]"
]
| |
3b1972c7337e835896a4475a300a79291544d6ce | d1456d37347e53717f1354f4fb528733dc090fc0 | /A/fileAdvance.cpp | 1bb93c117a96a85defc7907c50de95fc38cadc00 | []
| no_license | vvaibhav3/cpp | c7b4755d1027f1acb5a98819572395416a75e772 | 8537e588f2f2ff91193826e5c29a35b5a0c22ac3 | refs/heads/master | 2023-07-21T20:02:44.161342 | 2021-08-21T15:01:12 | 2021-08-21T15:01:12 | 341,088,951 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,093 | cpp | #include<iostream>
#include<fstream>
#include<iomanip>
#define SIZE 1024
using namespace std;
struct data{
char lable[SIZE],mnemonic[SIZE],op1[SIZE],op2[SIZE];
};
ostream &operator<<(ostream &stream,struct data s1){
stream<<s1.lable<<" "<<s1.mnemonic<<" "<<s1.op1<<" "<<s1.op2<<"\n";
return stream;
}
int main(){
struct data s1;
char ch='y';
ofstream ofs;
ofs.open("prgm1.dat",ios::out | ios::binary);
//system("0A);
cout<<"\n---------->Instruction <--------------- \n\n";
cout<<"\a1.Add ('-') for empty field \n2.Format of statement is : <lable> <mnemonic> <op1> <op2> \n3.To terminate enter keyword ('~') on new line\n\n";
cout<<"Write your code >>>> \n";
while(1){
cin>>s1.lable;
ch=s1.lable[0];
if(ch=='~')
break;
cin>>s1.mnemonic>>s1.op1>>s1.op2;
ofs.write((char *) &s1,sizeof(struct data));
}
ofs.close();
if(!ofs.good())
cout<<"error occured in writing.......\n";
ifstream ifs;
ifs.open("prgm1.dat",ios::in | ios::binary);
while(1){
ifs.read((char*)&s1,sizeof(struct data));
if(ifs)
cout<<s1;
else
break;
}
ifs.close();
return 0;
}
| [
"[email protected]"
]
| |
a08c06696de6145dd5cf01d126e16823b37b18ee | 02ba16bfef164e89ceb63f8ef073cbba1286c0ce | /week4/Rational4.cpp | 44b59861ddb1cbcf5f31bb379c6a0ca0d786fc09 | []
| no_license | nurSaadat/100DaysOfCode | b0bbc4374571535c035ed2e14a7a92811e25b976 | b808bf23223f63c54799f62791740f33f7721cd3 | refs/heads/master | 2021-03-24T02:16:57.299630 | 2020-06-18T12:58:17 | 2020-06-18T12:58:17 | 247,506,604 | 1 | 0 | null | 2020-03-15T16:35:26 | 2020-03-15T16:35:25 | null | UTF-8 | C++ | false | false | 4,341 | cpp | #include <iostream>
#include <string>
#include <iomanip>
using namespace std;
class Rational {
public:
Rational()
{
num = 0;
denom = 1;
}
Rational(int numerator, int denominator)
{
if (numerator == 0)
{
num = 0;
denom = 1;
}
else
{
if (denominator < 0)
{
denominator *= -1;
numerator *= -1;
}
bool is_negative = false;
if (numerator < 0)
{
is_negative = true;
numerator *= -1;
}
int gcd = GCD(numerator, denominator);
num = numerator / gcd;
if (is_negative)
{
num *= -1;
}
denom = denominator / gcd;
}
}
int Numerator() const
{
return num;
}
int Denominator() const
{
return denom;
}
private:
int num;
int denom;
int GCD(int a, int b)
{
while (a > 0 && b > 0)
{
if (a > b)
{
a %= b;
}
else
{
b %= a;
}
}
return a + b;
}
};
bool operator==(const Rational& lhs, const Rational& rhs)
{
if (lhs.Numerator() == rhs.Numerator() && lhs.Denominator() == rhs.Denominator())
{
return true;
}
else
{
return false;
}
}
Rational operator+(const Rational& lhs, const Rational& rhs)
{
if (rhs.Denominator() == lhs.Denominator())
{
return Rational(lhs.Numerator() + rhs.Numerator(), lhs.Denominator());
}
else
{
return Rational(lhs.Numerator() * rhs.Denominator() + rhs.Numerator() * lhs.Denominator(),
lhs.Denominator() * rhs.Denominator());
}
}
Rational operator-(const Rational& lhs, const Rational& rhs)
{
if (rhs.Denominator() == lhs.Denominator())
{
return Rational(lhs.Numerator() - rhs.Numerator(), lhs.Denominator());
}
else
{
return Rational(lhs.Numerator() * rhs.Denominator() - rhs.Numerator() * lhs.Denominator(),
lhs.Denominator() * rhs.Denominator());
}
}
Rational operator*(const Rational& lhs, const Rational& rhs)
{
return Rational(lhs.Numerator() * rhs.Numerator(), lhs.Denominator() * rhs.Denominator());
}
Rational operator/(const Rational& lhs, const Rational& rhs)
{
return Rational(lhs.Numerator() * rhs.Denominator(), lhs.Denominator() * rhs.Numerator());
}
istream& operator>>(istream& s, Rational& r)
{
int num = r.Numerator();
int denom = r.Denominator();
if (s)
{
s >> num;
s.ignore(1);
s >> denom;
}
r = Rational(num, denom);
return s;
}
ostream& operator<<(ostream& s, const Rational& r)
{
s << r.Numerator() << '/' << r.Denominator();
return s;
}
int main() {
{
ostringstream output;
output << Rational(-6, 8);
if (output.str() != "-3/4") {
cout << "Rational(-6, 8) should be written as \"-3/4\"" << endl;
return 1;
}
}
{
istringstream input("5/7");
Rational r;
input >> r;
bool equal = r == Rational(5, 7);
if (!equal) {
cout << "5/7 is incorrectly read as " << r << endl;
return 2;
}
}
{
istringstream input("5/7 10/8");
Rational r1, r2;
input >> r1 >> r2;
bool correct = r1 == Rational(5, 7) && r2 == Rational(5, 4);
if (!correct) {
cout << "Multiple values are read incorrectly: " << r1 << " " << r2 << endl;
return 3;
}
input >> r1;
input >> r2;
correct = r1 == Rational(5, 7) && r2 == Rational(5, 4);
if (!correct) {
cout << "Read from empty stream shouldn't change arguments: " << r1 << " " << r2 << endl;
return 4;
}
}
cout << "OK" << endl;
return 0;
}
| [
"[email protected]"
]
| |
7a0b79d604937d51230b441b7a749b4e32b4f854 | 432c0ff96204aa28d58e71209f0c8f037c412342 | /acmicpc/11720.cpp | 41f76f1b8bc36541a2021ffa95a1f549a6e9e4aa | []
| no_license | HONEY1b/tuestudy | be3323c7c7d614c7ec3135bb37bde96bb58a42fb | 6fe90032eb31e11f56f62a8f778edfa522264bfd | refs/heads/master | 2021-07-10T18:41:51.814989 | 2020-11-24T12:37:42 | 2020-11-24T12:37:42 | 209,746,267 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 233 | cpp | //11720
#include<stdio.h>
#include<iostream>
using namespace std;
int main(void){
int n;
scanf("%d",&n);
char arr[100];
int total=0;
for(int i=0;i<n;i++){
cin>>arr[i];
total+=arr[i]-48;
}
cout<<total<<'\n';
return 0;
}
| [
"[email protected]"
]
| |
628133174ddeaea1ca2480ea3fa7dd0303d07bf4 | db365c07a0121316cf6d3ec886bd55e28719824a | /Line drawer/main.cpp | 0ebe86cb54a06d33159d2b3164c5c6507fe756f5 | []
| no_license | koalaa13/Comp-Graphics | 46212cb64d7ba11b6191e47d69e6b7f4a48343ed | 07ae60a00b01ce6b496fa29542a3196608202811 | refs/heads/master | 2021-01-02T11:08:13.680758 | 2020-06-26T09:33:17 | 2020-06-26T09:33:17 | 239,594,864 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,133 | cpp | #include "Utils.h"
#include "ImageFile.h"
#include "PNMImage.h"
int main(int argc, char *argv[]) {
if (argc != 10 && argc != 9) {
printError(
"You should enter input filename, output filename, brightness, thickness, coordinates of line and (optionally) gamma");
}
try {
double gamma = 2.2; // Default value for sRGB gamma correction
ImageFile in(argv[1], "rb");
PNMImage image(in);
bool srgb = true;
if (argc == 10) {
gamma = std::stod(argv[9]);
srgb = false;
}
image.drawLine(std::stoi(argv[3]),
std::stod(argv[4]),
(int) std::stod(argv[5]),
(int) std::stod(argv[6]),
(int) std::stod(argv[7]),
(int) std::stod(argv[8]),
gamma,
srgb);
ImageFile out(argv[2], "wb");
image.writeToFile(out);
} catch (std::exception const &e) {
printError("Error, occurred while drawing a line: " + std::string(e.what()));
}
return 0;
}
| [
"[email protected]"
]
| |
26aeeec213f1c23b4c2a66b25ef9cb05c0aaa489 | 6c945f5861276389d565fc2326ddfd069f61e6a9 | /src/boost/spirit/repository/include/qi_confix.hpp | 3a7b0efae3d00c950947ae120b13c4ec65e74b9d | []
| no_license | Springhead/dependency | 3f78387d2a50439ce2edf7790a296026c6012fa3 | 05d4e6f9a3e9c21aae8db4b47573aa34058c4705 | refs/heads/master | 2023-04-23T23:40:13.402639 | 2021-05-08T05:55:22 | 2021-05-08T05:55:22 | 112,149,782 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 656 | hpp | /*=============================================================================
Copyright (c) 2001-2010 Joel de Guzman
Copyright (c) 2001-2010 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_REPOSITORY_INCLUDE_QI_CONFIX
#define BOOST_SPIRIT_REPOSITORY_INCLUDE_QI_CONFIX
#if defined(_MSC_VER)
#pragma once
#endif
#include <boost/spirit/repository/home/qi/directive/confix.hpp>
#endif
| [
"[email protected]"
]
| |
fe3700068f8e21d2319d7f77e991f9d0a8f3e493 | 1d139cccff2876f0e079cb51f26a6be78e0a4457 | /boj/solved/2739/main.cpp | 20d6debe6293fc8526d1cad29f1a2fd091ac4c6b | []
| no_license | kckjn97/algorithm-training | 5997564bd833e9299a7f64d28e921532f9713724 | bd0650585ef636013f261f4458e02e8f81e64f04 | refs/heads/master | 2023-01-30T00:41:14.751032 | 2020-12-10T14:54:26 | 2020-12-10T14:54:26 | 205,655,617 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 154 | cpp | #include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
for(int i=1; i<=9; i++)
cout << n << " * " << i << " = " << n*i << endl;
}
| [
"[email protected]"
]
| |
5060e93ae8a23f0c342373863e90b68cc91bf4b9 | d2f30d9fb226185956c3da1e5372664aaa506312 | /msvis/MSVis/MSContinuumSubtractor.h | c1029d8b0b52a54c95cb477a90b83370ef2d18a2 | []
| no_license | radio-astro/casasynthesis | 1e2fdacfcfc4313adde8f7524739a4dfd80d4c8f | 1cb9cd6a346d3ade9a6f563696d225c24654041c | refs/heads/master | 2021-01-17T05:22:01.380405 | 2019-01-08T10:43:34 | 2019-01-08T10:43:34 | 40,664,934 | 1 | 1 | null | 2022-12-16T13:17:36 | 2015-08-13T15:01:41 | C++ | UTF-8 | C++ | false | false | 4,397 | h | //# MSContinuumSubtractor.h: Fit & subtract continuum from spectral line data
//# Copyright (C) 2004
//# Associated Universities, Inc. Washington DC, USA.
//#
//# This library is free software; you can redistribute it and/or modify it
//# under the terms of the GNU Library General Public License as published by
//# the Free Software Foundation; either version 2 of the License, or (at your
//# option) any later version.
//#
//# This library is distributed in the hope that it will be useful, but WITHOUT
//# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
//# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public
//# License for more details.
//#
//# You should have received a copy of the GNU Library General Public License
//# along with this library; if not, write to the Free Software Foundation,
//# Inc., 675 Massachusetts Ave, Cambridge, MA 02139, USA.
//#
//# Correspondence concerning AIPS++ should be addressed as follows:
//# Internet email: [email protected].
//# Postal address: AIPS++ Project Office
//# National Radio Astronomy Observatory
//# 520 Edgemont Road
//# Charlottesville, VA 22903-2475 USA
//#
//# $Id$
//#
#ifndef MS_MSCONTINUUMSUBTRACTOR_H
#define MS_MSCONTINUUMSUBTRACTOR_H
#include <casa/aips.h>
#include <casa/BasicSL/String.h>
#include <ms/MeasurementSets/MSColumns.h>
namespace casa { //# NAMESPACE CASA - BEGIN
class MeasurementSet;
class LogIO;
// <summary>Fits and subtracts or models the continuum in spectra</summary>
// <use visibility=export>
//
// <reviewed reviewer="" date="yyyy/mm/dd" tests="" demos="">
// </reviewed>
//
// <prerequisite>
// <li> <linkto class=MeasurementSet>MeasurementSet</linkto>
// </prerequisite>
//
// <etymology>
// This class's main aim is to subtract the continuum from spectral line data.
// </etymology>
//
// <synopsis>
// Spectral line observations often contain continuum emission which is
// present in all channels (often with small slope across band). This
// class fits this continuum and subtracts it, replacing either the
// corrected data or the model data column.
// </synopsis>
//
// <example>
// <srcBlock>
// MS inMS(fileName);
// MSContinuumSubtractor mssub(inMS);
// mssub.setDataDescriptionIds(ddIds);
// mssub.setFields(fieldIds);
// mssub.setSolutionInterval(10.0);
// mssub.setMode("subtract");
// mssub.subtract();
// </srcBlock>
// A <src>MSContinuumSubtractor</src> object is constructed
// and the continuum is subtracted with a 10.0s averaging time for the fit.
// </example>
//
// <motivation>
// This class replaces existing functionality at the glish level, in an
// attempt to speed up the continuum subtraction process.
// </motivation>
//
// <todo asof="">
// </todo>
class MSContinuumSubtractor
{
public:
// Constructor
MSContinuumSubtractor (MeasurementSet& ms);
// Assignment (only copies reference to MS, need to reset selection etc)
MSContinuumSubtractor& operator=(MSContinuumSubtractor& other);
// Destructor
~MSContinuumSubtractor();
// Set the required field Ids
void setField(const String& field);
void setFields(const Vector<Int>& fieldIds);
// Set the channels to use in the fit
void setFitSpw(const String& fitspw);
void setSubSpw(const String& subspw);
// Set the required spws (ddids)
void setDataDescriptionIds(const Vector<Int>& ddIds);
// Set the solution interval in seconds, the value zero implies scan averaging
void setSolutionInterval(Float solInt);
// Set the solution interval in seconds, the value zero implies scan averaging
void setSolutionInterval(String solInt);
// Set the order of the fit (1=linear)
void setOrder(Int order);
// Set the processing mode: subtract, model or replace
void setMode(const String& mode);
// Do the subtraction (or save the model)
void subtract();
private:
// Pointer to MS
MeasurementSet* ms_p;
// DataDescription Ids to process
Vector<Int> itsDDIds;
// Field Ids to process
Vector<Int> itsFieldIds;
// Channels to use in fit
Matrix<Int> itsFitChans;
// Channels to subtract from
Matrix<Int> itsSubChans;
// Solution interval for fit
Float itsSolInt;
// Order of the fit
Int itsOrder;
// Processing mode
String itsMode;
// Number of spws
Int nSpw_;
};
} //# NAMESPACE CASA - END
#endif
| [
"[email protected]"
]
| |
f043732542c3f378cc34db759da498ee5ae38bd1 | 9638292ebb37f5d578740b47185ccf9232371db6 | /Section11/FunctionCalls/main.cpp | a9b3e555840f81ce1f423330ad570da33b913817 | []
| no_license | Cr0ckyy/udemy_cpp | 803495ef188a6f1bd43f8ac0b32bfbf2456a5169 | cc144eef3d08340dcb3d9405ddebe612dc8aa61a | refs/heads/master | 2022-03-10T16:19:22.408605 | 2019-11-18T19:25:22 | 2019-11-18T19:25:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 492 | cpp | #include <iostream>
#include <vector>
#include <iomanip>
#include <cmath>
using namespace std;
void func2(int &x, int y, int z);
int func1(int a, int b);
// result is changed inplace because of &x
void func2(int &x, int y, int z){
x += z + y;
}
int func1(int a, int b) {
int result {};
result = a + b;
func2(result, a, b);
return result;
}
int main(){
int x {10};
int y {20};
int z {};
z = func1(x, y);
cout << z << endl;
return 0;
} | [
"[email protected]"
]
| |
a5f31ebb6bab64f0d9c8aaf4d4355f15b827ff79 | 93bf6cabf6836d7c4dd3e1b33add7bfd1a77e26c | /src/discovery/DeviceType.h | f7ceca9a4a38e5495947360f36d6d68f4d31c122 | [
"MIT"
]
| permissive | harujioh/ofxPixelPusher | e358a3bb2b773c9bdf3b87840c818d3a47da0611 | 2bb0bf0bec5c6d43f15b123844d22679d5dc3ef6 | refs/heads/master | 2016-09-13T21:13:01.774386 | 2016-05-11T19:45:36 | 2016-05-11T19:45:36 | 58,575,403 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 903 | h | #pragma once
#include <string>
namespace DeviceDiscovery {
/**
* デバイスの種類
*/
enum DeviceType {
ETHERDREAM = 0,
LUMIABRIDGE = 1,
PIXELPUSHER = 2,
OTHER
};
/**
* デバイスの種類を取得
*/
inline DeviceType getDeviceType(int num) {
switch (num) {
case 0:
return ETHERDREAM;
case 1:
return LUMIABRIDGE;
case 2:
return PIXELPUSHER;
default:
return OTHER;
}
}
/**
* デバイスの種類名を取得
*/
inline std::string getDeviceTypeName(DeviceType type) {
switch (type) {
case ETHERDREAM:
return std::string("ETHERDREAM");
case LUMIABRIDGE:
return std::string("LUMIABRIDGE");
case PIXELPUSHER:
return std::string("PIXELPUSHER");
case OTHER:
default:
return "OTHER";
}
}
} | [
"[email protected]"
]
| |
bb6ed20938d9f4c981552a65326ee723b58ee392 | 0eb4cac7ac26506ea89724f671ece6ccdfbf139f | /lib/branches/initialStateLib/src/lorentz.cpp | 38e91c30e31a2069c8a1f9305ec6eb64357aba38 | []
| no_license | Ajiperuyellow/IPGLAMPS | c68be6d6e21cde85ff7a59bfafe1f5c34e5b5a84 | 9b3b8f2ad8b15745da07eb71144a56d74213f652 | refs/heads/master | 2020-04-18T02:40:24.007024 | 2019-03-21T16:39:35 | 2019-03-21T16:39:35 | 167,171,792 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 37,068 | cpp | //--------------------------------------------------------- -*- c++ -*- ------
//$HeadURL: file:///home/bamps/svn/lib/branches/initialStateLib/src/lorentz.cpp $
//$LastChangedDate: 2019-01-05 18:04:29 +0100 (Sa, 05. Jan 2019) $
//$LastChangedRevision: 2918 $
//$LastChangedBy: greif $
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
#include <iostream>
#include <math.h>
#include "lorentz.h"
///// set Beta /////
void lorentz::setBeta( const vector4D & beta0 )
{
#if defined (VECTOR_IMPL_SSE) || defined (VECTOR_IMPL_AVX)
SSE_ALIGNED(static const double) One = 1.0;
__m128d xG_lo = _mm_load_pd( beta0.Mem );
__m128d xG_hi = _mm_load_pd( beta0.Mem+2 );
xG_lo = _mm_loadl_pd( xG_lo, &One ); // set the lower value to 1.0
setBeta( xG_lo, xG_hi );
#else
setBetaScalar( beta0 );
#endif
}
void lorentz::setBetaScalar( const vector4D & beta0 )
{
vector4D beta = beta0;
if (fabs(beta(0)-1.0)>1e-5)
{
// std::cout << "WARNING: beta(0) != 1 !!!" << std::endl;
// std::cout << beta << std::endl << std::endl;
// std::string errMsg = "WARNING: beta(0) != 1 !!!";
// throw eLorentz_error( errMsg );
beta(0) = 1.0;
}
double g = beta.M2_Scalar(); // = 1 - b^2
if (g < 0)
{
std::cout << "ERROR: beta^2 > 1: g=" << g << std::endl;
std::cout << beta << std::endl << std::endl;
return;
}
g = 1/sqrt(g);
double gg = g*g/(1+g);
for (unsigned int i=1;i<4;i++)
for (unsigned int j=1;j<4;j++)
Arr[i+4*j] = gg * beta[i] * beta[j];
for (unsigned int i=1;i<4;i++)
Arr[i] = Arr[4*i] = g * beta[i];
Arr[0] = g;
for (unsigned int i=1;i<4;i++)
Arr[i+4*i] += 1;
}
void lorentz::setBetaCM( const vector4D & x1 )
{
#if defined (VECTOR_IMPL_SSE) || defined (VECTOR_IMPL_AVX)
// x1:
__m128d xlo = _mm_load_pd( x1.Mem );
__m128d xhi = _mm_load_pd( x1.Mem+2 );
// normalize:
__m128d xOne = _mm_set1_pd( 1.0 );
__m128d xE = _mm_unpacklo_pd( xlo, xlo );
xE = _mm_div_pd( xOne, xE );
xlo = _mm_mul_pd( xlo, xE );
xhi = _mm_mul_pd( xhi, xE );
// set beta:
setBeta( xlo, xhi );
#else
setBetaCMScalar( x1 );
#endif
}
void lorentz::setBetaCMScalar( const vector4D & x1 )
{
vector4D beta = x1;
beta *= 1/beta[0];
setBetaScalar( beta );
}
void lorentz::setBetaCM( const vector4D & x1, const vector4D & x2 )
{
#if defined (VECTOR_IMPL_SSE) || defined (VECTOR_IMPL_AVX)
// x1 + x2:
__m128d xlo = _mm_load_pd( x1.Mem );
__m128d xhi = _mm_load_pd( x1.Mem+2 );
__m128d xlo2 = _mm_load_pd( x2.Mem );
__m128d xhi2 = _mm_load_pd( x2.Mem+2 );
xlo = _mm_add_pd( xlo, xlo2 );
xhi = _mm_add_pd( xhi, xhi2 );
// normalize:
__m128d xOne = _mm_set1_pd( 1.0 );
__m128d xE = _mm_unpacklo_pd( xlo, xlo );
xE = _mm_div_pd( xOne, xE );
xlo = _mm_mul_pd( xlo, xE );
xhi = _mm_mul_pd( xhi, xE );
// set beta:
setBeta( xlo, xhi );
#else
setBetaCMScalar( x1, x2 );
#endif
}
void lorentz::setBetaCMScalar( const vector4D & x1, const vector4D & x2 )
{
vector4D beta = x1 + x2;
beta *= 1/beta[0];
setBetaScalar( beta );
}
void lorentz::setBetaCM( const vector4D & x1, const vector4D & x2, const vector4D & x3)
{
setBeta( (x1+x2+x3).NormalizeToE() );
}
///// BOOST ONE VECTOR /////
vector4D lorentz::boost( const vector4D & x ) const
{
#if defined (VECTOR_IMPL_SSE)
// please note: we have to be careful with the signs of the matrix:
// The components [0][i] and [i][0] have to be negated!
// we also use _mm_prefetch in order to load some memory into a
// cache closer to the processor.
_MM_PREFETCH(x.Mem, _MM_HINT_NTA);
SSE_ALIGNED(const unsigned long long) S = 0x8000000000000000ull ;
// cppcheck-suppress invalidPointerCast
__m128d xS10 = _mm_load_sd( (double *)&S ); // only lower part negates
__m128d xS01 = _mm_setzero_pd( ); // set it to zero
__m128d xS11 = _mm_unpacklo_pd( xS10, xS10 ); // both parts negate
xS01 = _mm_unpacklo_pd( xS01, xS10 ); // only upper part negates
_MM_PREFETCH(Arr, _MM_HINT_NTA);
__m128d V1 = _mm_load_pd(x.Mem);
__m128d V3 = _mm_load_pd(x.Mem+2);
__m128d V0 = _mm_unpacklo_pd( V1, V1 );
__m128d V2 = _mm_unpacklo_pd( V3, V3 );
V1 = _mm_unpackhi_pd( V1, V1 );
V3 = _mm_unpackhi_pd( V3, V3 );
// load the matrix components into SSE registers:
__m128d ArrLo0 = _mm_load_pd( Arr+0 );
__m128d ArrHi0 = _mm_load_pd( Arr+2 );
__m128d ArrLo1 = _mm_load_pd( Arr+4 );
__m128d ArrHi1 = _mm_load_pd( Arr+6 );
__m128d ArrLo2 = _mm_load_pd( Arr+8 );
__m128d ArrHi2 = _mm_load_pd( Arr+10 );
__m128d ArrLo3 = _mm_load_pd( Arr+12 );
__m128d ArrHi3 = _mm_load_pd( Arr+14 );
// correct the signs of the matrix components:
ArrLo0 = _mm_xor_pd( ArrLo0, xS01 );
ArrHi0 = _mm_xor_pd( ArrHi0, xS11 );
ArrLo1 = _mm_xor_pd( ArrLo1, xS10 );
ArrLo2 = _mm_xor_pd( ArrLo2, xS10 );
ArrLo3 = _mm_xor_pd( ArrLo3, xS10 );
__m128d resLo = _mm_mul_pd( V0, ArrLo0 );
__m128d resHi = _mm_mul_pd( V0, ArrHi0 );
resLo = _mm_add_pd( resLo, _mm_mul_pd( V1, ArrLo1 ));
resHi = _mm_add_pd( resHi, _mm_mul_pd( V1, ArrHi1 ));
resLo = _mm_add_pd( resLo, _mm_mul_pd( V2, ArrLo2 ));
resHi = _mm_add_pd( resHi, _mm_mul_pd( V2, ArrHi2 ));
resLo = _mm_add_pd( resLo, _mm_mul_pd( V3, ArrLo3 ));
resHi = _mm_add_pd( resHi, _mm_mul_pd( V3, ArrHi3 ));
return vector4D( resLo, resHi );
#elif defined (VECTOR_IMPL_AVX)
// __m256d a1 = _mm256_set_pd(1.0,2.0,3.0,4.0);
// __m256d a2 = _mm256_set_pd(10.0,20.0,30.0,40.0);
// cout << (vector4D)a1 << endl;
// cout << (vector4D)a2 << endl;
// __m256d b1 = _mm256_addsub_pd(a1,a2);
// cout << (vector4D)b1 << endl;
// load the vector into registers:
// (V0 consist of 4 copies of component 0, V1 has 4 copies of
// component 1 and so on)
__m256d V0 = _mm256_broadcast_sd(x.Mem);
__m256d V1 = _mm256_broadcast_sd(x.Mem+1);
__m256d V2 = _mm256_broadcast_sd(x.Mem+2);
__m256d V3 = _mm256_broadcast_sd(x.Mem+3);
// load the matrix components into registers:
__m256d Arr0 = _mm256_load_pd( Arr+0 );
__m256d Arr1 = _mm256_load_pd( Arr+4 );
__m256d Arr2 = _mm256_load_pd( Arr+8 );
__m256d Arr3 = _mm256_load_pd( Arr+12 );
// correct the signs of the matrix components:
// in Arr0, we have to flip signs .123
// in Arri, we have to flip signs 0...
static const __m256d S01 = _mm256_set_pd(-0.,-0.,-0., 0.);
static const __m256d S10 = _mm256_set_pd( 0., 0., 0.,-0.);
Arr0 = _mm256_xor_pd( Arr0, S01 );
Arr1 = _mm256_xor_pd( Arr1, S10 );
Arr2 = _mm256_xor_pd( Arr2, S10 );
Arr3 = _mm256_xor_pd( Arr3, S10 );
// cout << "changed Arr0:" << endl;
// cout << (vector4D)Arr0 << endl;
// cout << (vector4D)Arr1 << endl;
// cout << (vector4D)Arr2 << endl;
// cout << (vector4D)Arr3 << endl;
// do the actual multiplication:
__m256d res = _mm256_mul_pd( V0, Arr0 );
res = _mm256_add_pd( res, _mm256_mul_pd( V1, Arr1 ));
res = _mm256_add_pd( res, _mm256_mul_pd( V2, Arr2 ));
res = _mm256_add_pd( res, _mm256_mul_pd( V3, Arr3 ));
return vector4D( res );
#else
return boostScalar( x );
#endif
}
vector4D lorentz::boostScalar( const vector4D & x ) const
{
return vector4D( Arr[0+4*0]*x[0]-Arr[1+4*0]*x[1]-Arr[2+4*0]*x[2]-Arr[3+4*0]*x[3],
-Arr[0+4*3]*x[0]+Arr[1+4*3]*x[1]+Arr[2+4*3]*x[2]+Arr[3+4*3]*x[3],
-Arr[0+4*2]*x[0]+Arr[1+4*2]*x[1]+Arr[2+4*2]*x[2]+Arr[3+4*2]*x[3],
-Arr[0+4*1]*x[0]+Arr[1+4*1]*x[1]+Arr[2+4*1]*x[2]+Arr[3+4*1]*x[3]);
}
vector4D lorentz::boostInv( const vector4D & x ) const
{
#if defined (VECTOR_IMPL_SSE)
__m128d V1 = _mm_load_pd(x.Mem);
__m128d V3 = _mm_load_pd(x.Mem+2);
__m128d V0 = _mm_unpacklo_pd( V1, V1 );
__m128d V2 = _mm_unpacklo_pd( V3, V3 );
V1 = _mm_unpackhi_pd( V1, V1 );
V3 = _mm_unpackhi_pd( V3, V3 );
// load the matrix components into SSE registers:
__m128d ArrLo0 = _mm_load_pd( Arr+0 );
__m128d ArrHi0 = _mm_load_pd( Arr+2 );
__m128d ArrLo1 = _mm_load_pd( Arr+4 );
__m128d ArrHi1 = _mm_load_pd( Arr+6 );
__m128d ArrLo2 = _mm_load_pd( Arr+8 );
__m128d ArrHi2 = _mm_load_pd( Arr+10 );
__m128d ArrLo3 = _mm_load_pd( Arr+12 );
__m128d ArrHi3 = _mm_load_pd( Arr+14 );
__m128d resLo = _mm_mul_pd( V0, ArrLo0 );
__m128d resHi = _mm_mul_pd( V0, ArrHi0 );
resLo = _mm_add_pd( resLo, _mm_mul_pd( V1, ArrLo1 ));
resHi = _mm_add_pd( resHi, _mm_mul_pd( V1, ArrHi1 ));
resLo = _mm_add_pd( resLo, _mm_mul_pd( V2, ArrLo2 ));
resHi = _mm_add_pd( resHi, _mm_mul_pd( V2, ArrHi2 ));
resLo = _mm_add_pd( resLo, _mm_mul_pd( V3, ArrLo3 ));
resHi = _mm_add_pd( resHi, _mm_mul_pd( V3, ArrHi3 ));
return vector4D( resLo, resHi );
#elif defined (VECTOR_IMPL_AVX)
// load the vector into registers:
// (V0 consist of 4 copies of component 0, V1 has 4 copies of
// component 1 and so on)
__m256d V0 = _mm256_broadcast_sd(x.Mem);
__m256d V1 = _mm256_broadcast_sd(x.Mem+1);
__m256d V2 = _mm256_broadcast_sd(x.Mem+2);
__m256d V3 = _mm256_broadcast_sd(x.Mem+3);
// load the matrix components into registers:
__m256d Arr0 = _mm256_load_pd( Arr+0 );
__m256d Arr1 = _mm256_load_pd( Arr+4 );
__m256d Arr2 = _mm256_load_pd( Arr+8 );
__m256d Arr3 = _mm256_load_pd( Arr+12 );
// do the actual multiplication:
__m256d res = _mm256_mul_pd( V0, Arr0 );
res = _mm256_add_pd( res, _mm256_mul_pd( V1, Arr1 ));
res = _mm256_add_pd( res, _mm256_mul_pd( V2, Arr2 ));
res = _mm256_add_pd( res, _mm256_mul_pd( V3, Arr3 ));
return vector4D( res );
#else
return boostInvScalar( x );
#endif
}
vector4D lorentz::boostInvScalar( const vector4D & x ) const
{
return vector4D( Arr[0+4*0]*x[0]+Arr[1+4*0]*x[1]+Arr[2+4*0]*x[2]+Arr[3+4*0]*x[3],
Arr[0+4*3]*x[0]+Arr[1+4*3]*x[1]+Arr[2+4*3]*x[2]+Arr[3+4*3]*x[3],
Arr[0+4*2]*x[0]+Arr[1+4*2]*x[1]+Arr[2+4*2]*x[2]+Arr[3+4*2]*x[3],
Arr[0+4*1]*x[0]+Arr[1+4*1]*x[1]+Arr[2+4*1]*x[2]+Arr[3+4*1]*x[3]);
}
///// BOOST TWO VECTORS /////
void lorentz::boost( const vector4D & x1, const vector4D & x2,
vector4D & x1New, vector4D & x2New ) const
{
#if defined (VECTOR_IMPL_SSE)
// please note: we have to be careful with the signs of the matrix:
// The components [0][i] and [i][0] have to be negated!
// we also use _mm_prefetch in order to load some memory into a
// cache closer to the processor.
_MM_PREFETCH(x1.Mem, _MM_HINT_NTA);
_MM_PREFETCH(x2.Mem, _MM_HINT_NTA);
SSE_ALIGNED(const unsigned long long) S = 0x8000000000000000ull ;
// cppcheck-suppress invalidPointerCast
__m128d xS10 = _mm_load_sd( (double *)&S ); // only lower part negates
__m128d xS01 = _mm_setzero_pd( ); // set it to zero
__m128d xS11 = _mm_unpacklo_pd( xS10, xS10 ); // both parts negate
xS01 = _mm_unpacklo_pd( xS01, xS10 ); // only upper part negates
_MM_PREFETCH(Arr, _MM_HINT_NTA);
__m128d V1a = _mm_load_pd(x1.Mem);
__m128d V1b = _mm_load_pd(x2.Mem);
__m128d V3a = _mm_load_pd(x1.Mem+2);
__m128d V3b = _mm_load_pd(x2.Mem+2);
__m128d V0a = _mm_unpacklo_pd( V1a, V1a );
__m128d V0b = _mm_unpacklo_pd( V1b, V1b );
__m128d V2a = _mm_unpacklo_pd( V3a, V3a );
__m128d V2b = _mm_unpacklo_pd( V3b, V3b );
V1a = _mm_unpackhi_pd( V1a, V1a );
V1b = _mm_unpackhi_pd( V1b, V1b );
V3a = _mm_unpackhi_pd( V3a, V3a );
V3b = _mm_unpackhi_pd( V3b, V3b );
// load the matrix components into SSE registers:
__m128d ArrLo0 = _mm_load_pd( Arr+0 );
__m128d ArrHi0 = _mm_load_pd( Arr+2 );
__m128d ArrLo1 = _mm_load_pd( Arr+4 );
__m128d ArrHi1 = _mm_load_pd( Arr+6 );
__m128d ArrLo2 = _mm_load_pd( Arr+8 );
__m128d ArrHi2 = _mm_load_pd( Arr+10 );
__m128d ArrLo3 = _mm_load_pd( Arr+12 );
__m128d ArrHi3 = _mm_load_pd( Arr+14 );
// already load the output memory into cache
_MM_PREFETCH(x1New.Mem, _MM_HINT_NTA);
_MM_PREFETCH(x2New.Mem, _MM_HINT_NTA);
// correct the signs of the matrix components:
ArrLo0 = _mm_xor_pd( ArrLo0, xS01 );
ArrHi0 = _mm_xor_pd( ArrHi0, xS11 );
ArrLo1 = _mm_xor_pd( ArrLo1, xS10 );
ArrLo2 = _mm_xor_pd( ArrLo2, xS10 );
ArrLo3 = _mm_xor_pd( ArrLo3, xS10 );
__m128d resLo1 = _mm_mul_pd( V0a, ArrLo0 );
__m128d resHi1 = _mm_mul_pd( V0a, ArrHi0 );
__m128d resLo2 = _mm_mul_pd( V0b, ArrLo0 );
__m128d resHi2 = _mm_mul_pd( V0b, ArrHi0 );
resLo1 = _mm_add_pd( resLo1, _mm_mul_pd( V1a, ArrLo1 ));
resHi1 = _mm_add_pd( resHi1, _mm_mul_pd( V1a, ArrHi1 ));
resLo2 = _mm_add_pd( resLo2, _mm_mul_pd( V1b, ArrLo1 ));
resHi2 = _mm_add_pd( resHi2, _mm_mul_pd( V1b, ArrHi1 ));
resLo1 = _mm_add_pd( resLo1, _mm_mul_pd( V2a, ArrLo2 ));
resHi1 = _mm_add_pd( resHi1, _mm_mul_pd( V2a, ArrHi2 ));
resLo2 = _mm_add_pd( resLo2, _mm_mul_pd( V2b, ArrLo2 ));
resHi2 = _mm_add_pd( resHi2, _mm_mul_pd( V2b, ArrHi2 ));
resLo1 = _mm_add_pd( resLo1, _mm_mul_pd( V3a, ArrLo3 ));
resHi1 = _mm_add_pd( resHi1, _mm_mul_pd( V3a, ArrHi3 ));
resLo2 = _mm_add_pd( resLo2, _mm_mul_pd( V3b, ArrLo3 ));
resHi2 = _mm_add_pd( resHi2, _mm_mul_pd( V3b, ArrHi3 ));
x1New = vector4D( resLo1, resHi1 );
x2New = vector4D( resLo2, resHi2 );
#elif defined (VECTOR_IMPL_AVX)
_MM_PREFETCH(Arr, _MM_HINT_NTA);
_MM_PREFETCH(x1.Mem, _MM_HINT_NTA);
_MM_PREFETCH(x2.Mem, _MM_HINT_NTA);
// load the vector into registers:
// (V0 consist of 4 copies of component 0, V1 has 4 copies of
// component 1 and so on)
__m256d V0a = _mm256_broadcast_sd(x1.Mem);
__m256d V1a = _mm256_broadcast_sd(x1.Mem+1);
__m256d V2a = _mm256_broadcast_sd(x1.Mem+2);
__m256d V3a = _mm256_broadcast_sd(x1.Mem+3);
__m256d V0b = _mm256_broadcast_sd(x2.Mem);
__m256d V1b = _mm256_broadcast_sd(x2.Mem+1);
__m256d V2b = _mm256_broadcast_sd(x2.Mem+2);
__m256d V3b = _mm256_broadcast_sd(x2.Mem+3);
// load the matrix components into registers:
__m256d Arr0 = _mm256_load_pd( Arr+0 );
__m256d Arr1 = _mm256_load_pd( Arr+4 );
__m256d Arr2 = _mm256_load_pd( Arr+8 );
__m256d Arr3 = _mm256_load_pd( Arr+12 );
// already load the output memory into cache
_MM_PREFETCH(x1New.Mem, _MM_HINT_NTA);
_MM_PREFETCH(x2New.Mem, _MM_HINT_NTA);
// correct the signs of the matrix components:
// in Arr0, we have to flip signs .123
// in Arri, we have to flip signs 0...
static const __m256d S01 = _mm256_set_pd(-0.,-0.,-0., 0.);
static const __m256d S10 = _mm256_set_pd( 0., 0., 0.,-0.);
Arr0 = _mm256_xor_pd( Arr0, S01 );
Arr1 = _mm256_xor_pd( Arr1, S10 );
Arr2 = _mm256_xor_pd( Arr2, S10 );
Arr3 = _mm256_xor_pd( Arr3, S10 );
// do the actual multiplication:
__m256d res1 = _mm256_mul_pd( V0a, Arr0 );
res1 = _mm256_add_pd( res1, _mm256_mul_pd( V1a, Arr1 ));
res1 = _mm256_add_pd( res1, _mm256_mul_pd( V2a, Arr2 ));
res1 = _mm256_add_pd( res1, _mm256_mul_pd( V3a, Arr3 ));
__m256d res2 = _mm256_mul_pd( V0b, Arr0 );
res2 = _mm256_add_pd( res2, _mm256_mul_pd( V1b, Arr1 ));
res2 = _mm256_add_pd( res2, _mm256_mul_pd( V2b, Arr2 ));
res2 = _mm256_add_pd( res2, _mm256_mul_pd( V3b, Arr3 ));
x1New = vector4D( res1 );
x2New = vector4D( res2 );
#else
boostScalar( x1, x2, x1New, x2New );
#endif
}
void lorentz::boostScalar( const vector4D & x1, const vector4D & x2,
vector4D & x1New, vector4D & x2New ) const
{
x1New = vector4D( Arr[0+4*0]*x1[0]-Arr[1+4*0]*x1[1]-Arr[2+4*0]*x1[2]-Arr[3+4*0]*x1[3],
-Arr[0+4*3]*x1[0]+Arr[1+4*3]*x1[1]+Arr[2+4*3]*x1[2]+Arr[3+4*3]*x1[3],
-Arr[0+4*2]*x1[0]+Arr[1+4*2]*x1[1]+Arr[2+4*2]*x1[2]+Arr[3+4*2]*x1[3],
-Arr[0+4*1]*x1[0]+Arr[1+4*1]*x1[1]+Arr[2+4*1]*x1[2]+Arr[3+4*1]*x1[3]);
x2New = vector4D( Arr[0+4*0]*x2[0]-Arr[1+4*0]*x2[1]-Arr[2+4*0]*x2[2]-Arr[3+4*0]*x2[3],
-Arr[0+4*3]*x2[0]+Arr[1+4*3]*x2[1]+Arr[2+4*3]*x2[2]+Arr[3+4*3]*x2[3],
-Arr[0+4*2]*x2[0]+Arr[1+4*2]*x2[1]+Arr[2+4*2]*x2[2]+Arr[3+4*2]*x2[3],
-Arr[0+4*1]*x2[0]+Arr[1+4*1]*x2[1]+Arr[2+4*1]*x2[2]+Arr[3+4*1]*x2[3]);
}
double lorentz::getSpatialDistance(const vector4D& x1, const vector4D& x2)
{
double xsq = pow(x1[1]-x2[1],2.0);
double ysq = pow(x1[2]-x2[2],2.0);
double zsq = pow(x1[3]-x2[3],2.0);
return sqrt( xsq + ysq + zsq );
}
double lorentz::getDCAsquared(const vector4D& x1, const vector4D& x2, const vector4D& p1, const vector4D& p2)
{
double dvx,dvy,dvz,dx,dy,dz;
dvx = p1[1]/p1[0] - p2[1]/p2[0];
dvy = p1[2]/p1[0] - p2[2]/p2[0];
dvz = p1[3]/p1[0] - p2[3]/p2[0];
double dv2 = dvx*dvx +dvy*dvy + dvz*dvz;
dx = x1[1]-x2[1];
dy = x1[2]-x2[2];
dz = x1[3]-x2[3];
double dx2 = dx*dx + dy*dy + dz*dz;
double dvdx = dx*dvx + dy*dvy + dz*dvz;
double t=-(dvdx)/dv2;
return (dx2 - dvdx*dvdx/dv2);
}
void lorentz::boostInv( const vector4D & x1, const vector4D & x2,
vector4D & x1New, vector4D & x2New ) const
{
#if defined (VECTOR_IMPL_SSE)
__m128d V1a = _mm_load_pd(x1.Mem);
__m128d V1b = _mm_load_pd(x2.Mem);
__m128d V3a = _mm_load_pd(x1.Mem+2);
__m128d V3b = _mm_load_pd(x2.Mem+2);
__m128d V0a = _mm_unpacklo_pd( V1a, V1a );
__m128d V0b = _mm_unpacklo_pd( V1b, V1b );
__m128d V2a = _mm_unpacklo_pd( V3a, V3a );
__m128d V2b = _mm_unpacklo_pd( V3b, V3b );
V1a = _mm_unpackhi_pd( V1a, V1a );
V1b = _mm_unpackhi_pd( V1b, V1b );
V3a = _mm_unpackhi_pd( V3a, V3a );
V3b = _mm_unpackhi_pd( V3b, V3b );
// load the matrix components into SSE registers:
__m128d ArrLo0 = _mm_load_pd( Arr+0 );
__m128d ArrHi0 = _mm_load_pd( Arr+2 );
__m128d ArrLo1 = _mm_load_pd( Arr+4 );
__m128d ArrHi1 = _mm_load_pd( Arr+6 );
__m128d ArrLo2 = _mm_load_pd( Arr+8 );
__m128d ArrHi2 = _mm_load_pd( Arr+10 );
__m128d ArrLo3 = _mm_load_pd( Arr+12 );
__m128d ArrHi3 = _mm_load_pd( Arr+14 );
// already load the output memory into cache
_MM_PREFETCH(x1New.Mem, _MM_HINT_NTA);
_MM_PREFETCH(x2New.Mem, _MM_HINT_NTA);
__m128d resLo1 = _mm_mul_pd( V0a, ArrLo0 );
__m128d resHi1 = _mm_mul_pd( V0a, ArrHi0 );
__m128d resLo2 = _mm_mul_pd( V0b, ArrLo0 );
__m128d resHi2 = _mm_mul_pd( V0b, ArrHi0 );
resLo1 = _mm_add_pd( resLo1, _mm_mul_pd( V1a, ArrLo1 ));
resHi1 = _mm_add_pd( resHi1, _mm_mul_pd( V1a, ArrHi1 ));
resLo2 = _mm_add_pd( resLo2, _mm_mul_pd( V1b, ArrLo1 ));
resHi2 = _mm_add_pd( resHi2, _mm_mul_pd( V1b, ArrHi1 ));
resLo1 = _mm_add_pd( resLo1, _mm_mul_pd( V2a, ArrLo2 ));
resHi1 = _mm_add_pd( resHi1, _mm_mul_pd( V2a, ArrHi2 ));
resLo2 = _mm_add_pd( resLo2, _mm_mul_pd( V2b, ArrLo2 ));
resHi2 = _mm_add_pd( resHi2, _mm_mul_pd( V2b, ArrHi2 ));
resLo1 = _mm_add_pd( resLo1, _mm_mul_pd( V3a, ArrLo3 ));
resHi1 = _mm_add_pd( resHi1, _mm_mul_pd( V3a, ArrHi3 ));
resLo2 = _mm_add_pd( resLo2, _mm_mul_pd( V3b, ArrLo3 ));
resHi2 = _mm_add_pd( resHi2, _mm_mul_pd( V3b, ArrHi3 ));
x1New = vector4D( resLo1, resHi1 );
x2New = vector4D( resLo2, resHi2 );
#elif defined (VECTOR_IMPL_AVX)
_MM_PREFETCH(Arr, _MM_HINT_NTA);
_MM_PREFETCH(x1.Mem, _MM_HINT_NTA);
_MM_PREFETCH(x2.Mem, _MM_HINT_NTA);
// load the vector into registers:
// (V0 consist of 4 copies of component 0, V1 has 4 copies of
// component 1 and so on)
__m256d V0a = _mm256_broadcast_sd(x1.Mem);
__m256d V1a = _mm256_broadcast_sd(x1.Mem+1);
__m256d V2a = _mm256_broadcast_sd(x1.Mem+2);
__m256d V3a = _mm256_broadcast_sd(x1.Mem+3);
__m256d V0b = _mm256_broadcast_sd(x2.Mem);
__m256d V1b = _mm256_broadcast_sd(x2.Mem+1);
__m256d V2b = _mm256_broadcast_sd(x2.Mem+2);
__m256d V3b = _mm256_broadcast_sd(x2.Mem+3);
// load the matrix components into registers:
__m256d Arr0 = _mm256_load_pd( Arr+0 );
__m256d Arr1 = _mm256_load_pd( Arr+4 );
__m256d Arr2 = _mm256_load_pd( Arr+8 );
__m256d Arr3 = _mm256_load_pd( Arr+12 );
// already load the output memory into cache
_MM_PREFETCH(x1New.Mem, _MM_HINT_NTA);
_MM_PREFETCH(x2New.Mem, _MM_HINT_NTA);
// do the actual multiplication:
__m256d res1 = _mm256_mul_pd( V0a, Arr0 );
res1 = _mm256_add_pd( res1, _mm256_mul_pd( V1a, Arr1 ));
res1 = _mm256_add_pd( res1, _mm256_mul_pd( V2a, Arr2 ));
res1 = _mm256_add_pd( res1, _mm256_mul_pd( V3a, Arr3 ));
__m256d res2 = _mm256_mul_pd( V0b, Arr0 );
res2 = _mm256_add_pd( res2, _mm256_mul_pd( V1b, Arr1 ));
res2 = _mm256_add_pd( res2, _mm256_mul_pd( V2b, Arr2 ));
res2 = _mm256_add_pd( res2, _mm256_mul_pd( V3b, Arr3 ));
x1New = vector4D( res1 );
x2New = vector4D( res2 );
#else
boostInvScalar( x1, x2, x1New, x2New );
#endif
}
void lorentz::boostInvScalar( const vector4D & x1, const vector4D & x2,
vector4D & x1New, vector4D & x2New ) const
{
x1New = vector4D(Arr[0+4*0]*x1[0]+Arr[1+4*0]*x1[1]+Arr[2+4*0]*x1[2]+Arr[3+4*0]*x1[3],
Arr[0+4*3]*x1[0]+Arr[1+4*3]*x1[1]+Arr[2+4*3]*x1[2]+Arr[3+4*3]*x1[3],
Arr[0+4*2]*x1[0]+Arr[1+4*2]*x1[1]+Arr[2+4*2]*x1[2]+Arr[3+4*2]*x1[3],
Arr[0+4*1]*x1[0]+Arr[1+4*1]*x1[1]+Arr[2+4*1]*x1[2]+Arr[3+4*1]*x1[3]);
x2New = vector4D(Arr[0+4*0]*x2[0]+Arr[1+4*0]*x2[1]+Arr[2+4*0]*x2[2]+Arr[3+4*0]*x2[3],
Arr[0+4*3]*x2[0]+Arr[1+4*3]*x2[1]+Arr[2+4*3]*x2[2]+Arr[3+4*3]*x2[3],
Arr[0+4*2]*x2[0]+Arr[1+4*2]*x2[1]+Arr[2+4*2]*x2[2]+Arr[3+4*2]*x2[3],
Arr[0+4*1]*x2[0]+Arr[1+4*1]*x2[1]+Arr[2+4*1]*x2[2]+Arr[3+4*1]*x2[3]);
}
///// BOOST THREE VECTORS /////
void lorentz::boost( const vector4D & x1, const vector4D & x2, const vector4D & x3,
vector4D & x1New, vector4D & x2New, vector4D & x3New ) const
{
#if defined (VECTOR_IMPL_SSE)
// please note: we have to be careful with the signs of the matrix:
// The components [0][i] and [i][0] have to be negated!
// we also use _mm_prefetch in order to load some memory into a
// cache closer to the processor.
_MM_PREFETCH(x1.Mem, _MM_HINT_NTA);
_MM_PREFETCH(x2.Mem, _MM_HINT_NTA);
_MM_PREFETCH(x3.Mem, _MM_HINT_NTA);
SSE_ALIGNED(const unsigned long long) S = 0x8000000000000000ull ;
// cppcheck-suppress invalidPointerCast
__m128d xS10 = _mm_load_sd( (double *)&S ); // only lower part negates
__m128d xS01 = _mm_setzero_pd( ); // set it to zero
__m128d xS11 = _mm_unpacklo_pd( xS10, xS10 ); // both parts negate
xS01 = _mm_unpacklo_pd( xS01, xS10 ); // only upper part negates
_MM_PREFETCH(Arr, _MM_HINT_NTA);
__m128d V1a = _mm_load_pd(x1.Mem);
__m128d V1b = _mm_load_pd(x2.Mem);
__m128d V1c = _mm_load_pd(x3.Mem);
__m128d V3a = _mm_load_pd(x1.Mem+2);
__m128d V3b = _mm_load_pd(x2.Mem+2);
__m128d V3c = _mm_load_pd(x3.Mem+2);
__m128d V0a = _mm_unpacklo_pd( V1a, V1a );
__m128d V0b = _mm_unpacklo_pd( V1b, V1b );
__m128d V0c = _mm_unpacklo_pd( V1c, V1c );
__m128d V2a = _mm_unpacklo_pd( V3a, V3a );
__m128d V2b = _mm_unpacklo_pd( V3b, V3b );
__m128d V2c = _mm_unpacklo_pd( V3c, V3c );
V1a = _mm_unpackhi_pd( V1a, V1a );
V1b = _mm_unpackhi_pd( V1b, V1b );
V1c = _mm_unpackhi_pd( V1c, V1c );
V3a = _mm_unpackhi_pd( V3a, V3a );
V3b = _mm_unpackhi_pd( V3b, V3b );
V3c = _mm_unpackhi_pd( V3c, V3c );
// load the matrix components into SSE registers:
__m128d ArrLo0 = _mm_load_pd( Arr+0 );
__m128d ArrHi0 = _mm_load_pd( Arr+2 );
__m128d ArrLo1 = _mm_load_pd( Arr+4 );
__m128d ArrHi1 = _mm_load_pd( Arr+6 );
__m128d ArrLo2 = _mm_load_pd( Arr+8 );
__m128d ArrHi2 = _mm_load_pd( Arr+10 );
__m128d ArrLo3 = _mm_load_pd( Arr+12 );
__m128d ArrHi3 = _mm_load_pd( Arr+14 );
// already load the output memory into cache
_MM_PREFETCH(x1New.Mem, _MM_HINT_NTA);
_MM_PREFETCH(x2New.Mem, _MM_HINT_NTA);
_MM_PREFETCH(x3New.Mem, _MM_HINT_NTA);
// correct the signs of the matrix components:
ArrLo0 = _mm_xor_pd( ArrLo0, xS01 );
ArrHi0 = _mm_xor_pd( ArrHi0, xS11 );
ArrLo1 = _mm_xor_pd( ArrLo1, xS10 );
ArrLo2 = _mm_xor_pd( ArrLo2, xS10 );
ArrLo3 = _mm_xor_pd( ArrLo3, xS10 );
__m128d resLo1 = _mm_mul_pd( V0a, ArrLo0 );
__m128d resHi1 = _mm_mul_pd( V0a, ArrHi0 );
__m128d resLo2 = _mm_mul_pd( V0b, ArrLo0 );
__m128d resHi2 = _mm_mul_pd( V0b, ArrHi0 );
__m128d resLo3 = _mm_mul_pd( V0c, ArrLo0 );
__m128d resHi3 = _mm_mul_pd( V0c, ArrHi0 );
resLo1 = _mm_add_pd( resLo1, _mm_mul_pd( V1a, ArrLo1 ));
resHi1 = _mm_add_pd( resHi1, _mm_mul_pd( V1a, ArrHi1 ));
resLo2 = _mm_add_pd( resLo2, _mm_mul_pd( V1b, ArrLo1 ));
resHi2 = _mm_add_pd( resHi2, _mm_mul_pd( V1b, ArrHi1 ));
resLo3 = _mm_add_pd( resLo3, _mm_mul_pd( V1c, ArrLo1 ));
resHi3 = _mm_add_pd( resHi3, _mm_mul_pd( V1c, ArrHi1 ));
resLo1 = _mm_add_pd( resLo1, _mm_mul_pd( V2a, ArrLo2 ));
resHi1 = _mm_add_pd( resHi1, _mm_mul_pd( V2a, ArrHi2 ));
resLo2 = _mm_add_pd( resLo2, _mm_mul_pd( V2b, ArrLo2 ));
resHi2 = _mm_add_pd( resHi2, _mm_mul_pd( V2b, ArrHi2 ));
resLo3 = _mm_add_pd( resLo3, _mm_mul_pd( V2c, ArrLo2 ));
resHi3 = _mm_add_pd( resHi3, _mm_mul_pd( V2c, ArrHi2 ));
resLo1 = _mm_add_pd( resLo1, _mm_mul_pd( V3a, ArrLo3 ));
resHi1 = _mm_add_pd( resHi1, _mm_mul_pd( V3a, ArrHi3 ));
resLo2 = _mm_add_pd( resLo2, _mm_mul_pd( V3b, ArrLo3 ));
resHi2 = _mm_add_pd( resHi2, _mm_mul_pd( V3b, ArrHi3 ));
resLo3 = _mm_add_pd( resLo3, _mm_mul_pd( V3c, ArrLo3 ));
resHi3 = _mm_add_pd( resHi3, _mm_mul_pd( V3c, ArrHi3 ));
x1New = vector4D( resLo1, resHi1 );
x2New = vector4D( resLo2, resHi2 );
x3New = vector4D( resLo3, resHi3 );
#elif defined (VECTOR_IMPL_AVX)
_MM_PREFETCH(Arr, _MM_HINT_NTA);
_MM_PREFETCH(x1.Mem, _MM_HINT_NTA);
_MM_PREFETCH(x2.Mem, _MM_HINT_NTA);
_MM_PREFETCH(x3.Mem, _MM_HINT_NTA);
// load the vector into registers:
// (V0 consist of 4 copies of component 0, V1 has 4 copies of
// component 1 and so on)
__m256d V0a = _mm256_broadcast_sd(x1.Mem);
__m256d V1a = _mm256_broadcast_sd(x1.Mem+1);
__m256d V2a = _mm256_broadcast_sd(x1.Mem+2);
__m256d V3a = _mm256_broadcast_sd(x1.Mem+3);
__m256d V0b = _mm256_broadcast_sd(x2.Mem);
__m256d V1b = _mm256_broadcast_sd(x2.Mem+1);
__m256d V2b = _mm256_broadcast_sd(x2.Mem+2);
__m256d V3b = _mm256_broadcast_sd(x2.Mem+3);
__m256d V0c = _mm256_broadcast_sd(x3.Mem);
__m256d V1c = _mm256_broadcast_sd(x3.Mem+1);
__m256d V2c = _mm256_broadcast_sd(x3.Mem+2);
__m256d V3c = _mm256_broadcast_sd(x3.Mem+3);
// load the matrix components into registers:
__m256d Arr0 = _mm256_load_pd( Arr+0 );
__m256d Arr1 = _mm256_load_pd( Arr+4 );
__m256d Arr2 = _mm256_load_pd( Arr+8 );
__m256d Arr3 = _mm256_load_pd( Arr+12 );
// already load the output memory into cache
_MM_PREFETCH(x1New.Mem, _MM_HINT_NTA);
_MM_PREFETCH(x2New.Mem, _MM_HINT_NTA);
_MM_PREFETCH(x3New.Mem, _MM_HINT_NTA);
// correct the signs of the matrix components:
// in Arr0, we have to flip signs .123
// in Arri, we have to flip signs 0...
static const __m256d S01 = _mm256_set_pd(-0.,-0.,-0., 0.);
static const __m256d S10 = _mm256_set_pd( 0., 0., 0.,-0.);
Arr0 = _mm256_xor_pd( Arr0, S01 );
Arr1 = _mm256_xor_pd( Arr1, S10 );
Arr2 = _mm256_xor_pd( Arr2, S10 );
Arr3 = _mm256_xor_pd( Arr3, S10 );
// do the actual multiplication:
__m256d res1 = _mm256_mul_pd( V0a, Arr0 );
res1 = _mm256_add_pd( res1, _mm256_mul_pd( V1a, Arr1 ));
res1 = _mm256_add_pd( res1, _mm256_mul_pd( V2a, Arr2 ));
res1 = _mm256_add_pd( res1, _mm256_mul_pd( V3a, Arr3 ));
__m256d res2 = _mm256_mul_pd( V0b, Arr0 );
res2 = _mm256_add_pd( res2, _mm256_mul_pd( V1b, Arr1 ));
res2 = _mm256_add_pd( res2, _mm256_mul_pd( V2b, Arr2 ));
res2 = _mm256_add_pd( res2, _mm256_mul_pd( V3b, Arr3 ));
__m256d res3 = _mm256_mul_pd( V0c, Arr0 );
res3 = _mm256_add_pd( res3, _mm256_mul_pd( V1c, Arr1 ));
res3 = _mm256_add_pd( res3, _mm256_mul_pd( V2c, Arr2 ));
res3 = _mm256_add_pd( res3, _mm256_mul_pd( V3c, Arr3 ));
x1New = vector4D( res1 );
x2New = vector4D( res2 );
x3New = vector4D( res3 );
#else
boostScalar( x1, x2, x3, x1New, x2New, x3New );
#endif
}
void lorentz::boostScalar( const vector4D & x1, const vector4D & x2, const vector4D & x3,
vector4D & x1New, vector4D & x2New, vector4D & x3New ) const
{
x1New = vector4D( Arr[0+4*0]*x1[0]-Arr[1+4*0]*x1[1]-Arr[2+4*0]*x1[2]-Arr[3+4*0]*x1[3],
-Arr[0+4*3]*x1[0]+Arr[1+4*3]*x1[1]+Arr[2+4*3]*x1[2]+Arr[3+4*3]*x1[3],
-Arr[0+4*2]*x1[0]+Arr[1+4*2]*x1[1]+Arr[2+4*2]*x1[2]+Arr[3+4*2]*x1[3],
-Arr[0+4*1]*x1[0]+Arr[1+4*1]*x1[1]+Arr[2+4*1]*x1[2]+Arr[3+4*1]*x1[3]);
x2New = vector4D( Arr[0+4*0]*x2[0]-Arr[1+4*0]*x2[1]-Arr[2+4*0]*x2[2]-Arr[3+4*0]*x2[3],
-Arr[0+4*3]*x2[0]+Arr[1+4*3]*x2[1]+Arr[2+4*3]*x2[2]+Arr[3+4*3]*x2[3],
-Arr[0+4*2]*x2[0]+Arr[1+4*2]*x2[1]+Arr[2+4*2]*x2[2]+Arr[3+4*2]*x2[3],
-Arr[0+4*1]*x2[0]+Arr[1+4*1]*x2[1]+Arr[2+4*1]*x2[2]+Arr[3+4*1]*x2[3]);
x3New = vector4D( Arr[0+4*0]*x3[0]-Arr[1+4*0]*x3[1]-Arr[2+4*0]*x3[2]-Arr[3+4*0]*x3[3],
-Arr[0+4*3]*x3[0]+Arr[1+4*3]*x3[1]+Arr[2+4*3]*x3[2]+Arr[3+4*3]*x3[3],
-Arr[0+4*2]*x3[0]+Arr[1+4*2]*x3[1]+Arr[2+4*2]*x3[2]+Arr[3+4*2]*x3[3],
-Arr[0+4*1]*x3[0]+Arr[1+4*1]*x3[1]+Arr[2+4*1]*x3[2]+Arr[3+4*1]*x3[3]);
}
void lorentz::boostInv( const vector4D & x1, const vector4D & x2, const vector4D & x3,
vector4D & x1New, vector4D & x2New, vector4D & x3New ) const
{
#if defined (VECTOR_IMPL_SSE)
// we also use _mm_prefetch in order to load some memory into a
// cache closer to the processor.
_MM_PREFETCH(x1.Mem, _MM_HINT_NTA);
_MM_PREFETCH(x2.Mem, _MM_HINT_NTA);
_MM_PREFETCH(x3.Mem, _MM_HINT_NTA);
_MM_PREFETCH(Arr, _MM_HINT_NTA);
__m128d V1a = _mm_load_pd(x1.Mem);
__m128d V1b = _mm_load_pd(x2.Mem);
__m128d V1c = _mm_load_pd(x3.Mem);
__m128d V3a = _mm_load_pd(x1.Mem+2);
__m128d V3b = _mm_load_pd(x2.Mem+2);
__m128d V3c = _mm_load_pd(x3.Mem+2);
__m128d V0a = _mm_unpacklo_pd( V1a, V1a );
__m128d V0b = _mm_unpacklo_pd( V1b, V1b );
__m128d V0c = _mm_unpacklo_pd( V1c, V1c );
__m128d V2a = _mm_unpacklo_pd( V3a, V3a );
__m128d V2b = _mm_unpacklo_pd( V3b, V3b );
__m128d V2c = _mm_unpacklo_pd( V3c, V3c );
V1a = _mm_unpackhi_pd( V1a, V1a );
V1b = _mm_unpackhi_pd( V1b, V1b );
V1c = _mm_unpackhi_pd( V1c, V1c );
V3a = _mm_unpackhi_pd( V3a, V3a );
V3b = _mm_unpackhi_pd( V3b, V3b );
V3c = _mm_unpackhi_pd( V3c, V3c );
// load the matrix components into SSE registers:
__m128d ArrLo0 = _mm_load_pd( Arr+0 );
__m128d ArrHi0 = _mm_load_pd( Arr+2 );
__m128d ArrLo1 = _mm_load_pd( Arr+4 );
__m128d ArrHi1 = _mm_load_pd( Arr+6 );
__m128d ArrLo2 = _mm_load_pd( Arr+8 );
__m128d ArrHi2 = _mm_load_pd( Arr+10 );
__m128d ArrLo3 = _mm_load_pd( Arr+12 );
__m128d ArrHi3 = _mm_load_pd( Arr+14 );
// already load the output memory into cache
_MM_PREFETCH(x1New.Mem, _MM_HINT_NTA);
_MM_PREFETCH(x2New.Mem, _MM_HINT_NTA);
_MM_PREFETCH(x3New.Mem, _MM_HINT_NTA);
__m128d resLo1 = _mm_mul_pd( V0a, ArrLo0 );
__m128d resHi1 = _mm_mul_pd( V0a, ArrHi0 );
__m128d resLo2 = _mm_mul_pd( V0b, ArrLo0 );
__m128d resHi2 = _mm_mul_pd( V0b, ArrHi0 );
__m128d resLo3 = _mm_mul_pd( V0c, ArrLo0 );
__m128d resHi3 = _mm_mul_pd( V0c, ArrHi0 );
resLo1 = _mm_add_pd( resLo1, _mm_mul_pd( V1a, ArrLo1 ));
resHi1 = _mm_add_pd( resHi1, _mm_mul_pd( V1a, ArrHi1 ));
resLo2 = _mm_add_pd( resLo2, _mm_mul_pd( V1b, ArrLo1 ));
resHi2 = _mm_add_pd( resHi2, _mm_mul_pd( V1b, ArrHi1 ));
resLo3 = _mm_add_pd( resLo3, _mm_mul_pd( V1c, ArrLo1 ));
resHi3 = _mm_add_pd( resHi3, _mm_mul_pd( V1c, ArrHi1 ));
resLo1 = _mm_add_pd( resLo1, _mm_mul_pd( V2a, ArrLo2 ));
resHi1 = _mm_add_pd( resHi1, _mm_mul_pd( V2a, ArrHi2 ));
resLo2 = _mm_add_pd( resLo2, _mm_mul_pd( V2b, ArrLo2 ));
resHi2 = _mm_add_pd( resHi2, _mm_mul_pd( V2b, ArrHi2 ));
resLo3 = _mm_add_pd( resLo3, _mm_mul_pd( V2c, ArrLo2 ));
resHi3 = _mm_add_pd( resHi3, _mm_mul_pd( V2c, ArrHi2 ));
resLo1 = _mm_add_pd( resLo1, _mm_mul_pd( V3a, ArrLo3 ));
resHi1 = _mm_add_pd( resHi1, _mm_mul_pd( V3a, ArrHi3 ));
resLo2 = _mm_add_pd( resLo2, _mm_mul_pd( V3b, ArrLo3 ));
resHi2 = _mm_add_pd( resHi2, _mm_mul_pd( V3b, ArrHi3 ));
resLo3 = _mm_add_pd( resLo3, _mm_mul_pd( V3c, ArrLo3 ));
resHi3 = _mm_add_pd( resHi3, _mm_mul_pd( V3c, ArrHi3 ));
x1New = vector4D( resLo1, resHi1 );
x2New = vector4D( resLo2, resHi2 );
x3New = vector4D( resLo3, resHi3 );
#elif defined (VECTOR_IMPL_AVX)
_MM_PREFETCH(Arr, _MM_HINT_NTA);
_MM_PREFETCH(x1.Mem, _MM_HINT_NTA);
_MM_PREFETCH(x2.Mem, _MM_HINT_NTA);
_MM_PREFETCH(x3.Mem, _MM_HINT_NTA);
// load the vector into registers:
// (V0 consist of 4 copies of component 0, V1 has 4 copies of
// component 1 and so on)
__m256d V0a = _mm256_broadcast_sd(x1.Mem);
__m256d V1a = _mm256_broadcast_sd(x1.Mem+1);
__m256d V2a = _mm256_broadcast_sd(x1.Mem+2);
__m256d V3a = _mm256_broadcast_sd(x1.Mem+3);
__m256d V0b = _mm256_broadcast_sd(x2.Mem);
__m256d V1b = _mm256_broadcast_sd(x2.Mem+1);
__m256d V2b = _mm256_broadcast_sd(x2.Mem+2);
__m256d V3b = _mm256_broadcast_sd(x2.Mem+3);
__m256d V0c = _mm256_broadcast_sd(x3.Mem);
__m256d V1c = _mm256_broadcast_sd(x3.Mem+1);
__m256d V2c = _mm256_broadcast_sd(x3.Mem+2);
__m256d V3c = _mm256_broadcast_sd(x3.Mem+3);
// load the matrix components into registers:
__m256d Arr0 = _mm256_load_pd( Arr+0 );
__m256d Arr1 = _mm256_load_pd( Arr+4 );
__m256d Arr2 = _mm256_load_pd( Arr+8 );
__m256d Arr3 = _mm256_load_pd( Arr+12 );
// already load the output memory into cache
_MM_PREFETCH(x1New.Mem, _MM_HINT_NTA);
_MM_PREFETCH(x2New.Mem, _MM_HINT_NTA);
_MM_PREFETCH(x3New.Mem, _MM_HINT_NTA);
// do the actual multiplication:
__m256d res1 = _mm256_mul_pd( V0a, Arr0 );
res1 = _mm256_add_pd( res1, _mm256_mul_pd( V1a, Arr1 ));
res1 = _mm256_add_pd( res1, _mm256_mul_pd( V2a, Arr2 ));
res1 = _mm256_add_pd( res1, _mm256_mul_pd( V3a, Arr3 ));
__m256d res2 = _mm256_mul_pd( V0b, Arr0 );
res2 = _mm256_add_pd( res2, _mm256_mul_pd( V1b, Arr1 ));
res2 = _mm256_add_pd( res2, _mm256_mul_pd( V2b, Arr2 ));
res2 = _mm256_add_pd( res2, _mm256_mul_pd( V3b, Arr3 ));
__m256d res3 = _mm256_mul_pd( V0c, Arr0 );
res3 = _mm256_add_pd( res3, _mm256_mul_pd( V1c, Arr1 ));
res3 = _mm256_add_pd( res3, _mm256_mul_pd( V2c, Arr2 ));
res3 = _mm256_add_pd( res3, _mm256_mul_pd( V3c, Arr3 ));
x1New = vector4D( res1 );
x2New = vector4D( res2 );
x3New = vector4D( res3 );
#else
boostInvScalar( x1, x2, x3, x1New, x2New, x3New );
#endif
}
void lorentz::boostInvScalar( const vector4D & x1, const vector4D & x2, const vector4D & x3,
vector4D & x1New, vector4D & x2New, vector4D & x3New ) const
{
x1New = vector4D(Arr[0+4*0]*x1[0]+Arr[1+4*0]*x1[1]+Arr[2+4*0]*x1[2]+Arr[3+4*0]*x1[3],
Arr[0+4*3]*x1[0]+Arr[1+4*3]*x1[1]+Arr[2+4*3]*x1[2]+Arr[3+4*3]*x1[3],
Arr[0+4*2]*x1[0]+Arr[1+4*2]*x1[1]+Arr[2+4*2]*x1[2]+Arr[3+4*2]*x1[3],
Arr[0+4*1]*x1[0]+Arr[1+4*1]*x1[1]+Arr[2+4*1]*x1[2]+Arr[3+4*1]*x1[3]);
x2New = vector4D(Arr[0+4*0]*x2[0]+Arr[1+4*0]*x2[1]+Arr[2+4*0]*x2[2]+Arr[3+4*0]*x2[3],
Arr[0+4*3]*x2[0]+Arr[1+4*3]*x2[1]+Arr[2+4*3]*x2[2]+Arr[3+4*3]*x2[3],
Arr[0+4*2]*x2[0]+Arr[1+4*2]*x2[1]+Arr[2+4*2]*x2[2]+Arr[3+4*2]*x2[3],
Arr[0+4*1]*x2[0]+Arr[1+4*1]*x2[1]+Arr[2+4*1]*x2[2]+Arr[3+4*1]*x2[3]);
x3New = vector4D(Arr[0+4*0]*x3[0]+Arr[1+4*0]*x3[1]+Arr[2+4*0]*x3[2]+Arr[3+4*0]*x3[3],
Arr[0+4*3]*x3[0]+Arr[1+4*3]*x3[1]+Arr[2+4*3]*x3[2]+Arr[3+4*3]*x3[3],
Arr[0+4*2]*x3[0]+Arr[1+4*2]*x3[1]+Arr[2+4*2]*x3[2]+Arr[3+4*2]*x3[3],
Arr[0+4*1]*x3[0]+Arr[1+4*1]*x3[1]+Arr[2+4*1]*x3[2]+Arr[3+4*1]*x3[3]);
}
// #ifdef FOR_HISTORICAL_REASONS
// /**
// * Given a velocity vector beta, this routine boosts the vector A with this velocity.
// *
// * @param[in] beta[] Boost velocity vector.
// * @param[in] A[] 4-Vector to be boosted.
// * @param[out] LA[] The result - A boosted with beta
// */
// void lorentz(const double beta[4], const double A[4], double LA[4])
// {
// double beta2,cc,c0,c1,c2,c3,gama;
// beta2=0.0;
// for(int i=1;i<=3;i++)
// beta2 += beta[i]*beta[i];
// if(beta2 < 1.0e-10)
// {
// for(int k=0;k<=3;k++)
// LA[k]=A[k];
// return;
// }
// if(beta2 > (1.0-1.0e-10))
// {
// std::cout << beta2 <<" error in lorentz()" << std::endl;
// std::cout << A[0] << " " << A[1] << " " << A[2] << " " << A[3] << std::endl;
// std::cout << beta[1] << " " << beta[2] << " " << beta[3] << " " << std::endl;
// beta2 = (1.0-1.0e-10);
// std::cout << "Set beta2 to " << beta2 << std::endl;
// }
// else
// {
// gama=1.0/sqrt(1.0-beta2);
// //cout << beta2 << endl;
// //cout << A[0] << " " << A[1] << " " << A[2] << " " << A[3] << endl;
// }
// LA[0]=gama*(A[0]-beta[1]*A[1]-beta[2]*A[2]-beta[3]*A[3]);
// for(int j=1;j<=3;j++){
// cc=(gama-1.0)*beta[j]/beta2;
// c0=-gama*beta[j];
// c1=cc*beta[1];
// c2=cc*beta[2];
// c3=cc*beta[3];
// LA[j]=c0*A[0]+c1*A[1]+c2*A[2]+c3*A[3]+A[j];
// }
// }
// #endif
| [
"[email protected]"
]
| |
cc5f3112020949520a59003b1f6e87947b55b917 | 9b8d0efebecb318a83f97b47dc33cd9ff7646939 | /EGamma/ECGelec/plugins/SimpleNtpleCustom.cc | 69de9aec9b47ab0e16a3b396fa22127005e1f71b | []
| no_license | icantropo/SpikesKiller | 9d5b63f9ce10e07d3938edc895674d34eb3d00fb | fd017e35d58c5e8c74be883896b542c974dcc8e7 | refs/heads/master | 2016-09-05T18:34:50.342411 | 2015-07-02T18:14:25 | 2015-07-02T18:14:25 | 37,803,241 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 217,148 | cc | #include "EGamma/ECGelec/plugins/SimpleNtpleCustom.h"
using namespace std;
using namespace reco;
using namespace edm;
using namespace IPTools;
//using namespace math;
// ====================================================================================
SimpleNtpleCustom::SimpleNtpleCustom(const edm::ParameterSet& iConfig) :
// Nadir study
//EcalRecHitCollectionEB_ (iConfig.getParameter<edm::InputTag>("EcalRecHitCollectionEB")),
hcalTowers_ (iConfig.getParameter<edm::InputTag>("hcalTowers")),
hOverEConeSize_ (iConfig.getParameter<double>("hOverEConeSize")),
hOverEPtMin_ (iConfig.getParameter<double>("hOverEPtMin")),
nadGetL1M_ (iConfig.getUntrackedParameter<bool>("NadL1M")),
nadGetTP_ (iConfig.getUntrackedParameter<bool>("NadTP")),
nadGetTP_Modif_ (iConfig.getUntrackedParameter<bool>("NadTPmodif")),
nadGetTP_Emul_ (iConfig.getUntrackedParameter<bool>("NadTPemul")),
PrintDebug_ (iConfig.getUntrackedParameter<bool>("PrintDebug")),
tpCollectionNormal_ (iConfig.getParameter<edm::InputTag> ("TPCollectionNormal") ),
tpCollectionModif_ (iConfig.getParameter<edm::InputTag> ("TPCollectionModif") ),
tpEmulatorCollection_ (iConfig.getParameter<edm::InputTag> ("TPEmulatorCollection") ),
EleID_VeryLooseTag_ (iConfig.getParameter<edm::InputTag> ("eleID_VeryLooseTag")) ,
EleID_LooseTag_ (iConfig.getParameter<edm::InputTag> ("eleID_LooseTag")) ,
EleID_MediumTag_ (iConfig.getParameter<edm::InputTag> ("eleID_MediumTag")) ,
EleID_TightTag_ (iConfig.getParameter<edm::InputTag> ("eleID_TightTag")) ,
EleID_SuperTightTag_ (iConfig.getParameter<edm::InputTag> ("eleID_SuperTightTag")) ,
EleID_HyperTight1Tag_ (iConfig.getParameter<edm::InputTag> ("eleID_HyperTight1Tag")) ,
EleID_HyperTight2Tag_ (iConfig.getParameter<edm::InputTag> ("eleID_HyperTight2Tag")) ,
EleID_HyperTight3Tag_ (iConfig.getParameter<edm::InputTag> ("eleID_HyperTight3Tag")) ,
EleID_HyperTight4Tag_ (iConfig.getParameter<edm::InputTag> ("eleID_HyperTight4Tag")) ,
EleIso_TdrHzzTkMapTag_ (iConfig.getParameter<edm::InputTag>("eleIso_TdrHzzTkMapTag")),
EleIso_TdrHzzHcalMapTag_ (iConfig.getParameter<edm::InputTag>("eleIso_TdrHzzHcalMapTag")),
EleIso_Eg4HzzTkMapTag_ (iConfig.getParameter<edm::InputTag>("eleIso_Eg4HzzTkMapTag")),
EleIso_Eg4HzzEcalMapTag_ (iConfig.getParameter<edm::InputTag>("eleIso_Eg4HzzEcalMapTag")),
EleIso_Eg4HzzHcalMapTag_ (iConfig.getParameter<edm::InputTag>("eleIso_Eg4HzzHcalMapTag")),
EleTag_ (iConfig.getParameter<edm::InputTag> ("EleTag")),
MuonTag_ (iConfig.getParameter<edm::InputTag> ("MuonTag")),
MuonIso_HzzMapTag_ (iConfig.getParameter<edm::InputTag>("MuonIso_HzzMapTag")),
MuonIsoTk_HzzMapTag_ (iConfig.getParameter<edm::InputTag>("MuonIsoTk_HzzMapTag")),
MuonIsoEcal_HzzMapTag_ (iConfig.getParameter<edm::InputTag>("MuonIsoEcal_HzzMapTag")),
MuonIsoHcal_HzzMapTag_ (iConfig.getParameter<edm::InputTag>("MuonIsoHcal_HzzMapTag")),
SeedTag_ (iConfig.getParameter<edm::InputTag> ("SeedTag")),
MCTag_ (iConfig.getParameter<edm::InputTag>("MCTag")),
TkPTag_ (iConfig.getParameter<edm::InputTag>("TkPTag")),
CaloJetTag_(iConfig.getParameter<edm::InputTag> ("CaloJetTag")),
JPTJetTag_(iConfig.getParameter<edm::InputTag> ("JPTJetTag")),
PFJetTag_(iConfig.getParameter<edm::InputTag> ("PFJetTag")),
VerticesTag_(iConfig.getParameter<edm::InputTag> ("VerticesTag")),
dcsTag_ (iConfig.getUntrackedParameter<edm::InputTag>("dcsTag")),
// Trigger Stuff
HLTTag_(iConfig.getParameter<edm::InputTag> ("HLTTag")),
triggerEventTag_(iConfig.getParameter<edm::InputTag> ("TriggerEventTag")),
//
PileupSrc_ ("addPileupInfo"),
RhoCorrection_("kt6PFJets:rho"),
SigmaRhoCorrection_("kt6PFJets:sigma"),
type_ (iConfig.getParameter<std::string>("type")),
aod_ (iConfig.getUntrackedParameter<bool>("AOD")),
funcname_ (iConfig.getParameter<std::string>("functionName")),
useBeamSpot_ (iConfig.getParameter<bool>("useBeamSpot"))
//
//,"addPileupInfo::REDIGI311X"))
//
// ====================================================================================
{
//now do what ever initialization is needed
funcbase_ = EcalClusterFunctionFactory::get()->create( funcname_, iConfig );
gtRecordCollectionTag_ = iConfig.getParameter<std::string>("GTRecordCollection") ;
HLT_ElePaths_ = iConfig.getParameter<std::vector<std::string > >("HLTElePaths");
HLT_MuonPaths_ = iConfig.getParameter<std::vector<std::string > >("HLTMuonPaths");
HLT_Filters_ = iConfig.getParameter<std::vector<edm::InputTag > >("HLTFilters");
simulation_ = iConfig.getUntrackedParameter<bool>("simulation", false);
fillsc_ = iConfig.getUntrackedParameter<bool>("FillSC", false);
edm::Service<TFileService> fs ;
mytree_ = fs->make <TTree>("eIDSimpleTree","eIDSimpleTree");
// Global
mytree_->Branch("nEvent",&nEvent,"nEvent/I");
mytree_->Branch("nRun",&nRun,"nRun/I");
mytree_->Branch("nLumi",&nLumi,"nLumi/I");
// Pile UP
mytree_->Branch("PU_N",&_PU_N,"PU_N/I");
mytree_->Branch("PU_rhoCorr",&_PU_rho,"PU_rhoCorr/D");
mytree_->Branch("PU_sigmaCorr",&_PU_sigma,"PU_sigmaCorr/D");
// Vertices
mytree_->Branch("vtx_N",&_vtx_N,"vtx_N/I");
mytree_->Branch("vtx_normalizedChi2",&_vtx_normalizedChi2,"vtx_normalizedChi2[15]/D");
mytree_->Branch("vtx_ndof",&_vtx_ndof,"vtx_ndof[15]/D");
mytree_->Branch("vtx_nTracks",&_vtx_nTracks,"vtx_nTracks[15]/D");
mytree_->Branch("vtx_d0",&_vtx_d0,"vtx_d0[15]/D");
mytree_->Branch("vtx_x",&_vtx_x,"vtx_x[15]/D");
mytree_->Branch("vtx_y",&_vtx_y,"vtx_y[15]/D");
mytree_->Branch("vtx_z",&_vtx_z,"vtx_z[15]/D");
// Skim
mytree_->Branch("skim_is1lepton", &_skim_is1lepton, "skim_is1lepton/I");
mytree_->Branch("skim_is2leptons",&_skim_is2leptons,"skim_is2leptons/I");
mytree_->Branch("skim_is3leptons",&_skim_is3leptons,"skim_is3leptons/I");
// Towers (original collection)
mytree_->Branch("trig_tower_N", &_trig_tower_N, "trig_tower_N/I");
mytree_->Branch("trig_tower_ieta", &_trig_tower_ieta, "trig_tower_ieta[trig_tower_N]/I");
mytree_->Branch("trig_tower_iphi", &_trig_tower_iphi, "trig_tower_iphi[trig_tower_N]/I");
mytree_->Branch("trig_tower_adc", &_trig_tower_adc, "trig_tower_adc[trig_tower_N]/I");
mytree_->Branch("trig_tower_sFGVB", &_trig_tower_sFGVB, "trig_tower_sFGVB[trig_tower_N]/I");
// Towers (cleaned collection)
mytree_->Branch("trig_tower_N_modif", &_trig_tower_N_modif, "trig_tower_N_modif/I");
mytree_->Branch("trig_tower_ieta_modif", &_trig_tower_ieta_modif, "trig_tower_ieta_modif[trig_tower_N_modif]/I");
mytree_->Branch("trig_tower_iphi_modif", &_trig_tower_iphi_modif, "trig_tower_iphi_modif[trig_tower_N_modif]/I");
mytree_->Branch("trig_tower_adc_modif", &_trig_tower_adc_modif, "trig_tower_adc_modif[trig_tower_N_modif]/I");
mytree_->Branch("trig_tower_sFGVB_modif", &_trig_tower_sFGVB_modif, "trig_tower_sFGVB_modif[trig_tower_N_modif]/I");
// Towers (emulated)
mytree_->Branch("trig_tower_N_emul", &_trig_tower_N_emul, "trig_tower_N_emul/I");
mytree_->Branch("trig_tower_ieta_emul", &_trig_tower_ieta_emul, "trig_tower_ieta_emul[trig_tower_N_emul]/I");
mytree_->Branch("trig_tower_iphi_emul", &_trig_tower_iphi_emul, "trig_tower_iphi_emul[trig_tower_N_emul]/I");
mytree_->Branch("trig_tower_adc_emul", &_trig_tower_adc_emul, "trig_tower_adc_emul[trig_tower_N_emul][5]/I");
mytree_->Branch("trig_tower_sFGVB_emul", &_trig_tower_sFGVB_emul, "trig_tower_sFGVB_emul[trig_tower_N_emul][5]/I");
// Trigger
mytree_->Branch("trig_fired_names",&trig_fired_names,"trig_fired_names[5000]/C");
mytree_->Branch("trig_hltInfo",&trig_hltInfo,"trig_hltInfo[250]/I");
mytree_->Branch("trig_isUnbiased",&trig_isUnbiased,"trig_isUnbiased/I");
mytree_->Branch("trig_isPhoton10",&trig_isPhoton10,"trig_isPhoton10/I");
mytree_->Branch("trig_isPhoton15",&trig_isPhoton15,"trig_isPhoton15/I");
mytree_->Branch("trig_isL1SingleEG2",&trig_isL1SingleEG2,"trig_isL1SingleEG2/I");
mytree_->Branch("trig_isL1SingleEG5",&trig_isL1SingleEG5,"trig_isL1SingleEG5/I");
mytree_->Branch("trig_isL1SingleEG8",&trig_isL1SingleEG8,"trig_isL1SingleEG8/I");
mytree_->Branch("trig_isEle10_LW",&trig_isEle10_LW,"trig_isEle10_LW/I");
mytree_->Branch("trig_isEle15_LW",&trig_isEle15_LW,"trig_isEle15_LW/I");
//
mytree_->Branch("trig_isEleHLTpath", &_trig_isEleHLTpath, "trig_isEleHLTpath/I");
mytree_->Branch("trig_isMuonHLTpath", &_trig_isMuonHLTpath, "trig_isMuonHLTpath/I");
//
mytree_->Branch("trig_L1emIso_N", &_trig_L1emIso_N, "trig_L1emIso_N/I");
mytree_->Branch("trig_L1emIso_ieta", &_trig_L1emIso_ieta, "trig_L1emIso_ieta[4]/I");
mytree_->Branch("trig_L1emIso_iphi", &_trig_L1emIso_iphi, "trig_L1emIso_iphi[4]/I");
mytree_->Branch("trig_L1emIso_rank", &_trig_L1emIso_rank, "trig_L1emIso_rank[4]/I");
mytree_->Branch("trig_L1emIso_eta", &_trig_L1emIso_eta, "trig_L1emIso_eta[4]/D");
mytree_->Branch("trig_L1emIso_phi", &_trig_L1emIso_phi, "trig_L1emIso_phi[4]/D");
mytree_->Branch("trig_L1emIso_energy",&_trig_L1emIso_energy,"trig_L1emIso_energy[4]/D");
mytree_->Branch("trig_L1emIso_et", &_trig_L1emIso_et, "trig_L1emIso_et[4]/D");
//
mytree_->Branch("trig_L1emNonIso_N", &_trig_L1emNonIso_N, "trig_L1emNonIso_N/I");
mytree_->Branch("trig_L1emNonIso_ieta", &_trig_L1emNonIso_ieta, "trig_L1emNonIso_ieta[4]/I");
mytree_->Branch("trig_L1emNonIso_iphi", &_trig_L1emNonIso_iphi, "trig_L1emNonIso_iphi[4]/I");
mytree_->Branch("trig_L1emNonIso_rank", &_trig_L1emNonIso_rank, "trig_L1emNonIso_rank[4]/I");
mytree_->Branch("trig_L1emNonIso_eta", &_trig_L1emNonIso_eta, "trig_L1emNonIso_eta[4]/D");
mytree_->Branch("trig_L1emNonIso_phi", &_trig_L1emNonIso_phi, "trig_L1emNonIso_phi[4]/D");
mytree_->Branch("trig_L1emNonIso_energy",&_trig_L1emNonIso_energy,"trig_L1emNonIso_energy[4]/D");
mytree_->Branch("trig_L1emNonIso_et", &_trig_L1emNonIso_et, "trig_L1emNonIso_et[4]/D");
// L1 candidates : modified collection
mytree_->Branch("trig_L1emIso_N_M", &_trig_L1emIso_N_M, "trig_L1emIso_N_M/I");
mytree_->Branch("trig_L1emIso_ieta_M", &_trig_L1emIso_ieta_M, "trig_L1emIso_ieta_M[4]/I");
mytree_->Branch("trig_L1emIso_iphi_M", &_trig_L1emIso_iphi_M, "trig_L1emIso_iphi_M[4]/I");
mytree_->Branch("trig_L1emIso_rank_M", &_trig_L1emIso_rank_M, "trig_L1emIso_rank_M[4]/I");
mytree_->Branch("trig_L1emIso_eta_M", &_trig_L1emIso_eta_M, "trig_L1emIso_eta_M[4]/D");
mytree_->Branch("trig_L1emIso_phi_M", &_trig_L1emIso_phi_M, "trig_L1emIso_phi_M[4]/D");
mytree_->Branch("trig_L1emIso_energy_M",&_trig_L1emIso_energy_M,"trig_L1emIso_energy_M[4]/D");
mytree_->Branch("trig_L1emIso_et_M", &_trig_L1emIso_et_M, "trig_L1emIso_et_M[4]/D");
//
mytree_->Branch("trig_L1emNonIso_N_M", &_trig_L1emNonIso_N_M, "trig_L1emNonIso_N/I");
mytree_->Branch("trig_L1emNonIso_ieta_M", &_trig_L1emNonIso_ieta_M, "trig_L1emNonIso_ieta_M[4]/I");
mytree_->Branch("trig_L1emNonIso_iphi_M", &_trig_L1emNonIso_iphi_M, "trig_L1emNonIso_iphi_M[4]/I");
mytree_->Branch("trig_L1emNonIso_rank_M", &_trig_L1emNonIso_rank_M, "trig_L1emNonIso_rank_M[4]/I");
mytree_->Branch("trig_L1emNonIso_eta_M", &_trig_L1emNonIso_eta_M, "trig_L1emNonIso_eta_M[4]/D");
mytree_->Branch("trig_L1emNonIso_phi_M", &_trig_L1emNonIso_phi_M, "trig_L1emNonIso_phi_M[4]/D");
mytree_->Branch("trig_L1emNonIso_energy_M",&_trig_L1emNonIso_energy_M,"trig_L1emNonIso_energy_M[4]/D");
mytree_->Branch("trig_L1emNonIso_et_M", &_trig_L1emNonIso_et_M, "trig_L1emNonIso_et_M[4]/D");
// pre/post - firing
mytree_->Branch("trig_preL1emIso_N", &_trig_preL1emIso_N, "trig_preL1emIso_N/I");
mytree_->Branch("trig_preL1emIso_ieta", &_trig_preL1emIso_ieta, "trig_preL1emIso_ieta[4]/I");
mytree_->Branch("trig_preL1emIso_iphi", &_trig_preL1emIso_iphi, "trig_preL1emIso_iphi[4]/I");
mytree_->Branch("trig_preL1emIso_rank", &_trig_preL1emIso_rank, "trig_preL1emIso_rank[4]/I");
//
mytree_->Branch("trig_preL1emNonIso_N", &_trig_preL1emNonIso_N, "trig_preL1emNonIso_N/I");
mytree_->Branch("trig_preL1emNonIso_ieta", &_trig_preL1emNonIso_ieta, "trig_preL1emNonIso_ieta[4]/I");
mytree_->Branch("trig_preL1emNonIso_iphi", &_trig_preL1emNonIso_iphi, "trig_preL1emNonIso_iphi[4]/I");
mytree_->Branch("trig_preL1emNonIso_rank", &_trig_preL1emNonIso_rank, "trig_preL1emNonIso_rank[4]/I");
//
mytree_->Branch("trig_postL1emIso_N", &_trig_postL1emIso_N, "trig_postL1emIso_N/I");
mytree_->Branch("trig_postL1emIso_ieta", &_trig_postL1emIso_ieta, "trig_postL1emIso_ieta[4]/I");
mytree_->Branch("trig_postL1emIso_iphi", &_trig_postL1emIso_iphi, "trig_postL1emIso_iphi[4]/I");
mytree_->Branch("trig_postL1emIso_rank", &_trig_postL1emIso_rank, "trig_postL1emIso_rank[4]/I");
//
mytree_->Branch("trig_postL1emNonIso_N", &_trig_postL1emNonIso_N, "trig_postL1emNonIso_N/I");
mytree_->Branch("trig_postL1emNonIso_ieta", &_trig_postL1emNonIso_ieta, "trig_postL1emNonIso_ieta[4]/I");
mytree_->Branch("trig_postL1emNonIso_iphi", &_trig_postL1emNonIso_iphi, "trig_postL1emNonIso_iphi[4]/I");
mytree_->Branch("trig_postL1emNonIso_rank", &_trig_postL1emNonIso_rank, "trig_postL1emNonIso_rank[4]/I");
//
mytree_->Branch("trig_nMaskedRCT", &_trig_nMaskedRCT, "trig_nMaskedRCT/I");
mytree_->Branch("trig_iMaskedRCTeta", &_trig_iMaskedRCTeta, "trig_iMaskedRCTeta[trig_nMaskedRCT]/I");
mytree_->Branch("trig_iMaskedRCTcrate", &_trig_iMaskedRCTcrate,"trig_iMaskedRCTcrate[trig_nMaskedRCT]/I");
mytree_->Branch("trig_iMaskedRCTphi", &_trig_iMaskedRCTphi, "trig_iMaskedRCTphi[trig_nMaskedRCT]/I");
mytree_->Branch("trig_nMaskedCh", &_trig_nMaskedCh, "trig_nMaskedCh/I");
mytree_->Branch("trig_iMaskedTTeta", &_trig_iMaskedTTeta, "trig_iMaskedTTeta[trig_nMaskedCh]/I");
mytree_->Branch("trig_iMaskedTTphi", &_trig_iMaskedTTphi, "trig_iMaskedTTphi[trig_nMaskedCh]/I");
//
mytree_->Branch("trig_HLT_N", &_trig_HLT_N, "trig_HLT_N/I");
mytree_->Branch("trig_HLT_eta", &_trig_HLT_eta, "trig_HLT_eta[20]/D");
mytree_->Branch("trig_HLT_phi", &_trig_HLT_phi, "trig_HLT_phi[20]/D");
mytree_->Branch("trig_HLT_energy", &_trig_HLT_energy,"trig_HLT_energy[20]/D");
mytree_->Branch("trig_HLT_pt", &_trig_HLT_pt, "trig_HLT_pt[20]/D");
mytree_->Branch("trig_HLT_name", &_trig_HLT_name, "trig_HLT_name[20]/I");
// Beam Spot
mytree_->Branch("BS_x",&BS_x,"BS_x/D");
mytree_->Branch("BS_y",&BS_y,"BS_y/D");
mytree_->Branch("BS_z",&BS_z,"BS_z/D");
mytree_->Branch("BS_dz",&BS_dz,"BS_dz/D");
mytree_->Branch("BS_dxdz",&BS_dxdz,"BS_dxdz/D");
mytree_->Branch("BS_dydz",&BS_dydz,"BS_dydz/D");
mytree_->Branch("BS_bw_x",&BS_bw_x,"BS_bw_x/D");
mytree_->Branch("BS_bw_y",&BS_bw_y,"BS_bw_y/D");
// MC Properties
mytree_->Branch("MC_pthat",&_MC_pthat,"MC_pthat/D");
mytree_->Branch("MC_flavor",&_MC_flavor,"MC_flavor[2]/I");
// MC Truth Matching
mytree_->Branch("ele_MC_chosenEle_PoP_px",ele_MC_chosenEle_PoP_px,"ele_MC_chosenEle_PoP_px[10]/D");
mytree_->Branch("ele_MC_chosenEle_PoP_py",ele_MC_chosenEle_PoP_py,"ele_MC_chosenEle_PoP_py[10]/D");
mytree_->Branch("ele_MC_chosenEle_PoP_pz",ele_MC_chosenEle_PoP_pz,"ele_MC_chosenEle_PoP_pz[10]/D");
mytree_->Branch("ele_MC_chosenEle_PoP_e",ele_MC_chosenEle_PoP_e,"ele_MC_chosenEle_PoP_e[10]/D");
mytree_->Branch("ele_MC_chosenPho_PoP_px",ele_MC_chosenPho_PoP_px,"ele_MC_chosenPho_PoP_px[10]/D");
mytree_->Branch("ele_MC_chosenPho_PoP_py",ele_MC_chosenPho_PoP_py,"ele_MC_chosenPho_PoP_py[10]/D");
mytree_->Branch("ele_MC_chosenPho_PoP_pz",ele_MC_chosenPho_PoP_pz,"ele_MC_chosenPho_PoP_pz[10]/D");
mytree_->Branch("ele_MC_chosenPho_PoP_e",ele_MC_chosenPho_PoP_e,"ele_MC_chosenPho_PoP_e[10]/D");
mytree_->Branch("ele_MC_chosenHad_PoP_px",ele_MC_chosenHad_PoP_px,"ele_MC_chosenHad_PoP_px[10]/D");
mytree_->Branch("ele_MC_chosenHad_PoP_py",ele_MC_chosenHad_PoP_py,"ele_MC_chosenHad_PoP_py[10]/D");
mytree_->Branch("ele_MC_chosenHad_PoP_pz",ele_MC_chosenHad_PoP_pz,"ele_MC_chosenHad_PoP_pz[10]/D");
mytree_->Branch("ele_MC_chosenHad_PoP_e",ele_MC_chosenHad_PoP_e,"ele_MC_chosenHad_PoP_e[10]/D");
mytree_->Branch("ele_MC_closest_DR_px",ele_MC_closest_DR_px,"ele_MC_closest_DR_px[10]/D");
mytree_->Branch("ele_MC_closest_DR_py",ele_MC_closest_DR_py,"ele_MC_closest_DR_py[10]/D");
mytree_->Branch("ele_MC_closest_DR_pz",ele_MC_closest_DR_pz,"ele_MC_closest_DR_pz[10]/D");
mytree_->Branch("ele_MC_closest_DR_e",ele_MC_closest_DR_e,"ele_MC_closest_DR_e[10]/D");
mytree_->Branch("ele_N",&ele_N,"ele_N/I");
mytree_->Branch("ele_echarge",ele_echarge,"ele_echarge[10]/I");
mytree_->Branch("ele_he",ele_he,"ele_he[10]/D");
mytree_->Branch("ele_pin_mode",ele_pin_mode,"ele_pin_mode[10]/D");
mytree_->Branch("ele_pout_mode",ele_pout_mode,"ele_pout_mode[10]/D");
mytree_->Branch("ele_pin_mean",ele_pin_mean,"ele_pin_mean[10]/D");
mytree_->Branch("ele_pout_mean",ele_pout_mean,"ele_pout_mean[10]/D");
mytree_->Branch("ele_pTin_mode",ele_pTin_mode,"ele_pTin_mode[10]/D");
mytree_->Branch("ele_pTout_mode",ele_pTout_mode,"ele_pTout_mode[10]/D");
mytree_->Branch("ele_pTin_mean",ele_pTin_mean,"ele_pTin_mean[10]/D");
mytree_->Branch("ele_pTout_mean",ele_pTout_mean,"ele_pTout_mean[10]/D");
mytree_->Branch("ele_calo_energy",ele_calo_energy,"ele_calo_energy[10]/D");
mytree_->Branch("ele_sclRawE",ele_sclRawE,"els_sclRawE[10]/D");
mytree_->Branch("ele_sclEpresh",ele_sclEpresh,"els_sclEpresh[10]/D");
mytree_->Branch("ele_sclE",ele_sclE,"ele_sclE[10]/D");
mytree_->Branch("ele_sclEt",ele_sclEt,"ele_sclEt[10]/D");
mytree_->Branch("ele_sclEta",ele_sclEta,"ele_sclEta[10]/D");
mytree_->Branch("ele_sclPhi",ele_sclPhi,"ele_sclPhi[10]/D");
mytree_->Branch("ele_sclX",ele_sclX,"ele_sclX[10]/D");
mytree_->Branch("ele_sclY",ele_sclY,"ele_sclY[10]/D");
mytree_->Branch("ele_sclZ",ele_sclZ,"ele_sclZ[10]/D");
mytree_->Branch("ele_sclErr",ele_sclErr,"ele_sclErr[10]/D");
mytree_->Branch("ele_sclErr_pos",ele_sclErr_pos,"ele_sclErr_pos[10]/D");
mytree_->Branch("ele_sclErr_neg",ele_sclErr_neg,"ele_sclErr_neg[10]/D");
mytree_->Branch("ele_trErr",ele_trErr,"ele_trErr[10]/D");
mytree_->Branch("ele_momErr",ele_momErr,"ele_momErr[10]/D");
mytree_->Branch("ele_newmom",ele_newmom,"ele_newmom[10]/D");
mytree_->Branch("ele_newmomErr",ele_newmomErr,"ele_newmomErr[10]/D");
mytree_->Branch("ele_tr_atcaloX",ele_tr_atcaloX,"ele_tr_atcaloX[10]/D");
mytree_->Branch("ele_tr_atcaloY",ele_tr_atcaloY,"ele_tr_atcaloY[10]/D");
mytree_->Branch("ele_tr_atcaloZ",ele_tr_atcaloZ,"ele_tr_atcaloZ[10]/D");
mytree_->Branch("ele_firsthit_X",ele_firsthit_X,"ele_firsthit_X[10]/D");
mytree_->Branch("ele_firsthit_Y",ele_firsthit_Y,"ele_firsthit_Y[10]/D");
mytree_->Branch("ele_firsthit_Z",ele_firsthit_Z,"ele_firsthit_Z[10]/D");
// NEW H/E
mytree_->Branch("ele_he_00615_0", _ele_he_00615_0 ,"ele_he_00615_0[10]/D");
mytree_->Branch("ele_he_005_0", _ele_he_005_0 ,"ele_he_005_0[10]/D");
mytree_->Branch("ele_he_005_1", _ele_he_005_1,"ele_he_005_1[10]/D");
mytree_->Branch("ele_he_005_15", _ele_he_005_15,"ele_he_005_15[10]/D");
mytree_->Branch("ele_he_01_0", _ele_he_01_0,"ele_he_01_0[10]/D");
mytree_->Branch("ele_he_01_1", _ele_he_01_1,"ele_he_01_1[10]/D");
mytree_->Branch("ele_he_01_15", _ele_he_01_15,"ele_he_01_15[10]/D");
mytree_->Branch("ele_he_015_1", _ele_he_015_1,"ele_he_015_1[10]/D");
mytree_->Branch("ele_he_015_15",_ele_he_015_15 ,"ele_he_015_15[10]/D");
mytree_->Branch("ele_eseedpout",ele_eseedpout,"ele_eseedpout[10]/D");
mytree_->Branch("ele_ep",ele_ep,"ele_ep[10]/D");
mytree_->Branch("ele_eseedp",ele_eseedp,"ele_eseedp[10]/D");
mytree_->Branch("ele_eelepout",ele_eelepout,"ele_eelepout[10]/D");
mytree_->Branch("ele_deltaetaseed",ele_deltaetaseed,"ele_deltaetaseed[10]/D");
mytree_->Branch("ele_deltaphiseed",ele_deltaphiseed,"ele_deltaphiseed[10]/D");
mytree_->Branch("ele_deltaetaele",ele_deltaetaele,"ele_deltaetaele[10]/D");
mytree_->Branch("ele_deltaphiele",ele_deltaphiele,"ele_deltaphiele[10]/D");
mytree_->Branch("ele_deltaetain",ele_deltaetain,"ele_deltaetain[10]/D");
mytree_->Branch("ele_deltaphiin",ele_deltaphiin,"ele_deltaphiin[10]/D");
mytree_->Branch("ele_sigmaietaieta",ele_sigmaietaieta,"ele_sigmaietaieta[10]/D");
mytree_->Branch("ele_sigmaetaeta",ele_sigmaetaeta,"ele_sigmaetaeta[10]/D");
mytree_->Branch("ele_e15",ele_e15,"ele_e15[10]/D");
mytree_->Branch("ele_e25max",ele_e25max,"ele_e25max[10]/D");
mytree_->Branch("ele_e55",ele_e55,"ele_e55[10]/D");
mytree_->Branch("ele_e1",ele_e1,"ele_e1[10]/D");
mytree_->Branch("ele_e33",ele_e33,"ele_e33[10]/D");
mytree_->Branch("ele_e2overe9",ele_e2overe9,"ele_e2overe9[10]/D");
mytree_->Branch("ele_fbrem",ele_fbrem,"ele_fbrem[10]/D");
mytree_->Branch("ele_mva",ele_mva,"ele_mva[10]/D");
mytree_->Branch("ele_isbarrel",ele_isbarrel,"ele_isbarrel[10]/I");
mytree_->Branch("ele_isendcap",ele_isendcap,"ele_isendcap[10]/I");
mytree_->Branch("ele_isEBetaGap",ele_isEBetaGap,"ele_isEBetaGap[10]/I");
mytree_->Branch("ele_isEBphiGap",ele_isEBphiGap,"ele_isEBphiGap[10]/I");
mytree_->Branch("ele_isEEdeeGap",ele_isEEdeeGap,"ele_isEEdeeGap[10]/I");
mytree_->Branch("ele_isEEringGap",ele_isEEringGap,"ele_isEEringGap[10]/I");
mytree_->Branch("ele_isecalDriven",ele_isecalDriven,"ele_isecalDriven[10]/I");
mytree_->Branch("ele_istrackerDriven",ele_istrackerDriven,"ele_istrackerDriven[10]/I");
mytree_->Branch("ele_eClass",ele_eClass,"ele_eClass[10]/I");
mytree_->Branch("ele_missing_hits",ele_missing_hits,"ele_missing_hits[10]/I");
mytree_->Branch("ele_lost_hits",ele_lost_hits,"ele_lost_hits[10]/I");
mytree_->Branch("ele_chi2_hits",ele_chi2_hits,"ele_chi2_hits[10]/D");
mytree_->Branch("ele_dxy",ele_dxy,"ele_dxy[10]/D");
mytree_->Branch("ele_dxyB",ele_dxyB,"ele_dxyB[10]/D");
mytree_->Branch("ele_dz",ele_dz,"ele_dz[10]/D");
mytree_->Branch("ele_dzB",ele_dzB,"ele_dzB[10]/D");
mytree_->Branch("ele_dsz",ele_dsz,"ele_dsz[10]/D");
mytree_->Branch("ele_dszB",ele_dszB,"ele_dszB[10]/D");
mytree_->Branch("ele_dzPV",ele_dzPV,"ele_dzPV[10]/D");
mytree_->Branch("ele_dzPV_error",ele_dzPV_error,"ele_dzPV_error[10]/D");
mytree_->Branch("ele_dxyPV",ele_dxyPV,"ele_dxyPV[10]/D");
mytree_->Branch("ele_dxyPV_error",ele_dxyPV_error,"ele_dxyPV_error[10]/D");
mytree_->Branch("ele_dszPV",ele_dszPV,"ele_dszPV[10]/D");
mytree_->Branch("ele_dszPV_error",ele_dszPV_error,"ele_dszPV_error[10]/D");
mytree_->Branch("ele_eidVeryLoose",ele_eidVeryLoose,"ele_eidVeryLoose[10]/D");
mytree_->Branch("ele_eidLoose",ele_eidLoose,"ele_eidLoose[10]/D");
mytree_->Branch("ele_eidMedium",ele_eidMedium,"ele_eidMedium[10]/D");
mytree_->Branch("ele_eidTight",ele_eidTight,"ele_eidTight[10]/D");
mytree_->Branch("ele_eidSuperTight",ele_eidSuperTight,"ele_eidSuperTight[10]/D");
mytree_->Branch("ele_eidHyperTight1",ele_eidHyperTight1,"ele_eidHyperTight1[10]/D");
mytree_->Branch("ele_eidHyperTight2",ele_eidHyperTight2,"ele_eidHyperTight2[10]/D");
mytree_->Branch("ele_eidHyperTight3",ele_eidHyperTight3,"ele_eidHyperTight3[10]/D");
mytree_->Branch("ele_eidHyperTight4",ele_eidHyperTight4,"ele_eidHyperTight4[10]/D");
mytree_->Branch("ele_severityLevelSeed",ele_severityLevelSeed,"ele_severityLevelSeed[10]/I");
mytree_->Branch("ele_severityLevelClusters",ele_severityLevelClusters,"ele_severityLevelClusters[10]/I");
mytree_->Branch("ele_outOfTimeSeed",ele_outOfTimeSeed,"ele_outOfTimeSeed[10]/I");
mytree_->Branch("ele_outOfTimeClusters",ele_outOfTimeClusters,"ele_outOfTimeClusters[10]/I");
//Conversion Removal
mytree_->Branch("ele_isConversion",ele_isConversion,"ele_isConversion[10]/I");
mytree_->Branch("ele_convFound",ele_convFound,"ele_convFound[10]/I");
mytree_->Branch("ele_conv_dist",&ele_conv_dist,"ele_conv_dist[10]/D");
mytree_->Branch("ele_conv_dcot",&ele_conv_dcot,"ele_conv_dcot[10]/D");
mytree_->Branch("ele_track_x",ele_track_x,"ele_track_x[10]/D");
mytree_->Branch("ele_track_y",ele_track_y,"ele_track_y[10]/D");
mytree_->Branch("ele_track_z",ele_track_z,"ele_track_z[10]/D");
mytree_->Branch("ele_vertex_x",ele_vertex_x,"ele_vertex_x[10]/D");
mytree_->Branch("ele_vertex_y",ele_vertex_y,"ele_vertex_y[10]/D");
mytree_->Branch("ele_vertex_z",ele_vertex_z,"ele_vertex_z[10]/D");
mytree_->Branch("ele_tkSumPt_dr03",ele_tkSumPt_dr03,"ele_tkSumPt_dr03[10]/D");
mytree_->Branch("ele_ecalRecHitSumEt_dr03",ele_ecalRecHitSumEt_dr03,"ele_ecalRecHitSumEt_dr03[10]/D");
mytree_->Branch("ele_hcalDepth1TowerSumEt_dr03",ele_hcalDepth1TowerSumEt_dr03,"ele_hcalDepth1TowerSumEt_dr03[10]/D");
mytree_->Branch("ele_hcalDepth2TowerSumEt_dr03",ele_hcalDepth2TowerSumEt_dr03,"ele_hcalDepth2TowerSumEt_dr03[10]/D");
mytree_->Branch("ele_hcalDepth1plus2TowerSumEt_00615dr03",ele_hcalDepth1plus2TowerSumEt_00615dr03,"ele_hcalDepth1plus2TowerSumEt_00615dr03[10]/D");
mytree_->Branch("ele_hcalDepth1plus2TowerSumEt_005dr03",ele_hcalDepth1plus2TowerSumEt_005dr03,"ele_hcalDepth1plus2TowerSumEt_005dr03[10]/D");
mytree_->Branch("ele_hcalDepth1plus2TowerSumEt_0dr03",ele_hcalDepth1plus2TowerSumEt_0dr03,"ele_hcalDepth1plus2TowerSumEt_0dr03[10]/D");
mytree_->Branch("ele_tkSumPt_dr04",ele_tkSumPt_dr04,"ele_tkSumPt_dr04[10]/D");
mytree_->Branch("ele_ecalRecHitSumEt_dr04",ele_ecalRecHitSumEt_dr04,"ele_ecalRecHitSumEt_dr04[10]/D");
mytree_->Branch("ele_hcalDepth1TowerSumEt_dr04",ele_hcalDepth1TowerSumEt_dr04,"ele_hcalDepth1TowerSumEt_dr04[10]/D");
mytree_->Branch("ele_hcalDepth2TowerSumEt_dr04",ele_hcalDepth2TowerSumEt_dr04,"ele_hcalDepth2TowerSumEt_dr04[10]/D");
mytree_->Branch("ele_tkSumPtTdrHzz_dr025",ele_tkSumPtTdrHzz_dr025,"ele_tkSumPtTdrHzz_dr025[10]/D");
mytree_->Branch("ele_tkSumPtoPtTdrHzz_dr025",ele_tkSumPtoPtTdrHzz_dr025,"ele_tkSumPtoPtTdrHzz_dr025[10]/D");
mytree_->Branch("ele_hcalSumEtTdrHzz_dr02",ele_hcalSumEtTdrHzz_dr02,"ele_hcalSumEtTdrHzz_dr02[10]/D");
mytree_->Branch("ele_hcalSumEtoPtTdrHzz_dr02",ele_hcalSumEtoPtTdrHzz_dr02,"ele_hcalSumEtoPtTdrHzz_dr02[10]/D");
mytree_->Branch("ele_tkSumPtEg4Hzz_dr03",ele_tkSumPtEg4Hzz_dr03,"ele_tkSumPtEg4Hzz_dr03[10]/D");
mytree_->Branch("ele_tkSumPtoPtEg4Hzz_dr03",ele_tkSumPtoPtEg4Hzz_dr03,"ele_tkSumPtoPtEg4Hzz_dr03[10]/D");
mytree_->Branch("ele_ecalSumEtEg4Hzz_dr03",ele_ecalSumEtEg4Hzz_dr03,"ele_ecalSumEtEg4Hzz_dr03[10]/D");
mytree_->Branch("ele_ecalSumEtoPtEg4Hzz_dr03",ele_ecalSumEtoPtEg4Hzz_dr03,"ele_ecalSumEtoPtEg4Hzz_dr03[10]/D");
mytree_->Branch("ele_hcalSumEtEg4Hzz_dr04",ele_hcalSumEtEg4Hzz_dr04,"ele_hcalSumEtEg4Hzz_dr04[10]/D");
mytree_->Branch("ele_hcalSumEtoPtEg4Hzz_dr04",ele_hcalSumEtoPtEg4Hzz_dr04,"ele_hcalSumEtoPtEg4Hzz_dr04[10]/D");
mytree_->Branch("ele_ambiguousGsfTracks", ele_ambiguousGsfTracks, "ele_ambiguousGsfTracks[10]/I");
mytree_->Branch("ele_ambiguousGsfTracksdxy", ele_ambiguousGsfTracksdxy, "ele_ambiguousGsfTracksdxy[10][5]/D");
mytree_->Branch("ele_ambiguousGsfTracksdz", ele_ambiguousGsfTracksdz, "ele_ambiguousGsfTracksdz[10][5]/D");
mytree_->Branch("ele_ambiguousGsfTracksdxyB",ele_ambiguousGsfTracksdxyB,"ele_ambiguousGsfTracksdxyB[10][5]/D");
mytree_->Branch("ele_ambiguousGsfTracksdzB", ele_ambiguousGsfTracksdzB, "ele_ambiguousGsfTracksdzB[10][5]/D");
mytree_->Branch("ele_seedSubdet1",ele_seedSubdet1,"ele_seedSubdet1[10]/I");
mytree_->Branch("ele_seedDphi1Pos",ele_seedDphi1Pos,"ele_seedDphi1Pos[10]/D");
mytree_->Branch("el_eseedDrz1Pos",ele_seedDrz1Pos,"ele_seedDrz1Pos[10]/D");
mytree_->Branch("ele_seedDphi1Neg",ele_seedDphi1Neg,"ele_seedDphi1Neg[10]/D");
mytree_->Branch("el_eseedDrz1Neg",ele_seedDrz1Neg,"ele_seedDrz1Neg[10]/D");
mytree_->Branch("ele_seedSubdet2",ele_seedSubdet2,"ele_seedSubdet2[10]/I");
mytree_->Branch("ele_seedDphi2Pos",ele_seedDphi2Pos,"ele_seedDphi2Pos[10]/D");
mytree_->Branch("ele_seedDrz2Pos",ele_seedDrz2Pos,"ele_seedDrz2Pos[10]/D");
mytree_->Branch("ele_seedDphi2Neg",ele_seedDphi2Neg,"ele_seedDphi2Neg[10]/D");
mytree_->Branch("ele_seedDrz2Neg",ele_seedDrz2Neg,"ele_seedDrz2Neg[10]/D");
mytree_->Branch("ele_isMCEle",ele_isMCEle,"ele_isMCEle[10]/I");
mytree_->Branch("ele_isMCPhoton",ele_isMCPhoton,"ele_isMCPhoton[10]/I");
mytree_->Branch("ele_isMCHadron",ele_isMCHadron,"ele_isMCHadron[10]/I");
mytree_->Branch("ele_isSIM",ele_isSIM,"ele_isSIM[10]/I");
mytree_->Branch("ele_isSIMEle",ele_isSIMEle,"ele_isSIMEle[10]/I");
mytree_->Branch("ele_idPDGMatch",ele_idPDGMatch,"ele_idPDGMatch[10]/I");
mytree_->Branch("ele_idPDGmother_MCEle",ele_idPDGmother_MCEle,"ele_idPDGmother_MCEle[10]/I");
mytree_->Branch("ele_idPDGMatchSim",ele_idPDGMatchSim,"ele_idPDGMatchSim[10]/I");
mytree_->Branch("ele_nSeed", &ele_nSeed, "ele_nSeed/I");
mytree_->Branch("ele_SeedIsEcalDriven",ele_SeedIsEcalDriven,"ele_SeedIsEcalDriven[100]/I");
mytree_->Branch("ele_SeedIsTrackerDriven",ele_SeedIsTrackerDriven,"ele_SeedIsTrackerDriven[100]/I");
mytree_->Branch("ele_SeedSubdet2",ele_SeedSubdet2,"ele_SeedSubdet2[100]/I");
mytree_->Branch("ele_SeedDphi2Pos",ele_SeedDphi2Pos,"ele_SeedDphi2Pos[100]/D");
mytree_->Branch("ele_SeedDrz2Pos",ele_SeedDrz2Pos,"ele_SeedDrz2Pos[100]/D");
mytree_->Branch("ele_SeedDphi2Neg",ele_SeedDphi2Neg,"ele_SeedDphi2Neg[100]/D");
mytree_->Branch("ele_SeedDrz2Neg",ele_SeedDrz2Neg,"ele_SeedDrz2Neg[100]/D");
mytree_->Branch("ele_SeedSubdet1",ele_SeedSubdet1,"ele_SeedSubdet1[100]/I");
mytree_->Branch("ele_SeedDphi1Pos",ele_SeedDphi1Pos,"ele_SeedDphi1Pos[100]/D");
mytree_->Branch("ele_SeedDrz1Pos",ele_SeedDrz1Pos,"ele_SeedDrz1Pos[100]/D");
mytree_->Branch("ele_SeedDphi1Neg",ele_SeedDphi1Neg,"ele_SeedDphi1Neg[100]/D");
mytree_->Branch("ele_SeedDrz1Neg",ele_SeedDrz1Neg,"ele_SeedDrz1Neg[100]/D");
// For Charge, Clemy's stuff
mytree_->Branch("ele_expected_inner_hits",ele_expected_inner_hits,"ele_expected_inner_hits[10]/I");
//mytree_->Branch("tkIso03Rel",tkIso03Rel,"tkIso03Rel[10]/D");
//mytree_->Branch("ecalIso03Rel",ecalIso03Rel,"ecalIso03Rel[10]/D");
//mytree_->Branch("hcalIso03Rel",hcalIso03Rel,"hcalIso03Rel[10]/D");
mytree_->Branch("ele_sclNclus",ele_sclNclus,"ele_sclNclus[10]/I");
mytree_->Branch("ele_chargeGsfSC",ele_chargeGsfSC,"ele_chargeGsfSC[10]/I");
mytree_->Branch("ele_chargeGsfCtf",ele_chargeGsfCtf,"ele_chargeGsfCtf[10]/I");
mytree_->Branch("ele_chargeGsfCtfSC",ele_chargeGsfCtfSC,"ele_chargeGsfCtfSC[10]/I");
mytree_->Branch("ele_chargeDPhiInnEle",ele_chargeDPhiInnEle,"ele_chargeDPhiInnEle[10]/D");
mytree_->Branch("ele_chargeDPhiInnEleCorr",ele_chargeDPhiInnEleCorr,"ele_chargeDPhiInnEleCorr[10]/D");
mytree_->Branch("ele_chargeQoverPGsfVtx",ele_chargeQoverPGsfVtx,"ele_chargeQoverPGsfVtx[10]/D");
mytree_->Branch("ele_chargeQoverPCtf",ele_chargeQoverPCtf,"ele_chargeQoverPCtf[10]/D");
mytree_->Branch("ele_CtfTrackExists",ele_CtfTrackExists,"ele_CtfTrackExists[10]/I");
// For L1 Trigger, Clemy's stuff
//modif-alex rct region
mytree_->Branch("ele_RCTeta", &_ele_RCTeta, "ele_RCTeta[10]/I");
mytree_->Branch("ele_RCTphi", &_ele_RCTphi, "ele_RCTphi[10]/I");
mytree_->Branch("ele_RCTL1iso", &_ele_RCTL1iso, "ele_RCTL1iso[10]/I");
mytree_->Branch("ele_RCTL1noniso", &_ele_RCTL1noniso, "ele_RCTL1noniso[10]/I");
mytree_->Branch("ele_RCTL1iso_M", &_ele_RCTL1iso_M, "ele_RCTL1iso_M[10]/I");
mytree_->Branch("ele_RCTL1noniso_M", &_ele_RCTL1noniso_M, "ele_RCTL1noniso_M[10]/I");
mytree_->Branch("ele_TTetaVect", &_ele_TTetaVect, "ele_TTetaVect[10][50]/I");
mytree_->Branch("ele_TTphiVect", &_ele_TTphiVect, "ele_TTphiVect[10][50]/I");
mytree_->Branch("ele_TTetVect", &_ele_TTetVect, "ele_TTetVect[10][50]/D");
mytree_->Branch("ele_RCTetaVect", &_ele_RCTetaVect, "ele_RCTetaVect[10][10]/I");
mytree_->Branch("ele_RCTphiVect", &_ele_RCTphiVect, "ele_RCTphiVect[10][10]/I");
mytree_->Branch("ele_RCTetVect", &_ele_RCTetVect, "ele_RCTetVect[10][10]/D");
mytree_->Branch("ele_RCTL1isoVect", &_ele_RCTL1isoVect, "ele_RCTL1isoVect[10][10]/I");
mytree_->Branch("ele_RCTL1nonisoVect",&_ele_RCTL1nonisoVect, "ele_RCTL1nonisoVect[10][10]/I");
mytree_->Branch("ele_RCTL1isoVect_M", &_ele_RCTL1isoVect_M, "ele_RCTL1isoVect_M[10][10]/I");
mytree_->Branch("ele_RCTL1nonisoVect_M",&_ele_RCTL1nonisoVect_M, "ele_RCTL1nonisoVect_M[10][10]/I");
//ele TIP/LIP/IP
mytree_->Branch("ele_Tip",&ele_Tip,"ele_Tip[10]/D");
mytree_->Branch("ele_Lip",&ele_Lip,"ele_Lip[10]/D");
mytree_->Branch("ele_STip",&ele_STip,"ele_STip[10]/D");
mytree_->Branch("ele_SLip",&ele_SLip,"ele_SLip[10]/D");
mytree_->Branch("ele_TipSignif",&ele_TipSignif,"ele_TipSignif[10]/D");
mytree_->Branch("ele_LipSignif",&ele_LipSignif,"ele_LipSignif[10]/D");
mytree_->Branch("ele_Significance3D",&ele_Significance3D,"ele_Significance3D[10]/D");
mytree_->Branch("ele_Value3D",&ele_Value3D,"ele_Value3D[10]/D");
mytree_->Branch("ele_Error3D",&ele_Error3D,"ele_Error3D[10]/D");
// fbrem ECAL
mytree_->Branch("ele_ECAL_fbrem",&ele_ECAL_fbrem,"ele_ECAL_fbrem[10]/D");
mytree_->Branch("ele_PFcomb",&ele_PFcomb,"ele_PFcomb[10]/D");
mytree_->Branch("ele_PFcomb_Err",&ele_PFcomb_Err,"ele_PFcomb_Err[10]/D");
mytree_->Branch("ele_PF_SCenergy",&ele_PF_SCenergy,"ele_PF_SCenergy[10]/D");
mytree_->Branch("ele_PF_SCenergy_Err",&ele_PF_SCenergy_Err,"ele_PF_SCenergy_Err[10]/D");
// ele 4V
m_electrons = new TClonesArray ("TLorentzVector");
mytree_->Branch ("electrons", "TClonesArray", &m_electrons, 256000,0);
// MET
mytree_->Branch("met_calo_et",&_met_calo_et,"met_calo_et/D");
mytree_->Branch("met_calo_px",&_met_calo_px,"met_calo_px/D");
mytree_->Branch("met_calo_py",&_met_calo_py,"met_calo_py/D");
mytree_->Branch("met_calo_phi",&_met_calo_phi,"met_calo_phi/D");
mytree_->Branch("met_calo_set",&_met_calo_set,"met_calo_set/D");
mytree_->Branch("met_calo_sig",&_met_calo_sig,"met_calo_sig/D");
mytree_->Branch("met_calomu_et",&_met_calomu_et,"met_calomu_et/D");
mytree_->Branch("met_calomu_px",&_met_calomu_px,"met_calomu_px/D");
mytree_->Branch("met_calomu_py",&_met_calomu_py,"met_calomu_py/D");
mytree_->Branch("met_calomu_phi",&_met_calomu_phi,"met_calomu_phi/D");
mytree_->Branch("met_calomu_set",&_met_calomu_set,"met_calomu_set/D");
mytree_->Branch("met_calomu_sig",&_met_calomu_sig,"met_calomu_sig/D");
mytree_->Branch("met_tc_et",&_met_tc_et,"met_tc_et/D");
mytree_->Branch("met_tc_px",&_met_tc_px,"met_tc_px/D");
mytree_->Branch("met_tc_py",&_met_tc_py,"met_tc_py/D");
mytree_->Branch("met_tc_phi",&_met_tc_phi,"met_tc_phi/D");
mytree_->Branch("met_tc_set",&_met_tc_set,"met_tc_set/D");
mytree_->Branch("met_tc_sig",&_met_tc_sig,"met_tc_sig/D");
mytree_->Branch("met_pf_et",&_met_pf_et,"met_pf_et/D");
mytree_->Branch("met_pf_px",&_met_pf_px,"met_pf_px/D");
mytree_->Branch("met_pf_py",&_met_pf_py,"met_pf_py/D");
mytree_->Branch("met_pf_phi",&_met_pf_phi,"met_pf_phi/D");
mytree_->Branch("met_pf_set",&_met_pf_set,"met_pf_set/D");
mytree_->Branch("met_pf_sig",&_met_pf_sig,"met_pf_sig/D");
// Muons
mytree_->Branch("muons_N",&_muons_N,"muons_N/I");
m_muons = new TClonesArray ("TLorentzVector");
mytree_->Branch("muons", "TClonesArray", &m_muons, 256000,0);
mytree_->Branch("muons_charge",&_muons_charge,"muons_charge[20]/I");
mytree_->Branch("muons_istracker",&_muons_istracker,"muons_istracker[20]/I");
mytree_->Branch("muons_isstandalone",&_muons_isstandalone,"muons_isstandalone[20]/I");
mytree_->Branch("muons_isglobal",&_muons_isglobal,"muons_isglobal[20]/I");
//
mytree_->Branch("muons_dxy",&_muons_dxy,"muons_dxy[20]/D");
mytree_->Branch("muons_dz",&_muons_dz,"muons_dz[20]/D");
mytree_->Branch("muons_dxyPV",&_muons_dxyPV,"muons_dxyPV[20]/D");
mytree_->Branch("muons_dzPV",&_muons_dzPV,"muons_dzPV[20]/D");
mytree_->Branch("muons_normalizedChi2",&_muons_normalizedChi2,"muons_normalizedChi2[20]/D");
mytree_->Branch("muons_NtrackerHits",&_muons_NtrackerHits,"muons_NtrackerHits[20]/I");
mytree_->Branch("muons_NpixelHits",&_muons_NpixelHits,"muons_NpixelHits[20]/I");
mytree_->Branch("muons_NmuonHits",&_muons_NmuonHits,"muons_NmuonHits[20]/I");
mytree_->Branch("muons_Nmatches",&_muons_Nmatches,"muons_Nmatches[20]/I");
//
mytree_->Branch("muons_nTkIsoR03",&_muons_nTkIsoR03,"muons_nTkIsoR03[20]/I");
mytree_->Branch("muons_nTkIsoR05",&_muons_nTkIsoR05,"muons_nTkIsoR05[20]/I");
mytree_->Branch("muons_tkIsoR03",&_muons_tkIsoR03,"muons_tkIsoR03[20]/D");
mytree_->Branch("muons_tkIsoR05",&_muons_tkIsoR05,"muons_tkIsoR05[20]/D");
mytree_->Branch("muons_emIsoR03",&_muons_emIsoR03,"muons_emIsoR03[20]/D");
mytree_->Branch("muons_emIsoR05",&_muons_emIsoR05,"muons_emIsoR05[20]/D");
mytree_->Branch("muons_hadIsoR03",&_muons_hadIsoR03,"muons_hadIsoR03[20]/D");
mytree_->Branch("muons_hadIsoR05",&_muons_hadIsoR05,"muons_hadIsoR05[20]/D");
//muons TIP/LIP/IP
mytree_->Branch("muons_Tip",&muons_Tip,"muons_Tip[20]/D");
mytree_->Branch("muons_Lip",&muons_Lip,"muons_Lip[20]/D");
mytree_->Branch("muons_STip",&muons_STip,"muons_STip[20]/D");
mytree_->Branch("muons_SLip",&muons_SLip,"muons_SLip[20]/D");
mytree_->Branch("muons_TipSignif",&muons_TipSignif,"muons_TipSignif[20]/D");
mytree_->Branch("muons_LipSignif",&muons_LipSignif,"muons_LipSignif[20]/D");
mytree_->Branch("muons_Significance3D",&muons_Significance3D,"muons_Significance3D[20]/D");
mytree_->Branch("muons_Value3D",&muons_Value3D,"muons_Value3D[20]/D");
mytree_->Branch("muons_Error3D",&muons_Error3D,"muons_Error3D[20]/D");
//muonID variables for HZZ
mytree_->Branch("muons_trkDxy",&_muons_trkDxy,"muons_trkDxy[20]/D");
mytree_->Branch("muons_trkDxyError",&_muons_trkDxyError,"muons_trkDxyError[20]/D");
mytree_->Branch("muons_trkDxyB",&_muons_trkDxyB,"muons_trkDxyB[20]/D");
mytree_->Branch("muons_trkDz",&_muons_trkDz,"muons_trkDz[20]/D");
mytree_->Branch("muons_trkDzError",&_muons_trkDzError,"muons_trkDzError[20]/D");
mytree_->Branch("muons_trkDzB",&_muons_trkDzB,"muons_trkDzB[20]/D");
mytree_->Branch("muons_trkChi2PerNdof",&_muons_trkChi2PerNdof,"muons_trkChi2PerNdof[20]/D");
mytree_->Branch("muons_trkCharge",&_muons_trkCharge,"muons_trkCharge[20]/D");
mytree_->Branch("muons_trkNHits",&_muons_trkNHits,"muons_trkNHits[20]/D");
mytree_->Branch("muons_trkNPixHits",&_muons_trkNPixHits,"muons_trkNPixHits[20]/D");
mytree_->Branch("muons_trkmuArbitration",&_muons_trkmuArbitration,"muons_trkmuArbitration[20]/D");
mytree_->Branch("muons_trkmu2DCompatibilityLoose",&_muons_trkmu2DCompatibilityLoose,"muons_trkmu2DCompatibilityLoose[20]/D");
mytree_->Branch("muons_trkmu2DCompatibilityTight",&_muons_trkmu2DCompatibilityTight,"muons_trkmu2DCompatibilityTight[20]/D");
mytree_->Branch("muons_trkmuOneStationLoose",&_muons_trkmuOneStationLoose,"muons_trkmuOneStationLoose[20]/D");
mytree_->Branch("muons_trkmuOneStationTight",&_muons_trkmuOneStationTight,"muons_trkmuOneStationTight[20]/D");
mytree_->Branch("muons_trkmuLastStationLoose",&_muons_trkmuLastStationLoose,"muons_trkmuLastStationLoose[20]/D");
mytree_->Branch("muons_trkmuLastStationTight",&_muons_trkmuLastStationTight,"muons_trkmuLastStationTight[20]/D");
mytree_->Branch("muons_trkmuOneStationAngLoose",&_muons_trkmuOneStationAngLoose,"muons_trkmuOneStationAngLoose[20]/D");
mytree_->Branch("muons_trkmuOneStationAngTight",&_muons_trkmuOneStationAngTight,"muons_trkmuOneStationAngTight[20]/D");
mytree_->Branch("muons_trkmuLastStationAngLoose",&_muons_trkmuLastStationAngLoose,"muons_trkmuLastStationAngLoose[20]/D");
mytree_->Branch("muons_trkmuLastStationAngTight",&_muons_trkmuLastStationAngTight,"muons_trkmuLastStationAngTight[20]/D");
mytree_->Branch("muons_trkmuLastStationOptimizedLowPtLoose",&_muons_trkmuLastStationOptimizedLowPtLoose,"muons_trkmuLastStationOptimizedLowPtLoose[20]/D");
mytree_->Branch("muons_trkmuLastStationOptimizedLowPtTight",&_muons_trkmuLastStationOptimizedLowPtTight,"muons_trkmuLastStationOptimizedLowPtTight[20]/D");
mytree_->Branch("muons_caloCompatibility",&_muons_caloCompatibility,"muons_caloCompatibility[20]/D");
mytree_->Branch("muons_segmentCompatibility",&_muons_segmentCompatibility,"muons_segmentCompatibility[20]/D");
mytree_->Branch("muons_glbmuPromptTight",&_muons_glbmuPromptTight,"muons_glbmuPromptTight[20]/D");
mytree_->Branch("muons_hzzIso",&_muons_hzzIso,"muons_hzzIso[20]/D");
mytree_->Branch("muons_hzzIsoTk",&_muons_hzzIsoTk,"muons_hzzIsoTk[20]/D");
mytree_->Branch("muons_hzzIsoEcal",&_muons_hzzIsoEcal,"muons_hzzIsoEcal[20]/D");
mytree_->Branch("muons_hzzIsoHcal",&_muons_hzzIsoHcal,"muons_hzzIsoHcal[20]/D");
// Calo Jets
_m_jets_calo = new TClonesArray ("TLorentzVector");
mytree_->Branch("jets_calo_N",&_jets_calo_N,"jets_calo_N/I");
mytree_->Branch("jets_calo", "TClonesArray", &_m_jets_calo, 256000,0);
// JPT jets
_m_jets_jpt = new TClonesArray ("TLorentzVector");
mytree_->Branch("jets_jpt_N", &_jets_jpt_N, "jets_jpt_N/I");
mytree_->Branch("jets_jpt", "TClonesArray", &_m_jets_jpt, 256000,0);
// PF jets
_m_jets_pf = new TClonesArray ("TLorentzVector");
mytree_->Branch("jets_pf_N", &_jets_pf_N, "jets_pf_N/I");
mytree_->Branch ("jets_pf", "TClonesArray", &_m_jets_pf, 256000,0);
mytree_->Branch ("jets_pf_chargedHadEFrac", &jets_pf_chargedHadEFrac,"jets_pf_chargedHadEFrac[100]/D]");
mytree_->Branch ("jets_pf_chargedEmEFrac", &jets_pf_chargedEmEFrac, "jets_pf_chargedEmEFrac[100]/D");
mytree_->Branch ("jets_pf_chargedMuEFrac", &jets_pf_chargedMuEFrac, "jets_pf_chargedMuEFrac[100]/D");
mytree_->Branch ("jets_pf_neutralHadEFrac", &jets_pf_neutralHadEFrac, "jets_pf_neutralHadEFrac[100]/D");
mytree_->Branch ("jets_pf_neutralEmEFrac", &jets_pf_neutralEmEFrac, "jets_pf_neutralEmEFrac[100]/D");
mytree_->Branch ("jets_pf_PhotonEFrac", &jets_pf_PhotonEFrac, "jets_pf_PhotonEFrac[100]/D");
mytree_->Branch ("jets_pf_chargedHadMultiplicity", &jets_pf_chargedHadMultiplicity, "jets_pf_chargedHadMultiplicity[100]/I");
mytree_->Branch ("jets_pf_neutralHadMultiplicity", &jets_pf_neutralHadMultiplicity, "jets_pf_neutralHadMultiplicity[100]/I");
mytree_->Branch ("jets_pf_chargedMultiplicity", &jets_pf_chargedMultiplicity, "jets_pf_chargedMultiplicity[100]/I");
mytree_->Branch ("jets_pf_neutralMultiplicity", &jets_pf_neutralMultiplicity, "jets_pf_neutralMultiplicity[100]/I");
mytree_->Branch ("jets_pf_nConstituents", &jets_pf_nConstituents, "jets_pf_nConstituents[100]/I");
// SuperClusters
// SC EB
mytree_->Branch("sc_hybrid_N", &_sc_hybrid_N, "sc_hybrid_N/I");
mytree_->Branch("sc_hybrid_E", &_sc_hybrid_E, "sc_hybrid_E[25]/D");
mytree_->Branch("sc_hybrid_Et", &_sc_hybrid_Et, "sc_hybrid_Et[25]/D");
mytree_->Branch("sc_hybrid_Eta", &_sc_hybrid_Eta, "sc_hybrid_Eta[25]/D");
mytree_->Branch("sc_hybrid_Phi", &_sc_hybrid_Phi, "sc_hybrid_Phi[25]/D");
mytree_->Branch("sc_hybrid_outOfTimeSeed", &_sc_hybrid_outOfTimeSeed, "sc_hybrid_outOfTimeSeed[25]/I");
mytree_->Branch("sc_hybrid_severityLevelSeed", &_sc_hybrid_severityLevelSeed, "sc_hybrid_severityLevelSeed[25]/I");
mytree_->Branch("sc_hybrid_e1", &_sc_hybrid_e1, "sc_hybrid_e1[25]/D");
mytree_->Branch("sc_hybrid_e33", &_sc_hybrid_e33, "sc_hybrid_e33[25]/D");
mytree_->Branch("sc_hybrid_he",&_sc_hybrid_he, "sc_hybrid_he[25]/D");
mytree_->Branch("sc_hybrid_sigmaietaieta",&_sc_hybrid_sigmaietaieta, "sc_hybrid_sigmaietaieta[25]/D");
mytree_->Branch("sc_hybrid_hcalDepth1TowerSumEt_dr03", &_sc_hybrid_hcalDepth1TowerSumEt_dr03, "sc_hybrid_hcalDepth1TowerSumEt_dr03[25]/D");
mytree_->Branch("sc_hybrid_hcalDepth2TowerSumEt_dr03", &_sc_hybrid_hcalDepth2TowerSumEt_dr03, "sc_hybrid_hcalDepth2TowerSumEt_dr03[25]/D");
mytree_->Branch("sc_hybrid_ecalRecHitSumEt_dr03", &_sc_hybrid_ecalRecHitSumEt_dr03, "sc_hybrid_ecalRecHitSumEt_dr03[25]/D");
mytree_->Branch("sc_hybrid_trkiso_dr03", &_sc_hybrid_trkiso_dr03, "sc_hybrid_trkiso_dr03[25]/D");
// SC EB : L1 stuff
mytree_->Branch("sc_hybrid_TTetaVect", &_sc_hybrid_TTetaVect, "_sc_hybrid_TTetaVect[25][50]/I");
mytree_->Branch("sc_hybrid_TTphiVect", &_sc_hybrid_TTphiVect, "_sc_hybrid_TTphiVect[25][50]/I");
mytree_->Branch("sc_hybrid_TTetVect", &_sc_hybrid_TTetVect, "_sc_hybrid_TTetVect[25][50]/D");
mytree_->Branch("sc_hybrid_RCTetaVect", &_sc_hybrid_RCTetaVect, "_sc_hybrid_RCTetaVect[25][10]/I");
mytree_->Branch("sc_hybrid_RCTphiVect", &_sc_hybrid_RCTphiVect, "_sc_hybrid_RCTphiVect[25][10]/I");
mytree_->Branch("sc_hybrid_RCTetVect", &_sc_hybrid_RCTetVect, "_sc_hybrid_RCTetVect[25][10]/D");
mytree_->Branch("sc_hybrid_RCTL1isoVect", &_sc_hybrid_RCTL1isoVect, "_sc_hybrid_RCTL1isoVect[25][10]/I");
mytree_->Branch("sc_hybrid_RCTL1nonisoVect", &_sc_hybrid_RCTL1nonisoVect, "_sc_hybrid_RCTL1nonisoVect[25][10]/I");
//
mytree_->Branch("sc_hybrid_RCTeta", &_sc_hybrid_RCTeta, "_sc_hybrid_RCTeta[25]/I");
mytree_->Branch("sc_hybrid_RCTphi", &_sc_hybrid_RCTphi, "_sc_hybrid_RCTphi[25]/I");
mytree_->Branch("sc_hybrid_RCTL1iso", &_sc_hybrid_RCTL1iso, "_sc_hybrid_RCTL1iso[25]/I");
mytree_->Branch("sc_hybrid_RCTL1noniso", &_sc_hybrid_RCTL1noniso, "_sc_hybrid_RCTL1noniso[25]/I");
// SC EE
mytree_->Branch("sc_multi55_N", &_sc_multi55_N, "sc_multi55_N/I");
mytree_->Branch("sc_multi55_E", &_sc_multi55_E, "sc_multi55_E[25]/D");
mytree_->Branch("sc_multi55_Et", &_sc_multi55_Et, "sc_multi55_Et[25]/D");
mytree_->Branch("sc_multi55_Eta", &_sc_multi55_Eta, "sc_multi55_Eta[25]/D");
mytree_->Branch("sc_multi55_Phi", &_sc_multi55_Phi, "sc_multi55_Phi[25]/D");
mytree_->Branch("sc_multi55_he", &_sc_multi55_he, "sc_multi55_he[25]/D");
mytree_->Branch("sc_multi55_sigmaietaieta",&_sc_multi55_sigmaietaieta, "sc_multi55_sigmaietaieta[25]/D");
mytree_->Branch("sc_multi55_hcalDepth1TowerSumEt_dr03", &_sc_multi55_hcalDepth1TowerSumEt_dr03, "sc_multi55_hcalDepth1TowerSumEt_dr03[25]/D");
mytree_->Branch("sc_multi55_hcalDepth2TowerSumEt_dr03", &_sc_multi55_hcalDepth2TowerSumEt_dr03, "sc_multi55_hcalDepth2TowerSumEt_dr03[25]/D");
mytree_->Branch("sc_multi55_ecalRecHitSumEt_dr03", &_sc_multi55_ecalRecHitSumEt_dr03, "sc_multi55_ecalRecHitSumEt_dr03[25]/D");
mytree_->Branch("sc_multi55_trkiso_dr03", &_sc_multi55_trkiso_dr03, "sc_multi55_trkiso_dr03[25]/D");
// SC EE : L1 stuff
mytree_->Branch("sc_multi55_TTetaVect", &_sc_multi55_TTetaVect, "_sc_multi55_TTetaVect[25][50]/I");
mytree_->Branch("sc_multi55_TTphiVect", &_sc_multi55_TTphiVect, "_sc_multi55_TTphiVect[25][50]/I");
mytree_->Branch("sc_multi55_TTetVect", &_sc_multi55_TTetVect, "_sc_multi55_TTetVect[25][50]/D");
mytree_->Branch("sc_multi55_RCTetaVect", &_sc_multi55_RCTetaVect, "_sc_multi55_RCTetaVect[25][10]/I");
mytree_->Branch("sc_multi55_RCTphiVect", &_sc_multi55_RCTphiVect, "_sc_multi55_RCTphiVect[25][10]/I");
mytree_->Branch("sc_multi55_RCTetVect", &_sc_multi55_RCTetVect, "_sc_multi55_RCTetVect[25][10]/D");
mytree_->Branch("sc_multi55_RCTL1isoVect", &_sc_multi55_RCTL1isoVect, "_sc_multi55_RCTL1isoVect[25][10]/I");
mytree_->Branch("sc_multi55_RCTL1nonisoVect", &_sc_multi55_RCTL1nonisoVect, "_sc_multi55_RCTL1nonisoVect[25][10]/I");
//
mytree_->Branch("sc_multi55_RCTeta", &_sc_multi55_RCTeta, "_sc_multi55_RCTeta[25]/I");
mytree_->Branch("sc_multi55_RCTphi", &_sc_multi55_RCTphi, "_sc_multi55_RCTphi[25]/I");
mytree_->Branch("sc_multi55_RCTL1iso", &_sc_multi55_RCTL1iso, "_sc_multi55_RCTL1iso[25]/I");
mytree_->Branch("sc_multi55_RCTL1noniso", &_sc_multi55_RCTL1noniso, "_sc_multi55_RCTL1noniso[25]/I");
// Generated W,Z's & leptons
_m_MC_gen_V = new TClonesArray ("TLorentzVector");
mytree_->Branch ("MC_gen_V", "TClonesArray", &_m_MC_gen_V, 256000,0);
mytree_->Branch ("MC_gen_V_pdgid",&_MC_gen_V_pdgid, "MC_gen_V_pdgid[10]/D");
_m_MC_gen_leptons = new TClonesArray ("TLorentzVector");
mytree_->Branch ("MC_gen_leptons", "TClonesArray", &_m_MC_gen_leptons, 256000,0);
mytree_->Branch ("MC_gen_leptons_pdgid",&_MC_gen_leptons_pdgid, "MC_gen_leptons_pdgid[10]/D");
}
// ====================================================================================
SimpleNtpleCustom::~SimpleNtpleCustom()
// ====================================================================================
{
delete m_electrons ;
delete m_muons;
delete _m_jets_calo;
delete _m_jets_jpt;
delete _m_jets_pf;
if(type_ == "MC") {
delete _m_MC_gen_V;
delete _m_MC_gen_leptons;
} // if MC
}
// ====================================================================================
void SimpleNtpleCustom::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup)
// ====================================================================================
{
// Clemy's Stuff for Charge
bool updateField(false);
if (cacheIDMagField_!=iSetup.get<IdealMagneticFieldRecord>().cacheIdentifier()){
updateField = true;
cacheIDMagField_=iSetup.get<IdealMagneticFieldRecord>().cacheIdentifier();
iSetup.get<IdealMagneticFieldRecord>().get(theMagField);
}
bool updateGeometry(false);
if (cacheIDTDGeom_!=iSetup.get<TrackerDigiGeometryRecord>().cacheIdentifier()){
updateGeometry = true;
cacheIDTDGeom_=iSetup.get<TrackerDigiGeometryRecord>().cacheIdentifier();
iSetup.get<TrackerDigiGeometryRecord>().get(trackerHandle_);
}
if(updateField || updateGeometry){
mtsTransform_ = new MultiTrajectoryStateTransform(trackerHandle_.product(),theMagField.product());
}
// if (cacheIDTopo_!=iSetup.get<CaloTopologyRecord>().cacheIdentifier()){
// cacheIDTopo_=iSetup.get<CaloTopologyRecord>().cacheIdentifier();
// iSetup.get<CaloTopologyRecord>().get(theCaloTopo);
// }
// Tree Maker
//std::cout << "Init()" << std::endl;
Init();
if (funcbase_) funcbase_->init(iSetup);
//std::cout << "FillEvent (iEvent, iSetup);" << std::endl;
FillEvent (iEvent, iSetup);
// for Skimming
AnalysisUtils * skim = new AnalysisUtils();
_skim_is1lepton = skim->doSkim(iEvent, iSetup, true, true, 20., 20., 1, 1);
_skim_is2leptons = skim->doSkim(iEvent, iSetup, false, false, 10., 15., 2, 1);
_skim_is3leptons = skim->doSkim(iEvent, iSetup, false, false, 5., 10., 3, 2);
//bool isEleID_, bool isMuonID_, double lep_ptLow_, double lep_ptHigh_, int nLep_ptLow_, int nLep_ptHigh_);
//
FillTrigger (iEvent, iSetup);
//std::cout << "m_electrons -> Clear() ;" << std::endl;
m_electrons -> Clear() ;
//std::cout << "muons" << std::endl;
m_muons -> Clear() ;
//std::cout << "gen V" << std::endl;
if(type_ == "MC") {
_m_MC_gen_V->Clear();
//cout << "gen leptons" << endl;
_m_MC_gen_leptons->Clear();
} // if MC
if(PrintDebug_) std::cout << "FillEle (iEvent, iSetup);" << std::endl;
FillEle (iEvent, iSetup);
//
//std::cout << "FillMuon (iEvent, iSetup);" << std::endl;
//FillMuons (iEvent, iSetup);
//std::cout << "FillMET (iEvent, iSetup);" << std::endl;
//FillMET (iEvent, iSetup);
//std::cout << "FillJets(iEvent, iSetup);" << std::endl;
//FillJets(iEvent, iSetup);
//std::cout << "if(fillsc_) FillSuperClusters(iEvent, iSetup);" << std::endl;
//if(fillsc_) FillSuperClusters(iEvent, iSetup);
//std::cout << "FillTruth(iEvent, iSetup);" << std::endl;
//if(type_ == "MC") FillTruth(iEvent, iSetup);
//std::cout << "FillTipLipIp(iEvent, iSetup);" << std::endl;
//if(!aod_)
//FillTipLipIp(iEvent, iSetup);
//std::cout << "mytree_->Fill();" << std::endl;
mytree_->Fill();
} // analyze
// ====================================================================================
void SimpleNtpleCustom::FillEvent (const edm::Event& iEvent, const edm::EventSetup& iSetup)
// ====================================================================================
{
nEvent = iEvent.id().event();
nRun = iEvent.id().run();
nLumi = iEvent.luminosityBlock();
cout<<"test"<<endl;
// -----------------
// Pile-up
// -----------------
if(type_ == "MC") {
Handle<vector<PileupSummaryInfo> > PupInfo;
iEvent.getByLabel(PileupSrc_, PupInfo);
for (vector<PileupSummaryInfo>::const_iterator cand = PupInfo->begin();cand != PupInfo->end(); ++ cand) {
_PU_N = cand->getPU_NumInteractions();
//cout << " PU = "<< _PU_N << endl;
} // loop on Pile up
} // if MC
// Rho/FastJet Correction
Handle<double> rhoHandle, sigmaHandle;
iEvent.getByLabel(RhoCorrection_, rhoHandle);
iEvent.getByLabel(SigmaRhoCorrection_, sigmaHandle);
_PU_rho = *rhoHandle;
_PU_sigma = *sigmaHandle;
// cout << "Rho, Sigma: " << _rho << " " << _sigma << endl;
// -----------------
// Vertices
// -----------------
Handle<reco::VertexCollection> recoPrimaryVertexCollection;
iEvent.getByLabel(VerticesTag_,recoPrimaryVertexCollection);
edm::Handle<reco::BeamSpot> recoBeamSpotHandle;
///iEvent.getByType(recoBeamSpotHandle);
const reco::BeamSpot bs = *recoBeamSpotHandle;
int vtx_counter=0;
_vtx_N = recoPrimaryVertexCollection->size();
// select the primary vertex as the one with higest sum of (pt)^2 of tracks
PrimaryVertexSorter PVSorter;
std::vector<reco::Vertex> sortedVertices = PVSorter.sortedList( *(recoPrimaryVertexCollection.product()) );
if(_vtx_N > 0) {
GlobalPoint local_vertexPosition(sortedVertices.front().position().x(),
sortedVertices.front().position().y(),
sortedVertices.front().position().z());
vertexPosition = local_vertexPosition;
}
else {
GlobalPoint local_vertexPosition(bs.position().x(),
bs.position().y(),
bs.position().z());
vertexPosition = local_vertexPosition;
}
for( std::vector<reco::Vertex>::const_iterator PV = sortedVertices.begin(); PV != sortedVertices.end(); ++PV){
if(vtx_counter > 14 ) continue;
_vtx_normalizedChi2[vtx_counter] = PV->normalizedChi2();
_vtx_ndof[vtx_counter] = PV->ndof();
_vtx_nTracks[vtx_counter] = PV->tracksSize();
_vtx_d0[vtx_counter] = PV->position().Rho();
_vtx_x[vtx_counter] = PV->x();
_vtx_y[vtx_counter] = PV->y();
_vtx_z[vtx_counter] = PV->z();
vtx_counter++;
} // for loop on primary vertices
if(vtx_counter>14) { _vtx_N = 15; cout << "Number of primary vertices>15, vtx_N set to 15" << endl;}
}
// ====================================================================================
void SimpleNtpleCustom::FillTrigger (const edm::Event& iEvent, const edm::EventSetup& iSetup)
// ====================================================================================
{
// ----------------------------------------------
// Get HLT info
// ----------------------------------------------
// Get HLTTag when running
//Handle<trigger::TriggerEvent> triggerEventHLT;
//iEvent.getByLabel("hltTriggerSummaryAOD", triggerEventHLT);
//cout << " HLT = " << triggerEventHLT.provenance()->processName() << endl;
edm::Handle<edm::TriggerResults> triggerResultsHandle;
iEvent.getByLabel (HLTTag_,triggerResultsHandle);
const edm::TriggerNames & triggerNames = iEvent.triggerNames(*triggerResultsHandle);
// Get List of available Triggers
//for (int in=0;in<(int)triggerNames.size();in++) {
//cout << " Trigger Names " << in << " = " << triggerNames.triggerName(in) << endl;
//} // for loop in triggernames
trig_isUnbiased = 0 ;
// LOOP Over Trigger Results
strcpy(trig_fired_names,"*");
for (int iHLT=0; iHLT<static_cast<int>(triggerResultsHandle->size()); iHLT++) {
if (triggerResultsHandle->accept (iHLT)) {
trig_hltInfo[iHLT] = 1;
if ( strlen(trig_fired_names) <= 4950) {
const char* c_str();
string hlt_string = triggerNames.triggerName(iHLT);
strcat(trig_fired_names,hlt_string.c_str());
strcat(trig_fired_names,"*");
}
}
else {
trig_hltInfo[iHLT] = 0;
}
if(string(triggerNames.triggerName(iHLT)).find("HLT_Activity_Ecal_SC")!= std::string::npos) {
if (triggerResultsHandle->accept (iHLT)) trig_isUnbiased = 1 ;
}
if (triggerNames.triggerName(iHLT) == "HLT_L1SingleEG2" ) {
if (triggerResultsHandle->accept (iHLT))
trig_isL1SingleEG2 = 1 ;
else
trig_isL1SingleEG2 = 0 ;
}
if (triggerNames.triggerName(iHLT) == "HLT_L1SingleEG5" ) {
if (triggerResultsHandle->accept (iHLT))
trig_isL1SingleEG5 = 1 ;
else
trig_isL1SingleEG5 = 0 ;
}
if (triggerNames.triggerName(iHLT) == "HLT_L1SingleEG8" ) {
if (triggerResultsHandle->accept (iHLT))
trig_isL1SingleEG8 = 1 ;
else
trig_isL1SingleEG8 = 0 ;
}
if (triggerNames.triggerName(iHLT) == "HLT_Photon10_L1R" ) {
if (triggerResultsHandle->accept (iHLT))
trig_isPhoton10 = 1 ;
else
trig_isPhoton10 = 0 ;
}
if (triggerNames.triggerName(iHLT) == "HLT_Photon15_L1R" ) {
if (triggerResultsHandle->accept (iHLT))
trig_isPhoton15 = 1 ;
else
trig_isPhoton15 = 0 ;
}
if (triggerNames.triggerName(iHLT) == "HLT_Ele10_LW_L1R" ) {
if (triggerResultsHandle->accept (iHLT))
trig_isEle10_LW = 1 ;
else
trig_isEle10_LW = 0 ;
}
if (triggerNames.triggerName(iHLT) == "HLT_Ele15_LW_L1R" ) {
if (triggerResultsHandle->accept (iHLT))
trig_isEle15_LW = 1 ;
else
trig_isEle15_LW = 0 ;
} // if HLT Ele
} // for loop on trigger results
///////////////////////////
// Get TP data (Nadir) //
///////////////////////////
// commented to treat non modif reco SingleElectron dataset
// bool PrintDebug_ = true;
// if(PrintDebug_) std::cout << "" << endl;
// ORIGINAL TP
if( nadGetTP_ ) {
if(PrintDebug_) cout << "create new ecal_tp pointer" << endl;
//edm::Handle<EcalTrigPrimDigiCollection> tp;
edm::Handle<EcalTrigPrimDigiCollection>* ecal_tp_ = new edm::Handle<EcalTrigPrimDigiCollection> ;
if(PrintDebug_) cout << "..created. get by label the tp collection" << endl;
iEvent.getByLabel(tpCollectionNormal_,*ecal_tp_);
if(PrintDebug_) cout << "got it" << endl;
_trig_tower_N = ecal_tp_->product()->size();
if(PrintDebug_) {
cout << "TP Normal collection size=" << ecal_tp_->product()->size() << endl ;
cout << "is gonna get the TP data" << endl;
}
for (int i=0 ; i<_trig_tower_N ; i++) {
if(PrintDebug_) cout << "loop iteration #" << i << endl;
EcalTriggerPrimitiveDigi d_ = (*(ecal_tp_->product()))[i]; // EcalTriggerPrimitiveDigi d
if(PrintDebug_) cout << "got the trigger primitive" << endl;
EcalTrigTowerDetId TPtowid_ = d_.id(); // const EcalTrigTowerDetId TPtowid
if(PrintDebug_) cout << "got the tower id" << endl;
_trig_tower_iphi[i] = TPtowid_.iphi() ;
_trig_tower_ieta[i] = TPtowid_.ieta() ;
if(PrintDebug_) cout << "got the ieta and iphi : " << TPtowid_.ieta() << TPtowid_.iphi() << endl;
//_trig_tower_adc[i] = (d[0].raw()&0xfff) ; 0xfff <-> TTF(3bits)+FG(1bit)+Et(8bits)
_trig_tower_adc[i] = (d_[0].raw()&0xff) ; // 0xff <-> Et(8bits)
if(PrintDebug_) cout << "got the adc : " << (int)(d_[0].raw()&0xff) << endl;
//if(_trig_tower_adc[i]>0)
//cout << _trig_tower_adc[i] << " " ;
_trig_tower_sFGVB[i] = d_[0].sFGVB(); // 0=spike-like / 1=EM-like
if(PrintDebug_) cout << "got the sFGVB : " << d_[0].sFGVB() << endl;
//_trig_tower_sFGVB[i] = d[0].l1aSpike();
//if(d[0].l1aSpike()!=0) cout << "sFGVB=" << d[0].l1aSpike() << endl;
}
if(PrintDebug_) cout << "finished looping" << endl;
}
// ZEROING-BY-HAND TP
if( nadGetTP_Modif_ ) {
edm::Handle<EcalTrigPrimDigiCollection>* ecal_tpM_ = new edm::Handle<EcalTrigPrimDigiCollection> ;
iEvent.getByLabel(tpCollectionModif_,*ecal_tpM_);
//std::cout << "TP Modif collection size=" << tpM.product()->size() << std::endl ;
_trig_tower_N_modif = ecal_tpM_->product()->size();
for (int i=0 ; i<_trig_tower_N_modif ; i++) {
EcalTriggerPrimitiveDigi dM_ = (*(ecal_tpM_->product()))[i]; // EcalTriggerPrimitiveDigi dM
EcalTrigTowerDetId TPtowidM_ = dM_.id(); // EcalTrigTowerDetId
_trig_tower_iphi_modif[i] = TPtowidM_.iphi() ;
_trig_tower_ieta_modif[i] = TPtowidM_.ieta() ;
//_trig_tower_adc_modif[i] = (dM[0].raw()&0xfff) ;
_trig_tower_adc_modif[i] = (dM_[0].raw()&0xff) ;
//if(_trig_tower_adc_modif[i]>0)
//cout << _trig_tower_adc_modif[i] << " " ;
_trig_tower_sFGVB_modif[i] = dM_[0].sFGVB(); // 0=spike-like / 1=EM-like
//_trig_tower_sFGVB_modif[i] = dM[0].l1aSpike();
}
}
// EMULATOR TPs
if( nadGetTP_Emul_ ) {
edm::Handle<EcalTrigPrimDigiCollection>* ecal_tpM_ = new edm::Handle<EcalTrigPrimDigiCollection> ;
iEvent.getByLabel(tpEmulatorCollection_, *ecal_tpM_);
//if (print_) std::cout<<"TPEmulator collection size="<<tpEmul.product()->size()<<std::endl ;
_trig_tower_N_emul = ecal_tpM_->product()->size();
for (int i=0 ; i<_trig_tower_N_emul ; i++) {
EcalTriggerPrimitiveDigi dM_ = (*(ecal_tpM_->product()))[i]; //EcalTriggerPrimitiveDigi
EcalTrigTowerDetId TPtowidM_ = dM_.id();
_trig_tower_iphi_emul[i] = TPtowidM_.iphi() ;
_trig_tower_ieta_emul[i] = TPtowidM_.ieta() ;
bool showit = false;
for(int j=0 ; j<5 ; j++)
if( (dM_[j].raw()&0xff) > 0 ) showit = true ;
showit = false;
if(showit)
cout << "TTieta=" << TPtowidM_.ieta() << " TTiphi=" << TPtowidM_.iphi() << " adcEm=" ;
for (int j=0 ; j<5 ; j++) {
_trig_tower_adc_emul[i][j] = (dM_[j].raw()&0xff) ;
//_trig_tower_sFGVB_emul[i][j] = d[j].l1aSpike();
_trig_tower_sFGVB_emul[i][j] = dM_[j].sFGVB();
if(showit)
cout << (dM_[j].raw()&0xff) << " " ;
}
if(showit)
cout << endl;
}
}
// ----------------------------------
// Path from list given in .py file
// ----------------------------------
UInt_t trigger_size = triggerResultsHandle->size();
int passEleTrigger = 0;
int passMuonTrigger = 0;
// Electron Triggers
for(int ipath=0;ipath< (int) HLT_ElePaths_.size();ipath++) {
//cout << " i = " << ipath << " trigger = " << HLT_Paths_[ipath] << endl;
UInt_t trigger_position = triggerNames.triggerIndex(HLT_ElePaths_[ipath]); //hltpath_);
if (trigger_position < trigger_size) passEleTrigger = (int)triggerResultsHandle->accept(trigger_position);
if (passEleTrigger==1) _trig_isEleHLTpath = 1;
} // for loop on HLT Elepaths
// Muon Triggers
for(int ipath=0;ipath< (int) HLT_MuonPaths_.size();ipath++) {
//cout << " i = " << ipath << " trigger = " << HLT_Paths_[ipath] << endl;
UInt_t trigger_position = triggerNames.triggerIndex(HLT_MuonPaths_[ipath]); //hltpath_);
if (trigger_position < trigger_size) passMuonTrigger = (int)triggerResultsHandle->accept(trigger_position);
if (passMuonTrigger==1) _trig_isMuonHLTpath = 1;
} // for loop on HLT Muonpaths
if(!aod_) {
// ----------------------
// get L1 EM candidate
// ----------------------
// --- CURRENT BUNCH CROSSING --- //////////////////////////////////////////////////////////////////
edm::Handle< l1extra::L1EmParticleCollection > emNonisolColl ;
edm::Handle< l1extra::L1EmParticleCollection > emIsolColl ;
edm::Handle< l1extra::L1EmParticleCollection > emNonisolColl_M ;
edm::Handle< l1extra::L1EmParticleCollection > emIsolColl_M ;
if( !nadGetL1M_ ) {
// standard collection ALONE
iEvent.getByLabel("l1extraParticles","NonIsolated", emNonisolColl ) ;
iEvent.getByLabel("l1extraParticles","Isolated", emIsolColl ) ;
} else {
// standard collection
iEvent.getByLabel("l1extraParticlesOnline","NonIsolated", emNonisolColl ) ;
iEvent.getByLabel("l1extraParticlesOnline","Isolated", emIsolColl ) ;
// modified collection
iEvent.getByLabel("l1extraParticles","NonIsolated", emNonisolColl_M ) ;
iEvent.getByLabel("l1extraParticles","Isolated", emIsolColl_M ) ;
}
///// STANDARD COLLECTION ALONE
// Isolated candidates
_trig_L1emIso_N = emIsolColl->size();
if(PrintDebug_) cout << "N L1 candidate iso : " << _trig_L1emIso_N << endl;
int counter = 0;
for( l1extra::L1EmParticleCollection::const_iterator emItr = emIsolColl->begin(); emItr != emIsolColl->end() ;++emItr) {
// Used by Clemy
_trig_L1emIso_ieta[counter] = emItr->gctEmCand()->regionId().ieta();
_trig_L1emIso_iphi[counter] = emItr->gctEmCand()->regionId().iphi();
_trig_L1emIso_rank[counter] = emItr->gctEmCand()->rank(); // ET in ADC count... 1 ADC count = 0.5 GeV
// From Trigger twiki
_trig_L1emIso_eta[counter] = emItr->eta();
_trig_L1emIso_phi[counter] = emItr->phi();
_trig_L1emIso_energy[counter] = emItr->energy();
_trig_L1emIso_et[counter] = emItr->et();
counter++;
}
// Non Isolated candidates
_trig_L1emNonIso_N = emNonisolColl->size();
if(PrintDebug_) cout << "N L1 candidate noniso : " << _trig_L1emNonIso_N << endl;
counter = 0;
for( l1extra::L1EmParticleCollection::const_iterator emItr = emNonisolColl->begin(); emItr != emNonisolColl->end() ;++emItr){
// Used by Clemy
_trig_L1emNonIso_ieta[counter] = emItr->gctEmCand()->regionId().ieta();
_trig_L1emNonIso_iphi[counter] = emItr->gctEmCand()->regionId().iphi();
_trig_L1emNonIso_rank[counter] = emItr->gctEmCand()->rank(); // ET in ADC count... 1 ADC count = 0.5 GeV
// From Trigger twiki
_trig_L1emNonIso_eta[counter] = emItr->eta();
_trig_L1emNonIso_phi[counter] = emItr->phi();
_trig_L1emNonIso_energy[counter] = emItr->energy();
_trig_L1emNonIso_et[counter] = emItr->et();
counter++;
} // for loop on Non Iso cand
///// MODIFIED COLLECTION IF ASKED
if( nadGetL1M_ ) {
// Isolated candidates
_trig_L1emIso_N_M = emIsolColl_M->size();
if(PrintDebug_) cout << "_trig_L1emIso_N_M =" << _trig_L1emIso_N_M << endl;
counter=0;
for( l1extra::L1EmParticleCollection::const_iterator emItr = emIsolColl_M->begin();
emItr != emIsolColl_M->end() ;++emItr) {
// Used by Clemy
_trig_L1emIso_ieta_M[counter] = emItr->gctEmCand()->regionId().ieta();
_trig_L1emIso_iphi_M[counter] = emItr->gctEmCand()->regionId().iphi();
_trig_L1emIso_rank_M[counter] = emItr->gctEmCand()->rank();
// ET in ADC count... 1 ADC count = 0.5 GeV
// From Trigger twiki
_trig_L1emIso_eta_M[counter] = emItr->eta();
_trig_L1emIso_phi_M[counter] = emItr->phi();
_trig_L1emIso_energy_M[counter] = emItr->energy();
_trig_L1emIso_et_M[counter] = emItr->et();
counter++;
}
// Non Isolated candidates
_trig_L1emNonIso_N_M = emNonisolColl_M->size();
counter = 0;
for( l1extra::L1EmParticleCollection::const_iterator emItr = emNonisolColl_M->begin();
emItr != emNonisolColl_M->end() ;++emItr){
// Used by Clemy
_trig_L1emNonIso_ieta_M[counter] = emItr->gctEmCand()->regionId().ieta();
_trig_L1emNonIso_iphi_M[counter] = emItr->gctEmCand()->regionId().iphi();
_trig_L1emNonIso_rank_M[counter] = emItr->gctEmCand()->rank();
// ET in ADC count... 1 ADC count = 0.5 GeV
// From Trigger twiki
_trig_L1emNonIso_eta_M[counter] = emItr->eta();
_trig_L1emNonIso_phi_M[counter] = emItr->phi();
_trig_L1emNonIso_energy_M[counter] = emItr->energy();
_trig_L1emNonIso_et_M[counter] = emItr->et();
counter++;
} // for loop on Non Iso cand
}
///////////////////////////////////////////////////////////////////////////////////////////////
// --- PRE- AND POST-FIRING ---
edm::Handle< L1GlobalTriggerReadoutRecord > gtRecord;
iEvent.getByLabel( edm::InputTag(gtRecordCollectionTag_), gtRecord);
//PRE-FIRING
const L1GtPsbWord psb = gtRecord->gtPsbWord(0xbb0d, -1);
//psb.print(cout);
std::vector<int> psbel;
psbel.push_back(psb.aData(4));
psbel.push_back(psb.aData(5));
psbel.push_back(psb.bData(4));
psbel.push_back(psb.bData(5));
counter = 0;
std::vector<int>::const_iterator ipsbel;
for(ipsbel=psbel.begin(); ipsbel!=psbel.end(); ipsbel++) {
int rank = (*ipsbel)&0x3f; // ET in ADC count... 1 ADC count = 0.5 GeV
if(rank>0) {
int iEta = int(((*ipsbel)>>6)&7);
int sign = ( ((*ipsbel>>9)&1) ? -1. : 1. );
int regionEtaRec;
if(sign > 0) regionEtaRec = iEta + 11;
if(sign < 0) regionEtaRec = 10 - iEta;
if(sign==0) std::cout<<"WEIRD (pre, non-iso)"<<std::endl;
// Used by Clemy
_trig_preL1emNonIso_ieta[counter] = regionEtaRec;
_trig_preL1emNonIso_iphi[counter] = int(((*ipsbel)>>10)&0x1f);
_trig_preL1emNonIso_rank[counter] = rank;
counter++;
}
}//loop Noniso
_trig_preL1emNonIso_N = counter;
psbel.clear();
psbel.push_back(psb.aData(6));
psbel.push_back(psb.aData(7));
psbel.push_back(psb.bData(6));
psbel.push_back(psb.bData(7));
counter = 0;
for(ipsbel=psbel.begin(); ipsbel!=psbel.end(); ipsbel++) {
int rank = (*ipsbel)&0x3f; // ET in ADC count... 1 ADC count = 0.5 GeV
if(rank>0) {
int iEta = int(((*ipsbel)>>6)&7);
int sign = ( ((*ipsbel>>9)&1) ? -1. : 1. );
int regionEtaRec;
if(sign > 0) regionEtaRec = iEta + 11;
if(sign < 0) regionEtaRec = 10 - iEta;
if(sign==0) std::cout<<"WEIRD (pre, iso)"<<std::endl;
// Used by Clemy
_trig_preL1emIso_ieta[counter] = regionEtaRec;
_trig_preL1emIso_iphi[counter] = int(((*ipsbel)>>10)&0x1f);
_trig_preL1emIso_rank[counter] = rank;
counter++;
}
}//loop Iso
_trig_preL1emIso_N = counter;
//POST-FIRING
const L1GtPsbWord psb2 = gtRecord->gtPsbWord(0xbb0d, 1);
std::vector<int> psbel2;
psbel2.push_back(psb2.aData(4));
psbel2.push_back(psb2.aData(5));
psbel2.push_back(psb2.bData(4));
psbel2.push_back(psb2.bData(5));
counter = 0;
std::vector<int>::const_iterator ipsbel2;
for(ipsbel2=psbel2.begin(); ipsbel2!=psbel2.end(); ipsbel2++) {
int rank = (*ipsbel2)&0x3f; // ET in ADC count... 1 ADC count = 0.5 GeV
if(rank>0) {
int iEta = int(((*ipsbel2)>>6)&7);
int sign = ( ((*ipsbel2>>9)&1) ? -1. : 1. );
int regionEtaRec;
if(sign > 0) regionEtaRec = iEta + 11;
if(sign < 0) regionEtaRec = 10 - iEta;
if(sign==0) std::cout<<"WEIRD (post, non-iso)"<<std::endl;
// Used by Clemy
_trig_postL1emNonIso_ieta[counter] = regionEtaRec;
_trig_postL1emNonIso_iphi[counter] = int(((*ipsbel2)>>10)&0x1f);
_trig_postL1emNonIso_rank[counter] = rank;
counter++;
}
}//loop Noniso
_trig_postL1emNonIso_N = counter;
psbel2.clear();
psbel2.push_back(psb2.aData(6));
psbel2.push_back(psb2.aData(7));
psbel2.push_back(psb2.bData(6));
psbel2.push_back(psb2.bData(7));
counter = 0;
for(ipsbel2=psbel2.begin(); ipsbel2!=psbel2.end(); ipsbel2++) {
int rank = (*ipsbel2)&0x3f; // ET in ADC count... 1 ADC count = 0.5 GeV
if(rank>0) {
int iEta = int(((*ipsbel2)>>6)&7);
int sign = ( ((*ipsbel2>>9)&1) ? -1. : 1. );
int regionEtaRec;
if(sign > 0) regionEtaRec = iEta + 11;
if(sign < 0) regionEtaRec = 10 - iEta;
if(sign==0) std::cout<<"WEIRD (post, iso)"<<std::endl;
// Used by Clemy
_trig_postL1emIso_ieta[counter] = regionEtaRec;
_trig_postL1emIso_iphi[counter] = int(((*ipsbel2)>>10)&0x1f);
_trig_postL1emIso_rank[counter] = rank;
counter++;
}
}//loop Iso
_trig_postL1emIso_N = counter;
} // if AOD
// ----------------------
// get HLT EM candidate
// ----------------------
edm::Handle<trigger::TriggerEvent> trigEvent;
iEvent.getByLabel(triggerEventTag_, trigEvent);
const Int_t N_filter(trigEvent->sizeFilters());
std::vector<Int_t> ID_filter;
// Print Official Filters
//for(int ifi=0;ifi<N_filter;ifi++) {
//cout << "filter tag " << ifi << " = " << trigEvent->filterTag(ifi) << endl;
//} // for loop on filters
int hlt_counter = 0;
// Loop on user's Filters
for(int itrig=0;itrig< (int) HLT_Filters_.size();itrig++) {
ID_filter.push_back(trigEvent->filterIndex(HLT_Filters_[itrig]));
const trigger::TriggerObjectCollection& TOC(trigEvent->getObjects());
if( ID_filter[itrig] < N_filter) { // !!! To be checked !!! trigEvent->size() ) {
const trigger::Keys& keys( trigEvent->filterKeys(ID_filter[itrig]));
// Loop on HLT objects
for ( int hlto = 0; hlto < (int) keys.size(); hlto++ ) {
if(hlt_counter>19) continue;
trigger::size_type hltf = keys[hlto];
const trigger::TriggerObject& TrigObj(TOC[hltf]);
_trig_HLT_eta[hlt_counter] = TrigObj.eta();
_trig_HLT_phi[hlt_counter] = TrigObj.phi();
_trig_HLT_energy[hlt_counter] = TrigObj.energy();
_trig_HLT_pt[hlt_counter] = TrigObj.pt();
_trig_HLT_name[hlt_counter] = itrig;
hlt_counter++;
} // for loop on HLT objects
} // if idfilter<trigevent size
} // for loop on filters
_trig_HLT_N = hlt_counter;
if(hlt_counter>19) { _trig_HLT_N = 20; cout << "Number of HLT Objects>20, trig_HLT_N set to 20" << endl;}
} // end of FillTrigger
// ====================================================================================
void SimpleNtpleCustom::FillMET (const edm::Event& iEvent, const edm::EventSetup& iSetup)
// ====================================================================================
{
// caloMET object (negative vector sum of calorimeter towers)
edm::Handle< edm::View<reco::CaloMET> > caloMEThandle;
iEvent.getByLabel("met", caloMEThandle);
// MET object that corrects the basic calorimeter MET for muons
edm::Handle< edm::View<reco::CaloMET> > muCorrMEThandle;
iEvent.getByLabel("corMetGlobalMuons", muCorrMEThandle);
// MET object that corrects the basic calorimeter MET for muons and tracks
edm::Handle< edm::View<reco::MET> > tcMEThandle;
iEvent.getByLabel("tcMet", tcMEThandle);
// MET object built as the (negative) vector sum of all particles (PFCandidates) reconstructed in the event
edm::Handle< edm::View<reco::PFMET> > pfMEThandle;
iEvent.getByLabel("pfMet", pfMEThandle);
// CALO MET
_met_calo_et = (caloMEThandle->front() ).et();
_met_calo_px = (caloMEThandle->front() ).px();
_met_calo_py = (caloMEThandle->front() ).py();
_met_calo_phi = (caloMEThandle->front() ).phi();
_met_calo_set = (caloMEThandle->front() ).sumEt();
_met_calo_sig = (caloMEThandle->front() ).mEtSig();
// CALOMU MET
_met_calomu_et = (muCorrMEThandle->front() ).et();
_met_calomu_px = (muCorrMEThandle->front() ).px();
_met_calomu_py = (muCorrMEThandle->front() ).py();
_met_calomu_phi = (muCorrMEThandle->front() ).phi();
_met_calomu_set = (muCorrMEThandle->front() ).sumEt();
_met_calomu_sig = (muCorrMEThandle->front() ).mEtSig();
// TC MET
_met_tc_et = (tcMEThandle->front() ).et();
_met_tc_px = (tcMEThandle->front() ).px();
_met_tc_py = (tcMEThandle->front() ).py();
_met_tc_phi = (tcMEThandle->front() ).phi();
_met_tc_set = (tcMEThandle->front() ).sumEt();
_met_tc_sig = (tcMEThandle->front() ).mEtSig();
// PFMET
_met_pf_et = (pfMEThandle->front() ).et();
_met_pf_px = (pfMEThandle->front() ).px();
_met_pf_py = (pfMEThandle->front() ).py();
_met_pf_phi = (pfMEThandle->front() ).phi();
_met_pf_set = (pfMEThandle->front() ).sumEt();
_met_pf_sig = (pfMEThandle->front() ).mEtSig();
} // end of Fill MET
// ====================================================================================
void SimpleNtpleCustom::FillEle(const edm::Event& iEvent, const edm::EventSetup& iSetup)
// ====================================================================================
{
edm::Handle<reco::GsfElectronCollection> EleHandle ;
iEvent.getByLabel (EleTag_.label(),EleHandle) ;
edm::Handle<reco::PFCandidateCollection> PfEleHandle;
iEvent.getByLabel("particleFlow", PfEleHandle);
std::vector<edm::Handle<edm::ValueMap<float> > > eleIdCutHandles(9) ;
iEvent.getByLabel (EleID_VeryLooseTag_ , eleIdCutHandles[0]) ;
iEvent.getByLabel (EleID_LooseTag_ , eleIdCutHandles[1]) ;
iEvent.getByLabel (EleID_MediumTag_ , eleIdCutHandles[2]) ;
iEvent.getByLabel (EleID_TightTag_ , eleIdCutHandles[3]) ;
iEvent.getByLabel (EleID_SuperTightTag_ , eleIdCutHandles[4]) ;
iEvent.getByLabel (EleID_HyperTight1Tag_ , eleIdCutHandles[5]) ;
iEvent.getByLabel (EleID_HyperTight2Tag_ , eleIdCutHandles[6]) ;
iEvent.getByLabel (EleID_HyperTight3Tag_ , eleIdCutHandles[7]) ;
iEvent.getByLabel (EleID_HyperTight4Tag_ , eleIdCutHandles[8]) ;
//std::cout << " FillEle recoBeamSpotHandle " << std::endl;
edm::Handle<reco::BeamSpot> recoBeamSpotHandle ;
///iEvent.getByType(recoBeamSpotHandle) ;
const reco::BeamSpot bs = *recoBeamSpotHandle ;
//std::cout << " FillEle calo topology " << std::endl;
//calo topology
const CaloTopology * topology ;
///const EcalChannelStatus *chStatus ;
edm::Handle< EcalRecHitCollection > reducedEBRecHits;
edm::Handle< EcalRecHitCollection > reducedEERecHits;
unsigned long long cacheIDTopo_=0;
edm::ESHandle<CaloTopology> theCaloTopo;
if (cacheIDTopo_!=iSetup.get<CaloTopologyRecord>().cacheIdentifier()){
cacheIDTopo_=iSetup.get<CaloTopologyRecord>().cacheIdentifier();
iSetup.get<CaloTopologyRecord>().get(theCaloTopo);
}
topology = theCaloTopo.product() ;
edm::ESHandle<EcalChannelStatus> pChannelStatus;
iSetup.get<EcalChannelStatusRcd>().get(pChannelStatus);
///chStatus = pChannelStatus.product();
//for42x
unsigned long long cacheSevLevel = 0;
edm::ESHandle<EcalSeverityLevelAlgo> sevLevel;
if(cacheSevLevel != iSetup.get<EcalSeverityLevelAlgoRcd>().cacheIdentifier()){
cacheSevLevel = iSetup.get<EcalSeverityLevelAlgoRcd>().cacheIdentifier();
iSetup.get<EcalSeverityLevelAlgoRcd>().get(sevLevel);
}
const EcalSeverityLevelAlgo* sl=sevLevel.product();
//std::cout << " FillEle geometry (used for L1 trigger) " << std::endl;
// geometry (used for L1 trigger)
edm::ESHandle<CaloSubdetectorGeometry> theEndcapGeometry_handle, theBarrelGeometry_handle;
iSetup.get<EcalEndcapGeometryRecord>().get("EcalEndcap",theEndcapGeometry_handle);
iSetup.get<EcalBarrelGeometryRecord>().get("EcalBarrel",theBarrelGeometry_handle);
iSetup.get<IdealGeometryRecord>().get(eTTmap_);
theEndcapGeometry_ = &(*theEndcapGeometry_handle);
theBarrelGeometry_ = &(*theBarrelGeometry_handle);
//std::cout << " FillEle reduced rechits " << std::endl;
// reduced rechits
if(!aod_){
iEvent.getByLabel( edm::InputTag("ecalRecHit:EcalRecHitsEB"), reducedEBRecHits );
iEvent.getByLabel( edm::InputTag("ecalRecHit:EcalRecHitsEE"), reducedEERecHits ) ;
}
else{
iEvent.getByLabel( edm::InputTag("reducedEcalRecHitsEB"), reducedEBRecHits );
iEvent.getByLabel( edm::InputTag("reducedEcalRecHitsEE"), reducedEERecHits ) ;
}
edm::Handle<reco::TrackCollection> tracks_h;
iEvent.getByLabel("generalTracks", tracks_h);
edm::Handle<DcsStatusCollection> dcsHandle;
iEvent.getByLabel(dcsTag_, dcsHandle);
double evt_bField;
// need the magnetic field
//
// if isData then derive bfield using the
// magnet current from DcsStatus
// otherwise take it from the IdealMagneticFieldRecord
if(type_ == "DATA" )
{
// scale factor = 3.801/18166.0 which are
// average values taken over a stable two
// week period
if ((*dcsHandle).size() != 0 ) {
float currentToBFieldScaleFactor = 2.09237036221512717e-04;
float current = (*dcsHandle)[0].magnetCurrent();
evt_bField = current*currentToBFieldScaleFactor;
}
else {
edm::ESHandle<MagneticField> magneticField;
iSetup.get<IdealMagneticFieldRecord>().get(magneticField);
GlobalPoint gPoint(0.,0.,0.);
evt_bField = magneticField->inTesla(gPoint).z();
}
}
else {
edm::ESHandle<MagneticField> magneticField;
iSetup.get<IdealMagneticFieldRecord>().get(magneticField);
GlobalPoint gPoint(0.,0.,0.);
evt_bField = magneticField->inTesla(gPoint).z();
}
//std::cout << " FillEle Beam Spot Information " << std::endl;
// Beam Spot Information
BS_x = bs.position().x();
BS_y = bs.position().y();
BS_z = bs.position().z();
BS_dz = bs.sigmaZ();
BS_dydz = bs.dydz();
BS_dxdz = bs.dxdz();
BS_bw_x = bs.BeamWidthX();
BS_bw_y = bs.BeamWidthY();
//std::cout << " FillEle Masked Towers " << std::endl;
// -----------------------------
// Masked Towers
// -----------------------------
// !!! Idealy, should be in FillTrigger... but not possible for now !!!
//Adding RCT mask
// list of RCT channels to mask
edm::ESHandle<L1RCTChannelMask> channelMask;
iSetup.get<L1RCTChannelMaskRcd>().get(channelMask);
const L1RCTChannelMask* cEs = channelMask.product();
uint n0MaskedRCT = 0;
for(int i = 0; i< 18; i++)
for(int j =0; j< 2; j++)
for(int k =0; k<28; k++)
if(cEs->ecalMask[i][j][k]){
//cout << "ECAL masked channel: RCT crate " << i << " iphi " << j <<" ieta " <<k <<endl;
_trig_iMaskedRCTeta[n0MaskedRCT]=k;
_trig_iMaskedRCTphi[n0MaskedRCT]=j;
_trig_iMaskedRCTcrate[n0MaskedRCT]=i;
n0MaskedRCT++;
}
_trig_nMaskedRCT = n0MaskedRCT;
//Adding TT mask
// list of towers masked for trigger
edm::ESHandle<EcalTPGTowerStatus> theEcalTPGTowerStatus_handle;
iSetup.get<EcalTPGTowerStatusRcd>().get(theEcalTPGTowerStatus_handle);
const EcalTPGTowerStatus * ecaltpgTowerStatus=theEcalTPGTowerStatus_handle.product();
const EcalTPGTowerStatusMap &towerMap=ecaltpgTowerStatus->getMap();
EcalTPGTowerStatusMapIterator ittpg;
uint nMaskedChannels = 0;
for (ittpg=towerMap.begin();ittpg!=towerMap.end();++ittpg) {
if ((*ittpg).second > 0)
{
EcalTrigTowerDetId ttId((*ittpg).first);
_trig_iMaskedTTeta[nMaskedChannels] = ttId.ieta();
_trig_iMaskedTTphi[nMaskedChannels] = ttId.iphi();
nMaskedChannels++;
}
}//loop trigger towers
_trig_nMaskedCh = nMaskedChannels;
//std::cout << " FillEle Seeds collection " << std::endl;
// ----------------------------------------------
// Get Seeds collection
// ----------------------------------------------
if(!aod_){
edm::Handle<reco::ElectronSeedCollection> elSeeds;
iEvent.getByLabel(SeedTag_,elSeeds);
if(elSeeds.product()->size() < 100) ele_nSeed = elSeeds.product()->size();
else ele_nSeed = 100;
if(ele_nSeed > 0){
reco::ElectronSeedCollection::const_iterator MyS_seed = (*elSeeds).begin();
for(int counterSeed=0; counterSeed<ele_nSeed; ++counterSeed){
if(MyS_seed->isEcalDriven()) ele_SeedIsEcalDriven[counterSeed] = 1;
if(MyS_seed->isTrackerDriven()) ele_SeedIsTrackerDriven[counterSeed] = 1;
ele_SeedSubdet2[counterSeed] = int(MyS_seed->subDet2());
//to avoid some inf values//
if(fabs(MyS_seed->dPhi2Pos()) < 100.) ele_SeedDphi2Pos[counterSeed] = double(MyS_seed->dPhi2Pos());
if(fabs(MyS_seed->dRz2Pos()) < 100.) ele_SeedDrz2Pos[counterSeed] = double(MyS_seed->dRz2Pos());
if(fabs(MyS_seed->dPhi2()) < 100.) ele_SeedDphi2Neg[counterSeed] = double(MyS_seed->dPhi2());
if(fabs(MyS_seed->dRz2()) < 100.) ele_SeedDrz2Neg[counterSeed] = double(MyS_seed->dRz2());
ele_SeedSubdet1[counterSeed] = int(MyS_seed->subDet1());
//to avoid some inf values//
if(fabs(MyS_seed->dPhi1Pos()) < 100.) ele_SeedDphi1Pos[counterSeed] = double(MyS_seed->dPhi1Pos());
if(fabs(MyS_seed->dRz1Pos()) < 100.) ele_SeedDrz1Pos[counterSeed] = double(MyS_seed->dRz1Pos());
if(fabs(MyS_seed->dPhi1()) < 100.) ele_SeedDphi1Neg[counterSeed] = double(MyS_seed->dPhi1());
if(fabs(MyS_seed->dRz1()) < 100.) ele_SeedDrz1Neg[counterSeed] = double(MyS_seed->dRz1());
++MyS_seed;
} // loop on seed
} // if nSeed>0
}
//std::cout << " FillEle Get MC information " << std::endl;
// ----------------------------------------------
// Get MC information
// ----------------------------------------------
edm::Handle<edm::HepMCProduct> HepMCEvt;
if(type_ == "MC" && aod_ == false) iEvent.getByLabel(MCTag_, HepMCEvt);
const HepMC::GenEvent* MCEvt = 0;
HepMC::GenParticle* genPc = 0;
HepMC::FourVector pAssSim;
if(type_ == "MC" && aod_ == false) { MCEvt = HepMCEvt->GetEvent();
_MC_pthat = HepMCEvt -> GetEvent() -> event_scale();}
if(type_ == "MC" && aod_ == true) {
edm::Handle< GenEventInfoProduct > HepMCEvt;
iEvent.getByLabel(MCTag_, HepMCEvt);
if(HepMCEvt->hasBinningValues()) _MC_pthat = (HepMCEvt->binningValues())[0];
else _MC_pthat = 0.0;
}
edm::Handle<reco::GenParticleCollection> genParticlesColl;
if(aod_ == true && type_ == "MC") iEvent.getByLabel("genParticles", genParticlesColl);
//std::cout << " FillEle Get TrackingParticles info " << std::endl;
// ----------------------------------------------
// Get TrackingParticles info
// ----------------------------------------------
/*
// Get simulated
edm::Handle<TrackingParticleCollection> simCollection;
if(type_ == "MC" && simulation_ == true) iEvent.getByLabel(TkPTag_, simCollection);
// Get reconstructed
edm::Handle<edm::View<reco::Track> > recCollection;
iEvent.getByLabel("electronGsfTracks", recCollection);
edm::RefToBaseVector<reco::Track> tc(recCollection);
for (unsigned int j=0; j<recCollection->size();j++)
tc.push_back(edm::RefToBase<reco::Track>(recCollection,j));
// Get associator
edm::ESHandle<TrackAssociatorBase> theHitsAssociator;
if(type_ == "MC" && simulation_ == true) iSetup.get<TrackAssociatorRecord>().get("TrackAssociatorByHits", theHitsAssociator);
TrackAssociatorBase* theAssociatorByHits;
reco::RecoToSimCollection recoToSim;
if(type_ == "MC" && simulation_ == true) {
theAssociatorByHits = (TrackAssociatorBase*)theHitsAssociator.product();
recoToSim = theAssociatorByHits->associateRecoToSim(recCollection, simCollection,&iEvent);
// recoToSim = theAssociatorByHits->associateRecoToSim(tc, simCollection,&iEvent);
if(recoToSim.size() > 0) std::cout << "size = " << recoToSim.size() << std::endl;
}
*/
// Get OLD HZZ isolation (commented... NOT USED ANYMORE)
//edm::Handle<edm::ValueMap<float> > isoTkelemap;
//if(!aod_) iEvent.getByLabel(EleIso_TdrHzzTkMapTag_, isoTkelemap);
//edm::Handle<edm::ValueMap<float> > isoHadelemap;
//if(!aod_) iEvent.getByLabel(EleIso_TdrHzzHcalMapTag_, isoHadelemap);
// for H/E
towersH_ = new edm::Handle<CaloTowerCollection>() ;
if (!iEvent.getByLabel(hcalTowers_,*towersH_))
{ edm::LogError("ElectronHcalHelper::readEvent")<<"failed to get the hcal towers of label "<<hcalTowers_ ; }
// H/E, with Rcone = 0.05 & different ET threshold
EgammaTowerIsolation * towerIso1_00615_0 = new EgammaTowerIsolation(0.0615, 0., 0., 1, towersH_->product()) ;
EgammaTowerIsolation * towerIso2_00615_0 = new EgammaTowerIsolation(0.0615, 0., 0., 2, towersH_->product()) ;
EgammaTowerIsolation * towerIso1_005_0 = new EgammaTowerIsolation(0.05, 0., 0., 1, towersH_->product()) ;
EgammaTowerIsolation * towerIso2_005_0 = new EgammaTowerIsolation(0.05, 0., 0., 2, towersH_->product()) ;
EgammaTowerIsolation * towerIso1_005_1 = new EgammaTowerIsolation(0.05, 0., 1., 1, towersH_->product()) ;
EgammaTowerIsolation * towerIso2_005_1 = new EgammaTowerIsolation(0.05, 0., 1., 2, towersH_->product()) ;
EgammaTowerIsolation * towerIso1_005_15 = new EgammaTowerIsolation(0.05, 0., 1.5, 1, towersH_->product()) ;
EgammaTowerIsolation * towerIso2_005_15 = new EgammaTowerIsolation(0.05, 0., 1.5, 2, towersH_->product()) ;
// H/E, with Rcone = 0.1 & different ET threshold
EgammaTowerIsolation * towerIso1_01_0 = new EgammaTowerIsolation(0.1, 0., 0., 1, towersH_->product()) ;
EgammaTowerIsolation * towerIso2_01_0 = new EgammaTowerIsolation(0.1, 0., 0., 2, towersH_->product()) ;
EgammaTowerIsolation * towerIso1_01_1 = new EgammaTowerIsolation(0.1, 0., 1., 1, towersH_->product()) ;
EgammaTowerIsolation * towerIso2_01_1 = new EgammaTowerIsolation(0.1, 0., 1., 2, towersH_->product()) ;
EgammaTowerIsolation * towerIso1_01_15 = new EgammaTowerIsolation(0.1, 0., 1.5, 1, towersH_->product()) ;
EgammaTowerIsolation * towerIso2_01_15 = new EgammaTowerIsolation(0.1, 0., 1.5, 2, towersH_->product()) ;
// H/E, with Rcone = 0.15 & different ET threshold
//EgammaTowerIsolation * towerIso1_015_0 = new EgammaTowerIsolation(0.15, 0., 0., 1, towersH_->product()) ;
//EgammaTowerIsolation * towerIso2_015_0 = new EgammaTowerIsolation(0.15, 0., 0., 2, towersH_->product()) ;
EgammaTowerIsolation * towerIso1_015_1 = new EgammaTowerIsolation(0.15, 0., 1., 1, towersH_->product()) ;
EgammaTowerIsolation * towerIso2_015_1 = new EgammaTowerIsolation(0.15, 0., 1., 2, towersH_->product()) ;
EgammaTowerIsolation * towerIso1_015_15 = new EgammaTowerIsolation(0.15, 0., 1.5, 1, towersH_->product()) ;
EgammaTowerIsolation * towerIso2_015_15 = new EgammaTowerIsolation(0.15, 0., 1.5, 2, towersH_->product()) ;
//for NEW HCAL Iso
EgammaTowerIsolation * towerIso1_00615Ring03_0 = new EgammaTowerIsolation(0.3, 0.0615, 0., 1, towersH_->product()) ;
EgammaTowerIsolation * towerIso2_00615Ring03_0 = new EgammaTowerIsolation(0.3, 0.0615, 0., 2, towersH_->product()) ;
EgammaTowerIsolation * towerIso1_005Ring03_0 = new EgammaTowerIsolation(0.3, 0.05, 0., 1, towersH_->product()) ;
EgammaTowerIsolation * towerIso2_005Ring03_0 = new EgammaTowerIsolation(0.3, 0.05, 0., 2, towersH_->product()) ;
EgammaTowerIsolation * towerIso1_0Ring03_0 = new EgammaTowerIsolation(0.3, 0., 0., 1, towersH_->product()) ;
EgammaTowerIsolation * towerIso2_0Ring03_0 = new EgammaTowerIsolation(0.3, 0., 0., 2, towersH_->product()) ;
// Get e/g for HZZ Isolation (e/g isolation optimized for HZZ)
edm::Handle<edm::ValueMap<double> > egmisoTkelemap;
iEvent.getByLabel(EleIso_Eg4HzzTkMapTag_ , egmisoTkelemap);
edm::Handle<edm::ValueMap<double> > egmisoEcalelemap;
iEvent.getByLabel(EleIso_Eg4HzzEcalMapTag_ , egmisoEcalelemap);
edm::Handle<edm::ValueMap<double> > egmisoHcalelemap;
iEvent.getByLabel(EleIso_Eg4HzzHcalMapTag_ , egmisoHcalelemap);
float deta = -20.;
float dphi = -20.;
if(EleHandle->size() < 10 ){ ele_N = EleHandle->size(); }
else {ele_N = 10;}
TClonesArray &electrons = *m_electrons;
int counter = 0;
//std::cout << " FillEle Loop on Electrons " << std::endl;
// ----------------------------------------------
// Loop on Electrons
// ----------------------------------------------
int nTow=0;
int nReg=0;
for(int i=0; i< ele_N; i++){
edm::Ref<reco::GsfElectronCollection> electronEdmRef(EleHandle,i);
setMomentum (myvector, (*EleHandle)[i].p4());
new (electrons[counter]) TLorentzVector (myvector);
ele_eidVeryLoose[counter] = (*(eleIdCutHandles[0]))[electronEdmRef];
ele_eidLoose[counter] = (*(eleIdCutHandles[1]))[electronEdmRef];
ele_eidMedium[counter] = (*(eleIdCutHandles[2]))[electronEdmRef];
ele_eidTight[counter] = (*(eleIdCutHandles[3]))[electronEdmRef];
ele_eidSuperTight[counter] = (*(eleIdCutHandles[4]))[electronEdmRef];
ele_eidHyperTight1[counter] = (*(eleIdCutHandles[5]))[electronEdmRef];
ele_eidHyperTight2[counter] = (*(eleIdCutHandles[6]))[electronEdmRef];
ele_eidHyperTight3[counter] = (*(eleIdCutHandles[7]))[electronEdmRef];
ele_eidHyperTight4[counter] = (*(eleIdCutHandles[8]))[electronEdmRef];
ele_echarge[counter] = (*EleHandle)[i].charge();
ele_he[counter] = (*EleHandle)[i].hadronicOverEm() ;
ele_eseedpout[counter] = (*EleHandle)[i].eSeedClusterOverPout();
ele_ep[counter] = (*EleHandle)[i].eSuperClusterOverP() ;
ele_eseedp[counter] = (*EleHandle)[i].eSeedClusterOverP() ;
ele_eelepout[counter] = (*EleHandle)[i].eEleClusterOverPout() ;
ele_pin_mode[counter] = (*EleHandle)[i].trackMomentumAtVtx().R() ;
ele_pout_mode[counter] = (*EleHandle)[i].trackMomentumOut().R() ;
ele_calo_energy[counter] = (*EleHandle)[i].caloEnergy() ;
ele_pTin_mode[counter] = (*EleHandle)[i].trackMomentumAtVtx().Rho() ;
ele_pTout_mode[counter] = (*EleHandle)[i].trackMomentumOut().Rho() ;
if(!aod_){
ele_pin_mean[counter] = (*EleHandle)[i].gsfTrack()->innerMomentum().R() ;
ele_pout_mean[counter] = (*EleHandle)[i].gsfTrack()->outerMomentum().R();
ele_pTin_mean[counter] = (*EleHandle)[i].gsfTrack()->innerMomentum().Rho() ;
ele_pTout_mean[counter] = (*EleHandle)[i].gsfTrack()->outerMomentum().Rho() ;
}
//std::cout << " FillEle Get SuperCluster Informations " << std::endl;
// Get SuperCluster Informations
reco::SuperClusterRef sclRef = (*EleHandle)[i].superCluster();
math::XYZPoint sclPos = (*EleHandle)[i].superClusterPosition();
if (!(*EleHandle)[i].ecalDrivenSeed() && (*EleHandle)[i].trackerDrivenSeed())
sclRef = (*EleHandle)[i].pflowSuperCluster();
double R=TMath::Sqrt(sclRef->x()*sclRef->x() + sclRef->y()*sclRef->y() +sclRef->z()*sclRef->z());
double Rt=TMath::Sqrt(sclRef->x()*sclRef->x() + sclRef->y()*sclRef->y());
ele_sclRawE[counter] = sclRef->rawEnergy() ;
ele_sclEpresh[counter] = 0. ;
if ((*EleHandle)[i].isEE()) ele_sclEpresh[counter] = sclRef->preshowerEnergy() ;
ele_sclE[counter] = sclRef->energy() ;
ele_sclEt[counter] = sclRef->energy()*(Rt/R) ;
ele_sclEta[counter] = sclRef->eta() ;
ele_sclPhi[counter] = sclRef->phi() ;
ele_sclX[counter] = sclPos.X();
ele_sclY[counter] = sclPos.Y();
ele_sclZ[counter] = sclPos.Z();
//cout << "scl X Y Z : "<< sclPos.X() <<", "<<sclPos.Y()<<", "<<sclPos.Z()<<endl;
//cout << "scl X Y Z : "<< sclX[counter] <<", "<<sclY[counter]<<", "<<sclZ[counter]<<endl;
// NEW H/E
//reco::SuperCluster EmSCCand = *isc;
reco::SuperCluster EmSCCand = *sclRef;
double HoE_00615_0 = towerIso1_00615_0->getTowerESum(&EmSCCand) + towerIso2_00615_0->getTowerESum(&EmSCCand) ;
double HoE_005_0 = towerIso1_005_0->getTowerESum(&EmSCCand) + towerIso2_005_0->getTowerESum(&EmSCCand) ;
double HoE_005_1 = towerIso1_005_1->getTowerESum(&EmSCCand) + towerIso2_005_1->getTowerESum(&EmSCCand) ;
double HoE_005_15 = towerIso1_005_15->getTowerESum(&EmSCCand) + towerIso2_005_15->getTowerESum(&EmSCCand) ;
double HoE_01_0 = towerIso1_01_0->getTowerESum(&EmSCCand) + towerIso2_01_0->getTowerESum(&EmSCCand) ;
double HoE_01_1 = towerIso1_01_1->getTowerESum(&EmSCCand) + towerIso2_01_1->getTowerESum(&EmSCCand) ;
double HoE_01_15 = towerIso1_01_15->getTowerESum(&EmSCCand) + towerIso2_01_15->getTowerESum(&EmSCCand) ;
//double HoE_015_0 = towerIso1_01_0->getTowerESum(&EmSCCand) + towerIso2_01_0->getTowerESum(&EmSCCand) ;
double HoE_015_1 = towerIso1_015_1->getTowerESum(&EmSCCand) + towerIso2_015_1->getTowerESum(&EmSCCand) ;
double HoE_015_15 = towerIso1_015_15->getTowerESum(&EmSCCand) + towerIso2_015_15->getTowerESum(&EmSCCand) ;
HoE_00615_0 /= sclRef->energy() ;
HoE_005_0 /= sclRef->energy() ;
HoE_005_1 /= sclRef->energy() ;
HoE_005_15 /= sclRef->energy() ;
HoE_01_0 /= sclRef->energy() ;
HoE_01_1 /= sclRef->energy() ;
HoE_01_15 /= sclRef->energy() ;
//HoE_015_0 /= sclRef->energy() ;
HoE_015_1 /= sclRef->energy() ;
HoE_015_15 /= sclRef->energy() ;
_ele_he_00615_0[counter] = HoE_00615_0 ;
_ele_he_005_0[counter] = HoE_005_0 ;
_ele_he_005_1[counter] = HoE_005_1 ;
_ele_he_005_15[counter] = HoE_005_15 ;
_ele_he_01_0[counter] = HoE_01_0 ;
_ele_he_01_1[counter] = HoE_01_1 ;
_ele_he_01_15[counter] = HoE_01_15 ;
//_ele_he_015_0[counter] = HoE_01_0 ;
_ele_he_015_1[counter] = HoE_015_1 ;
_ele_he_015_15[counter] = HoE_015_15 ;
// cout<<"debug 0 "<<counter<<endl;
// total effective uncertainty on energy in GeV
if (funcbase_) {
ele_sclErr[counter] = funcbase_->getValue(*sclRef, 0); //
// cout<<"debug 1 "<<counter<<endl;
// positive uncertainty
ele_sclErr_pos[counter] = funcbase_->getValue(*sclRef, 1);
//cout<<"debug 2 "<<counter<<endl;
// negative uncertainty
ele_sclErr_neg[counter] = funcbase_->getValue(*sclRef, -1);
// cout<<"debug 3 "<<counter<<endl;
ele_trErr[counter]=(*EleHandle)[i].trackMomentumError();
//cout<<"debug 4 "<<counter<<endl;
//for42X
// ele_momErr[counter]=(*EleHandle)[i].electronMomentumError();
ele_momErr[counter]=(*EleHandle)[i].p4Error(GsfElectron::P4_COMBINATION);
//cout<<"debug 5 "<<counter<<endl;
// cout<<" ele_trErr[counter]/ele_pin_mode[counter] = "<<ele_trErr[counter]/ele_pin_mode[counter]<<" ele_sclErr[counter]/ele_sclE[counter] = "<<ele_sclErr[counter]/ele_sclE[counter]<<endl;
if (!(*EleHandle)[i].ecalDrivenSeed()) { /// no change if not ecaldriven
// cout<<" no change not ecal driven"<<endl;
ele_newmom[counter] = (*EleHandle)[i].p4().P();
ele_newmomErr[counter] = ele_momErr[counter];
}
else { //if ecal driven special care for large errors
if (ele_trErr[counter]/ele_pin_mode[counter] > 0.5 && ele_sclErr[counter]/ele_sclE[counter] <= 0.5) { //take E if sigmaE/E <=0.5 and sigmaP/P >0.5
ele_newmom[counter] = ele_sclE[counter]; ele_newmomErr[counter] = ele_sclErr[counter];
// cout<<" E choice new mom= "<<ele_newmom[counter]<<" new err= "<<ele_newmomErr[counter]<<endl;
}
else if (ele_trErr[counter]/ele_pin_mode[counter] <= 0.5 && ele_sclErr[counter]/ele_sclE[counter] > 0.5){//take P if sigmaE/E > 0.5 and sigmaP/P <=0.5
ele_newmom[counter] = ele_pin_mode[counter]; ele_newmomErr[counter] = ele_trErr[counter];
// cout<<" P choice new mom= "<<ele_newmom[counter]<<" new err= "<<ele_newmomErr[counter]<<endl;
}
else if (ele_trErr[counter]/ele_pin_mode[counter] > 0.5 && ele_sclErr[counter]/ele_sclE[counter] > 0.5){//take the lowest sigma/value if sigmaE/E >0.5 and sigmaP/P >0.5
if (ele_trErr[counter]/ele_pin_mode[counter] < ele_sclErr[counter]/ele_sclE[counter]) {
ele_newmom[counter] = ele_pin_mode[counter]; ele_newmomErr[counter] = ele_trErr[counter];
// cout<<" P choice new mom= "<<ele_newmom[counter]<<" new err= "<<ele_newmomErr[counter]<<endl;
}
else{
ele_newmom[counter] = ele_sclE[counter]; ele_newmomErr[counter] = ele_sclErr[counter];
// cout<<" E choice new mom= "<<ele_newmom[counter]<<" new err= "<<ele_newmomErr[counter]<<endl;
}
}
else { // if sigmaE/E <= 0.5 and sigmaP/P <=0.5 no change
// cout<<" no change"<<endl;
ele_newmom[counter] = (*EleHandle)[i].p4().P();
ele_newmomErr[counter] = ele_momErr[counter];
}
}
}
// else cout<<"no function base for ecal errors"<<endl;
// cout<<" new mom= "<< ele_newmom[counter]<<" new error= "<<ele_newmomErr[counter] <<endl;
ele_tr_atcaloX[counter] = (*EleHandle)[i].trackPositionAtCalo().x();
ele_tr_atcaloY[counter] = (*EleHandle)[i].trackPositionAtCalo().y();
ele_tr_atcaloZ[counter] = (*EleHandle)[i].trackPositionAtCalo().z();
//cout<<"track @calo: "<<(*EleHandle)[i].trackPositionAtCalo().x()<<" "<<(*EleHandle)[i].trackPositionAtCalo().y()<<" "<<(*EleHandle)[i].trackPositionAtCalo().z()<<endl;
if(!aod_){
ele_firsthit_X[counter] = (*EleHandle)[i].gsfTrack()->innerPosition().x();
ele_firsthit_Y[counter] = (*EleHandle)[i].gsfTrack()->innerPosition().y();
ele_firsthit_Z[counter] = (*EleHandle)[i].gsfTrack()->innerPosition().z();
}
// cout<<"first hit: "<<firsthit_X[counter]<<" "<<firsthit_Y[counter]<<" "<<firsthit_Z[counter]<<endl;
ele_deltaetaseed[counter] = (*EleHandle)[i].deltaEtaSeedClusterTrackAtCalo() ;
ele_deltaphiseed[counter] = (*EleHandle)[i].deltaPhiSeedClusterTrackAtCalo() ;
ele_deltaetaele[counter] = (*EleHandle)[i].deltaEtaEleClusterTrackAtCalo() ;
ele_deltaphiele[counter] = (*EleHandle)[i].deltaPhiEleClusterTrackAtCalo() ;
ele_deltaetain[counter] = (*EleHandle)[i].deltaEtaSuperClusterTrackAtVtx();
ele_deltaphiin[counter] = (*EleHandle)[i].deltaPhiSuperClusterTrackAtVtx();
ele_sigmaietaieta[counter] = (*EleHandle)[i].sigmaIetaIeta() ;
ele_sigmaetaeta[counter] = (*EleHandle)[i].sigmaEtaEta() ;
ele_e15[counter] = (*EleHandle)[i].e1x5() ;
ele_e25max[counter] = (*EleHandle)[i].e2x5Max() ;
ele_e55[counter] = (*EleHandle)[i].e5x5() ;
const EcalRecHitCollection * reducedRecHits = 0 ;
if ((*EleHandle)[i].isEB())
reducedRecHits = reducedEBRecHits.product() ;
else
reducedRecHits = reducedEERecHits.product() ;
const reco::CaloCluster & seedCluster = *(*EleHandle)[i].superCluster()->seed() ;
ele_e1[counter] = EcalClusterTools::eMax(seedCluster,reducedRecHits) ;
ele_e33[counter] = EcalClusterTools::e3x3(seedCluster,reducedRecHits,topology) ;
ele_fbrem[counter] = (*EleHandle)[i].fbrem() ;
ele_mva[counter] = (*EleHandle)[i].mva() ;
if ((*EleHandle)[i].isEB()) ele_isbarrel[counter] = 1 ;
else ele_isbarrel[counter] = 0 ;
if ((*EleHandle)[i].isEE()) ele_isendcap[counter] = 1 ;
else ele_isendcap[counter] = 0 ;
if ((*EleHandle)[i].isEBEtaGap()) ele_isEBetaGap[counter] = 1 ;
if ((*EleHandle)[i].isEBPhiGap()) ele_isEBphiGap[counter] = 1 ;
if ((*EleHandle)[i].isEEDeeGap()) ele_isEEdeeGap[counter] = 1 ;
if ((*EleHandle)[i].isEERingGap()) ele_isEEringGap[counter] = 1 ;
if ((*EleHandle)[i].ecalDrivenSeed()) ele_isecalDriven[counter] = 1 ;
if ((*EleHandle)[i].trackerDrivenSeed()) ele_istrackerDriven[counter] = 1 ;
ele_eClass[counter] = (*EleHandle)[i].classification() ;
ele_vertex_x[counter] = (*EleHandle)[i].vertex().x();
ele_vertex_y[counter] = (*EleHandle)[i].vertex().y();
ele_vertex_z[counter] = (*EleHandle)[i].vertex().z();
//if(!aod_){
ele_missing_hits[counter] = (*EleHandle)[i].gsfTrack()->numberOfLostHits();
ele_lost_hits[counter] = (*EleHandle)[i].gsfTrack()->numberOfValidHits() ;
ele_chi2_hits[counter] = (*EleHandle)[i].gsfTrack()->normalizedChi2() ;
ele_dxyB[counter] = (*EleHandle)[i].gsfTrack()->dxy(bs.position()) ;
ele_dxy[counter] = (*EleHandle)[i].gsfTrack()->dxy() ;
ele_dzB[counter] = (*EleHandle)[i].gsfTrack()->dz(bs.position()) ;
ele_dz[counter] = (*EleHandle)[i].gsfTrack()->dz() ;
ele_dszB[counter] = (*EleHandle)[i].gsfTrack()->dsz(bs.position()) ;
ele_dsz[counter] = (*EleHandle)[i].gsfTrack()->dsz() ;
ele_dzPV[counter] = (*EleHandle)[i].gsfTrack()->dz(math::XYZPoint(vertexPosition));
ele_dzPV_error[counter] = (*EleHandle)[i].gsfTrack()->dzError();
ele_dxyPV[counter] = (*EleHandle)[i].gsfTrack()->dxy(math::XYZPoint(vertexPosition));
ele_dxyPV_error[counter] = (*EleHandle)[i].gsfTrack()->dxyError();
ele_dszPV[counter] = (*EleHandle)[i].gsfTrack()->dsz(math::XYZPoint(vertexPosition));
ele_dszPV_error[counter] = (*EleHandle)[i].gsfTrack()->dszError();
ele_track_x[counter] = (*EleHandle)[i].gsfTrack()->vx();
ele_track_y[counter] = (*EleHandle)[i].gsfTrack()->vy();
ele_track_z[counter] = (*EleHandle)[i].gsfTrack()->vz();
//} // if AOD
//std::cout << " FillEle Get Isolation variables " << std::endl;
// Isolation variables
ele_tkSumPt_dr03[counter] = (*EleHandle)[i].dr03TkSumPt() ;
ele_ecalRecHitSumEt_dr03[counter] = (*EleHandle)[i].dr03EcalRecHitSumEt() ;
ele_hcalDepth1TowerSumEt_dr03[counter] = (*EleHandle)[i].dr03HcalDepth1TowerSumEt() ;
ele_hcalDepth2TowerSumEt_dr03[counter] = (*EleHandle)[i].dr03HcalDepth2TowerSumEt() ;
ele_tkSumPt_dr04[counter] = (*EleHandle)[i].dr04TkSumPt() ;
ele_ecalRecHitSumEt_dr04[counter] = (*EleHandle)[i].dr04EcalRecHitSumEt() ;
ele_hcalDepth1TowerSumEt_dr04[counter] = (*EleHandle)[i].dr04HcalDepth1TowerSumEt() ;
ele_hcalDepth2TowerSumEt_dr04[counter] = (*EleHandle)[i].dr04HcalDepth2TowerSumEt() ;
//NEW HCAL Isolation
double HcalIso_00615Ring03_0 = (towerIso1_00615Ring03_0->getTowerEtSum(&((*EleHandle)[i])) +
towerIso2_00615Ring03_0->getTowerEtSum(&((*EleHandle)[i])) );
double HcalIso_005Ring03_0 = (towerIso1_005Ring03_0->getTowerEtSum(&((*EleHandle)[i])) +
towerIso2_005Ring03_0->getTowerEtSum(&((*EleHandle)[i])) );
double HcalIso_0Ring03_0 = (towerIso1_0Ring03_0->getTowerEtSum(&((*EleHandle)[i])) +
towerIso2_0Ring03_0->getTowerEtSum(&((*EleHandle)[i])) );
ele_hcalDepth1plus2TowerSumEt_00615dr03[counter] = HcalIso_00615Ring03_0;
ele_hcalDepth1plus2TowerSumEt_005dr03[counter] = HcalIso_005Ring03_0;
ele_hcalDepth1plus2TowerSumEt_0dr03[counter] = HcalIso_0Ring03_0;
//std::cout << " FillEle Get from HZZ isolation " << std::endl;
//from HZZ isolation
//SumPt
//if(!aod_){
//ele_tkSumPtTdrHzz_dr025[counter] = (*isoTkelemap)[electronEdmRef] ;
//ele_hcalSumEtTdrHzz_dr02[counter] = (*isoHadelemap)[electronEdmRef];
ele_tkSumPtEg4Hzz_dr03[counter] = (*egmisoTkelemap)[electronEdmRef];
ele_ecalSumEtEg4Hzz_dr03[counter] = (*egmisoEcalelemap)[electronEdmRef];
ele_hcalSumEtEg4Hzz_dr04[counter] = (*egmisoHcalelemap)[electronEdmRef];
//}
//SumPt/Pt normalization
double pT_new = (*EleHandle)[i].p4().Pt(); //* ele_newmom[counter] / (*EleHandle)[i].p4().P();
//if(!aod_){
//ele_tkSumPtoPtTdrHzz_dr025[counter] = (*isoTkelemap)[electronEdmRef]/pT_new;
//ele_hcalSumEtoPtTdrHzz_dr02[counter] = (*isoHadelemap)[electronEdmRef]/pT_new;
ele_tkSumPtoPtEg4Hzz_dr03[counter] = (*egmisoTkelemap)[electronEdmRef]/pT_new;
ele_ecalSumEtoPtEg4Hzz_dr03[counter] = (*egmisoEcalelemap)[electronEdmRef]/pT_new;
ele_hcalSumEtoPtEg4Hzz_dr04[counter] = (*egmisoHcalelemap)[electronEdmRef]/pT_new;
//}
// std::cout << " FillEle Conversion Removal " << std::endl;
ele_ECAL_fbrem[counter] = sclRef->phiWidth()/sclRef->etaWidth();
//cout<< "ecalfbrem = "<<ele_ECAL_fbrem[counter]<<" fbrem= "<<ele_fbrem[counter]<<endl;
// pflow combinaison
ele_PFcomb[counter] = 0.;
ele_PFcomb_Err[counter] = 0.;
std::vector<reco::PFCandidate> candidates = (*PfEleHandle.product());
for (std::vector<reco::PFCandidate>::iterator it = candidates.begin(); it != candidates.end(); ++it) {
reco::PFCandidate::ParticleType type = (*it).particleId();
// here you can ask for particle type, mu,e,gamma
if ( type == reco::PFCandidate::e) {
// gsfElectronRef pas encore impl�ment�e, utilisation de gsfTrackRef instead
//if (!(*it).gsfElectronRef().isNull() && ((*it).gsfElectronRef()->p4().e() == (*EleHandle)[i].p4().e())){
//FIXME !aod_ added for DATA
if (!(*it).gsfTrackRef().isNull() && ((*it).gsfTrackRef()->p() == (*EleHandle)[i].gsfTrack()->p())){
//std::cout << "[E-p combi] found corresponding Gsfelectron " << std::endl;
//std::cout << "[E-p combi] EG comb " << (*EleHandle)[i].p4().P() << " PF comb "<< (*it).energy()<< std::endl;
ele_PFcomb[counter] = (*it).energy();
}
}
}
//ele_PFcomb[counter] = (*EleHandle)[i].p4(GsfElectron::P4_PFLOW_COMBINATION).P();
//cout<<" PF comb = "<< ele_PFcomb[counter] << " EG comb= "<<(*EleHandle)[i].p4().P()<<endl;
ele_PFcomb_Err[counter] =(*EleHandle)[i].p4Error(GsfElectron::P4_PFLOW_COMBINATION);
//cout<<" PF comberr = "<< ele_PFcomb_Err[counter]<<endl;
if (!(*EleHandle)[i].pflowSuperCluster().isNull()) ele_PF_SCenergy[counter] = (*EleHandle)[i].pflowSuperCluster()->energy();
//cout<<" PF SC energy = "<< ele_PF_SCenergy[counter]<<endl;
ele_PF_SCenergy_Err[counter] = 0 ; //not implemented for the moment
// Conversion Removal
ele_isConversion[counter] = IsConv ((*EleHandle)[i]);
ConversionFinder convFinder;
// std::cout << " FillEle Conversion >=36X " << std::endl;
// Conversion >=36X
//if ( convFinder.isElFromConversion((*EleHandle)[i], tracks_h, evt_bField, 0.02, 0.02, 0.45)) ele_convFound[counter] = 1;
ConversionInfo convInfo = convFinder.getConversionInfo((*EleHandle)[i], tracks_h, evt_bField);
ele_conv_dist[counter] = convInfo.dist();
ele_conv_dcot[counter] = convInfo.dcot();
ele_convFound[counter] = 0;
// Conversion 36X
if ( convFinder.isFromConversion(convInfo, 0.02, 0.02) ) ele_convFound[counter] = 1;
//std::cout << " FillEle For L1 Trigger, Clemy's stuff " << std::endl;
// ------------------------------
// For L1 Trigger, Clemy's stuff
// ------------------------------
//LOOP MATCHING ON L1 trigger
//modif-alex l1 matching
//LOOP MATCHING ON L1 trigger
nTow=0;
nReg=0;
for(int icc = 0; icc < 50; ++icc) {
_ele_TTetaVect[counter][icc] = -999;
_ele_TTphiVect[counter][icc] = -999;
_ele_TTetVect[counter][icc] = 0.;
}
for(int icc = 0; icc < 10; ++icc) {
_ele_RCTetaVect[counter][icc] = -999;
_ele_RCTphiVect[counter][icc] = -999;
_ele_RCTetVect[counter][icc] = 0.;
_ele_RCTL1isoVect[counter][icc] = -999;
_ele_RCTL1nonisoVect[counter][icc] = -999;
_ele_RCTL1isoVect_M[counter][icc] = -999;
_ele_RCTL1nonisoVect_M[counter][icc] = -999;
}
for (reco::CaloCluster_iterator clus = sclRef->clustersBegin () ;
clus != sclRef->clustersEnd () ;
++clus){
std::vector<std::pair<DetId, float> > clusterDetIds = (*clus)->hitsAndFractions() ; //get these from the cluster
//loop on xtals in cluster
for (std::vector<std::pair<DetId, float> >::const_iterator detitr = clusterDetIds.begin () ;
detitr != clusterDetIds.end () ;
++detitr)
{
//Here I use the "find" on a digi collection... I have been warned...
if ( (detitr -> first).det () != DetId::Ecal)
{
std::cout << " det is " << (detitr -> first).det () << std::endl ;
continue ;
}
EcalRecHitCollection::const_iterator thishit;
EcalRecHit myhit;
EcalTrigTowerDetId towid;
float thetahit;
if ( (detitr -> first).subdetId () == EcalBarrel)
{
thishit = reducedRecHits->find ( (detitr -> first) ) ;
if (thishit == reducedRecHits->end ()) continue;
myhit = (*thishit) ;
EBDetId detid(thishit->id());
towid= detid.tower();
thetahit = theBarrelGeometry_->getGeometry((detitr -> first))->getPosition().theta();
}//barrel rechit
else {
if ( (detitr -> first).subdetId () == EcalEndcap)
{
thishit = reducedRecHits->find ( (detitr -> first) ) ;
if (thishit == reducedRecHits->end ()) continue;
myhit = (*thishit) ;
EEDetId detid(thishit->id());
towid= (*eTTmap_).towerOf(detid);
thetahit = theEndcapGeometry_->getGeometry((detitr -> first))->getPosition().theta();
}
else continue;
}//endcap rechit
//XTAL max
//if(myhit.energy() > rechitmax){
//rechitmax = myhit.energy();
//towidmax=towid;
//}
int iETA = towid.ieta();
int iPHI = towid.iphi();
int iReta = getGCTRegionEta(iETA);
int iRphi = getGCTRegionPhi(iPHI);
double iET = myhit.energy()*sin(thetahit);
bool newTow = true;
if(nTow>0) {
for (int iTow=0; iTow<nTow; ++iTow) {
if(_ele_TTetaVect[counter][iTow] == iETA && _ele_TTphiVect[counter][iTow] == iPHI) {
newTow = false;
_ele_TTetVect[counter][iTow] += iET;
}
}
}
if(newTow) {
_ele_TTetaVect[counter][nTow] = iETA;
_ele_TTphiVect[counter][nTow] = iPHI;
_ele_TTetVect[counter][nTow] = iET;
nTow++;
}
bool newReg = true;
if(nReg>0) {
for (int iReg=0; iReg<nReg; ++iReg) {
if(_ele_RCTetaVect[counter][iReg] == iReta && _ele_RCTphiVect[counter][iReg] == iRphi) {
newReg = false;
_ele_RCTetVect[counter][iReg] += iET;
}
}
}
if(newReg) {
_ele_RCTetaVect[counter][nReg] = iReta;
_ele_RCTphiVect[counter][nReg] = iRphi;
_ele_RCTetVect[counter][nReg] = iET;
// standard collection
for(int il1=0; il1<_trig_L1emIso_N; ++il1) {
if(_trig_L1emIso_iphi[il1] == iRphi && _trig_L1emIso_ieta[il1] == iReta) _ele_RCTL1isoVect[counter][nReg] = _trig_L1emIso_rank[il1];
}
for(int il1=0; il1<_trig_L1emNonIso_N; ++il1) {
if(_trig_L1emNonIso_iphi[il1] == iRphi && _trig_L1emNonIso_ieta[il1] == iReta) _ele_RCTL1nonisoVect[counter][nReg] = _trig_L1emNonIso_rank[il1];
}
// modified collection
for(int il1=0; il1<_trig_L1emIso_N_M; ++il1) {
if(_trig_L1emIso_iphi_M[il1] == iRphi && _trig_L1emIso_ieta_M[il1] == iReta) _ele_RCTL1isoVect_M[counter][nReg] = _trig_L1emIso_rank_M[il1];
}
for(int il1=0; il1<_trig_L1emNonIso_N_M; ++il1) {
if(_trig_L1emNonIso_iphi_M[il1] == iRphi && _trig_L1emNonIso_ieta_M[il1] == iReta) _ele_RCTL1nonisoVect_M[counter][nReg] = _trig_L1emNonIso_rank_M[il1];
}
nReg++;
} // if newReg
}//loop crystal
}//loop cluster
//double TTetmax = 0.;
//int iTTmax = -1.;
double TTetmax2 = 0.;
int iTTmax2 = -1.;
// std::cout<<"ele: "<<counter<<std::endl;
// std::cout<<"SC ET, eta, phi: "<<sclEt[counter]<<" "<<sclEta[counter]<<" "<<sclPhi[counter]<<std::endl;
// std::cout<<" towers"<<std::endl;
for (int iTow=0; iTow<nTow; ++iTow) {
bool nomaskTT = true;
//if(eTTetVect[counter][iTow] > 2) std::cout<<"TT ET, eta, phi: "<<eTTetVect[counter][iTow]<<" "<<eTTetaVect[counter][iTow]<<" "<<eTTphiVect[counter][iTow]<<std::endl;
for (ittpg=towerMap.begin();ittpg!=towerMap.end();++ittpg) {
if ((*ittpg).second > 0)
{
EcalTrigTowerDetId ttId((*ittpg).first);
if(ttId.ieta() == _ele_TTetaVect[counter][iTow] && ttId.iphi() == _ele_TTphiVect[counter][iTow]) {
//if(eTTetVect[counter][iTow] > 2) std::cout<<"*** masked ***"<<std::endl;
nomaskTT=false;
}
}
}//loop trigger towers
//if(_ele_eTTetVect[counter][iTow] > TTetmax) {
//iTTmax = iTow;
//TTetmax = _ele_eTTetVect[counter][iTow];
//}
if(nomaskTT && _ele_TTetVect[counter][iTow] > TTetmax2) {
iTTmax2 = iTow;
TTetmax2 = _ele_TTetVect[counter][iTow];
} // if nomask
} // for loop on Towers
// std::cout<<" regions"<<std::endl;
// for (int iReg=0; iReg<nReg; ++iReg) {
// if(_ele_eRCTetVect[counter][iReg] > 2) std::cout<<"RCT ET, eta, phi: "<<_ele_eRCTetVect[counter][iReg]<<" "<<_ele_eRCTetaVect[counter][iReg]<<" "<<_ele_eRCTphiVect[counter][iReg]<<std::endl;
// }
//int TTetamax = getGCTRegionEta(_ele_eTTetaVect[counter][iTTmax]);
//int TTphimax = getGCTRegionPhi(_ele_eTTphiVect[counter][iTTmax]);
//_ele_eleRCTeta[counter]=TTetamax;
//_ele_eleRCTphi[counter]=TTphimax;
//for(int il1=0; il1<_trig_L1emIso_N; ++il1) {
//if(_trig_L1emIso_iphi[il1] == TTphimax && _trig_L1emIso_ieta[il1] == TTetamax) _ele_eleRCTL1iso[counter] = _trig_L1emIso_rank[il1];
//}
//for(int il1=0; il1<_trig_L1emNonIso_N; ++il1) {
//if(_trig_L1emNonIso_iphi[il1] == TTphimax && _trig_L1emNonIso_ieta[il1] == TTetamax) _ele_eleRCTL1noniso[counter] = _trig_L1emNonIso_rank[il1];
//}
if(iTTmax2>=0) {
int TTetamax2 = getGCTRegionEta(_ele_TTetaVect[counter][iTTmax2]);
int TTphimax2 = getGCTRegionPhi(_ele_TTphiVect[counter][iTTmax2]);
_ele_RCTeta[counter] = TTetamax2;
_ele_RCTphi[counter] = TTphimax2;
// standard collection
for(int il1=0; il1<_trig_L1emIso_N; ++il1) {
if(_trig_L1emIso_iphi[il1] == TTphimax2 && _trig_L1emIso_ieta[il1] == TTetamax2) _ele_RCTL1iso[counter] = _trig_L1emIso_rank[il1];
}
for(int il1=0; il1<_trig_L1emNonIso_N; ++il1) {
if(_trig_L1emNonIso_iphi[il1] == TTphimax2 && _trig_L1emNonIso_ieta[il1] == TTetamax2) _ele_RCTL1noniso[counter] = _trig_L1emNonIso_rank[il1];
}
// modified collection
for(int il1=0; il1<_trig_L1emIso_N_M; ++il1) {
if(_trig_L1emIso_iphi_M[il1] == TTphimax2 && _trig_L1emIso_ieta_M[il1] == TTetamax2) _ele_RCTL1iso_M[counter] = _trig_L1emIso_rank_M[il1];
}
for(int il1=0; il1<_trig_L1emNonIso_N; ++il1) {
if(_trig_L1emNonIso_iphi_M[il1] == TTphimax2 && _trig_L1emNonIso_ieta_M[il1] == TTetamax2) _ele_RCTL1noniso_M[counter] = _trig_L1emNonIso_rank_M[il1];
}
} // if iTTmax2
// std::cout<<"main TT eta, phi: "<<eTTetaVect[counter][iTTmax]<<" "<<eTTphiVect[counter][iTTmax]<<std::endl;
// ---------------------------
// For Charge, Clemy's stuff
// ---------------------------
if(!aod_)
ele_expected_inner_hits[counter] = (*EleHandle)[i].gsfTrack()->trackerExpectedHitsInner().numberOfHits();
//tkIso03Rel[counter] = (*EleHandle)[i].dr03TkSumPt()/(*EleHandle)[i].p4().Pt();
//ecalIso03Rel[counter] = (*EleHandle)[i].dr03EcalRecHitSumEt()/(*EleHandle)[i].p4().Pt();
//hcalIso03Rel[counter] = (*EleHandle)[i].dr03HcalTowerSumEt()/(*EleHandle)[i].p4().Pt();
ele_sclNclus[counter] = (*EleHandle)[i].superCluster()->clustersSize();
ele_chargeGsfSC[counter] = 0;
ele_chargeGsfCtf[counter] = 0;
ele_chargeGsfCtfSC[counter] = 0;
if((*EleHandle)[i].isGsfScPixChargeConsistent()) ele_chargeGsfSC[counter]=1;
if((*EleHandle)[i].isGsfCtfChargeConsistent()) ele_chargeGsfCtf[counter]=1;
if((*EleHandle)[i].isGsfCtfScPixChargeConsistent()) ele_chargeGsfCtfSC[counter]=1;
if(!aod_)
ele_chargeQoverPGsfVtx[counter]=float((*EleHandle)[i].gsfTrack()->charge()) / ((*EleHandle)[i].trackMomentumAtVtx().R());
if(!(((*EleHandle)[i].closestCtfTrackRef()).isNull())) {
ele_CtfTrackExists[counter] = 1;
ele_chargeQoverPCtf[counter]=(*EleHandle)[i].closestCtfTrackRef()->qoverp();
}
else {
ele_CtfTrackExists[counter] = 0;
}
if(!aod_){
TrajectoryStateOnSurface innTSOS_ = mtsTransform_->innerStateOnSurface(*((*EleHandle)[i].gsfTrack()),
*(trackerHandle_.product()), theMagField.product());
if(innTSOS_.isValid()) {
GlobalPoint orig(bs.position().x(), bs.position().y(), bs.position().z()) ;
GlobalPoint scpos(sclRef->position().x(), sclRef->position().y(), sclRef->position().z()) ;
GlobalPoint scposCorr=scpos;
if(type_ == "DATA" && (*EleHandle)[i].isEE() && sclRef->eta() > 0)
scposCorr = GlobalPoint(sclRef->position().x()+0.52, sclRef->position().y()-0.81, sclRef->position().z()+0.81) ;
if(type_ == "DATA" && (*EleHandle)[i].isEE() && sclRef->eta() < 0)
scposCorr = GlobalPoint(sclRef->position().x()-0.02, sclRef->position().y()-0.83, sclRef->position().z()-0.94) ;
GlobalVector scvect(scpos-orig) ;
GlobalVector scvectCorr(scposCorr-orig) ;
GlobalPoint inntkpos = innTSOS_.globalPosition() ;
GlobalVector inntkvect = GlobalVector(inntkpos-orig) ;
ele_chargeDPhiInnEle[counter] = inntkvect.phi() - scvect.phi() ;
ele_chargeDPhiInnEleCorr[counter] = inntkvect.phi() - scvectCorr.phi() ;
} // is valid
}
//std::cout << " Spikes analysis " << std::endl;
// ------------------
// Spikes analysis
// ------------------
if ((*EleHandle)[i].isEB()) { /*spikes are in the barrel*/
const EcalRecHitCollection * reducedRecHits = 0 ;
reducedRecHits = reducedEBRecHits.product() ;
//seed cluster analysis
const edm::Ptr<reco::CaloCluster> & seedCluster = (*EleHandle)[i].superCluster()->seed();
std::pair<DetId, float> id = EcalClusterTools::getMaximum(seedCluster->hitsAndFractions(),reducedRecHits);
const EcalRecHit & rh = getRecHit(id.first,reducedRecHits);
int flag = rh.recoFlag();
if (flag == EcalRecHit::kOutOfTime)
ele_outOfTimeSeed[counter] = 1;
else
ele_outOfTimeSeed[counter] = 0;
//for42X
// int sev = EcalSeverityLevelAlgo::severityLevel(id.first,*reducedRecHits,*chStatus, 5., EcalSeverityLevelAlgo::kSwissCross,0.95) ;
int sev=sl->severityLevel(id.first,*reducedRecHits);
ele_severityLevelSeed[counter] = sev ;
int dummyFlag = 0;
int dummySev = 0;
for (reco::CaloCluster_iterator bc = (*EleHandle)[i].superCluster()->clustersBegin();
bc!=(*EleHandle)[i].superCluster()->clustersEnd();
++bc) {
if ( seedCluster==(*bc) ) continue;
std::pair<DetId, float> id = EcalClusterTools::getMaximum((*bc)->hitsAndFractions(),reducedRecHits);
const EcalRecHit & rh = getRecHit(id.first,reducedRecHits);
int flag = rh.recoFlag();
if (flag == EcalRecHit::kOutOfTime)
dummyFlag = 1 ;
//for42X
// int sev = EcalSeverityLevelAlgo::severityLevel(id.first,*reducedRecHits,*chStatus, 5., EcalSeverityLevelAlgo::kSwissCross,0.95);
int sev=sl->severityLevel(id.first,*reducedRecHits);
if (sev > dummySev)
dummySev = sev ;
}
ele_severityLevelClusters[counter] = dummySev ;
ele_outOfTimeClusters[counter] = dummyFlag ;
ele_e2overe9[counter] = E2overE9( id.first,*reducedRecHits,5,5, true, true);
// cout<<"e1/e9= "<<ele_e1[counter]/ele_e33[counter]<<" e2/e9= "<<ele_e2overe9[counter]<<endl;
}
else {
ele_e2overe9[counter] = 0;
ele_severityLevelSeed[counter] = 0 ;
ele_outOfTimeSeed[counter] = 0 ;
ele_severityLevelClusters[counter] = 0 ;
ele_outOfTimeClusters[counter] = 0 ;
}
//std::cout << " Ambigous Tracks " << std::endl;
// Ambigous Tracks
ele_ambiguousGsfTracks[counter] = (*EleHandle)[i].ambiguousGsfTracksSize() ;
reco::GsfTrackRefVector::const_iterator firstTrack = (*EleHandle)[i].ambiguousGsfTracksBegin() ;
reco::GsfTrackRefVector::const_iterator lastTrack = (*EleHandle)[i].ambiguousGsfTracksEnd() ;
int jj = 0 ;
if ( ele_ambiguousGsfTracks[counter] < 5 )
for (reco::GsfTrackRefVector::const_iterator myTrack = firstTrack ;
myTrack < lastTrack ;
++myTrack)
{
ele_ambiguousGsfTracksdxy[counter][jj] = (*myTrack)->dxy() ;
ele_ambiguousGsfTracksdz[counter][jj] = (*myTrack)->dz() ;
ele_ambiguousGsfTracksdxyB[counter][jj]= (*myTrack)->dxy(bs.position()) ;
ele_ambiguousGsfTracksdzB[counter][jj] = (*myTrack)->dz(bs.position()) ;
++jj;
} // for loop on tracks
if(!aod_){
edm::RefToBase<TrajectorySeed> seed = (*EleHandle)[i].gsfTrack()->extra()->seedRef();
reco::ElectronSeedRef MyS = seed.castTo<reco::ElectronSeedRef>();
ele_seedSubdet2[counter] = int(MyS->subDet2());
if(fabs(MyS->dPhi2Pos()) < 100.) ele_seedDphi2Pos[counter] = double(MyS->dPhi2Pos());
if(fabs(MyS->dRz2Pos()) < 100.) ele_seedDrz2Pos[counter] = double(MyS->dRz2Pos());
if(fabs(MyS->dPhi2()) < 100.) ele_seedDphi2Neg[counter] = double(MyS->dPhi2());
if(fabs(MyS->dRz2()) < 100.) ele_seedDrz2Neg[counter] = double(MyS->dRz2());
ele_seedSubdet1[counter] = int(MyS->subDet1());
if(fabs(MyS->dPhi1Pos()) < 100.) ele_seedDphi1Pos[counter] = double(MyS->dPhi1Pos());
if(fabs(MyS->dRz1Pos()) < 100.) ele_seedDrz1Pos[counter] = double(MyS->dRz1Pos());
if(fabs(MyS->dPhi1()) < 100.) ele_seedDphi1Neg[counter] = double(MyS->dPhi1());
if(fabs(MyS->dRz1()) < 100.) ele_seedDrz1Neg[counter] = double(MyS->dRz1());
}
if(type_ == "MC"){
// bool okeleFound_conv = false;
// bool okeleFound = false;
double eleOkRatio = 999999.;
double eleOkRatioE = 999999.;
double eleOkRatioG = 999999.;
double eleOkRatioH = 999999.;
int idPDG = 999999 ;
int idPDG_ele = 999999 ;
int idPDG_mother_conv = 999999;
int idPDG_pho = 999999 ;
int idPDG_had = 999999 ;
HepMC::FourVector MC_chosenEle_PoP_loc;
HepMC::FourVector MC_chosenPho_PoP_loc;
HepMC::FourVector MC_chosenHad_PoP_loc;
HepMC::FourVector MC_closest_DR_loc;
if(aod_ == false){
HepMC::GenParticle* mother = 0; // for particle gun
for (HepMC::GenEvent::particle_const_iterator partIter = MCEvt->particles_begin();
partIter != MCEvt->particles_end(); ++partIter) {
// for (HepMC::GenEvent::vertex_const_iterator vertIter = MCEvt->vertices_begin();
// vertIter != MCEvt->vertices_end(); ++vertIter) {
// HepMC::FourVector momentum = (*partIter)->momentum();
int idTmpPDG = (*partIter)->pdg_id();
//MC particle
genPc = (*partIter);
pAssSim = genPc->momentum();
//reco electron
float eta = (*EleHandle)[i].eta();
float phi = (*EleHandle)[i].phi();
float p = (*EleHandle)[i].p();
//matching conditions
dphi = phi-pAssSim.phi();
if (fabs(dphi)>CLHEP::pi)
dphi = dphi < 0? (CLHEP::twopi) + dphi : dphi - CLHEP::twopi;
deta = eta - pAssSim.eta();
float deltaR = sqrt(pow(deta,2) + pow(dphi,2));
//standard
if ( deltaR < 0.15 ){ // in the cone
if ( pAssSim.perp() > 1.5 ){
double tmpeleRatio = p/pAssSim.t();
if (idTmpPDG == 11 || idTmpPDG == -11 ){ // looking at Ele
if ( fabs(tmpeleRatio-1) < fabs(eleOkRatioE-1) ) { //best p/p
eleOkRatioE = tmpeleRatio;
idPDG_ele = idTmpPDG;
//for particle gun
//idPDG_mother_conv = (*((*partIter)->production_vertex()->particles_begin(HepMC::parents)))->pdg_id();
mother = *((*partIter)->production_vertex()->particles_begin(HepMC::parents));
if (mother!=0) idPDG_mother_conv = mother->pdg_id();
MC_chosenEle_PoP_loc = pAssSim;
} //best p/p conditions
} // looking at Ele
if(idTmpPDG == 22) { // looking at Gamma
if ( fabs(tmpeleRatio-1) < fabs(eleOkRatioG-1) ) {
eleOkRatioG = tmpeleRatio;
idPDG_pho = idTmpPDG;
MC_chosenPho_PoP_loc = pAssSim;
} //best p/p conditions
} // looking at E/Gamma
if(abs(idTmpPDG) == 211 || abs(idTmpPDG) == 321){ //looking at had
if ( fabs(tmpeleRatio-1) < fabs(eleOkRatioH-1) ) {
eleOkRatioH = tmpeleRatio;
idPDG_had = idTmpPDG;
MC_chosenHad_PoP_loc = pAssSim;
} //best p/p
} // looking at had
if ( fabs(tmpeleRatio-1) < fabs(eleOkRatio-1) ) { // overall best p/p ratio
eleOkRatio = tmpeleRatio;
idPDG = idTmpPDG;
MC_closest_DR_loc = pAssSim;
}
} // p > 1.5
} // deltaR
// }//end loop over vertex
//if (okeleFound) continue ;
}//end loop over MC particles
} // !AOD
else{
const Candidate * mother = 0; //for particlegun
for (reco::GenParticleCollection::const_iterator partIter = genParticlesColl->begin();
partIter != genParticlesColl->end(); ++partIter) {
// HepMC::FourVector momentum = (*partIter)->momentum();
int idTmpPDG = partIter->pdgId();
//MC particle
//genPc = (*partIter);
pAssSim = partIter->p4();
//reco electron
float eta = (*EleHandle)[i].eta();
float phi = (*EleHandle)[i].phi();
float p = (*EleHandle)[i].p();
//matching conditions
dphi = phi-pAssSim.phi();
if (fabs(dphi)>CLHEP::pi)
dphi = dphi < 0? (CLHEP::twopi) + dphi : dphi - CLHEP::twopi;
deta = eta - pAssSim.eta();
float deltaR = sqrt(pow(deta,2) + pow(dphi,2));
//standard
if ( deltaR < 0.15 ){ // in the cone
if ( pAssSim.perp() > 1.5 ){
double tmpeleRatio = p/pAssSim.t();
if (idTmpPDG == 11 || idTmpPDG == -11 ){ // looking at Ele
if ( fabs(tmpeleRatio-1) < fabs(eleOkRatioE-1) ) { //best p/p
eleOkRatioE = tmpeleRatio;
idPDG_ele = idTmpPDG;
//for particle gun
//idPDG_mother_conv = partIter->mother()->pdgId();
mother = partIter->mother();
if (mother!=0) idPDG_mother_conv = mother->pdgId();
MC_chosenEle_PoP_loc = pAssSim;
} //best p/p conditions
} // looking at Ele
if(idTmpPDG == 22) { // looking at Gamma
if ( fabs(tmpeleRatio-1) < fabs(eleOkRatioG-1) ) {
eleOkRatioG = tmpeleRatio;
idPDG_pho = idTmpPDG;
MC_chosenPho_PoP_loc = pAssSim;
} //best p/p conditions
} // looking at E/Gamma
if(abs(idTmpPDG) == 211 || abs(idTmpPDG) == 321){ //looking at had
if ( fabs(tmpeleRatio-1) < fabs(eleOkRatioH-1) ) {
eleOkRatioH = tmpeleRatio;
idPDG_had = idTmpPDG;
MC_chosenHad_PoP_loc = pAssSim;
} //best p/p
} // looking at had
if ( fabs(tmpeleRatio-1) < fabs(eleOkRatio-1) ) { // overall best p/p ratio
eleOkRatio = tmpeleRatio;
idPDG = idTmpPDG;
MC_closest_DR_loc = pAssSim;
}
} // p > 1.5
} // deltaR
// }//end loop over vertex
//if (okeleFound) continue ;
}//end loop over MC particles
}
//real electrons
if (idPDG_ele == 11 || idPDG_ele == -11) {
ele_isMCEle[counter] = 1;
ele_MC_chosenEle_PoP_px[counter] = MC_chosenEle_PoP_loc.px();
ele_MC_chosenEle_PoP_py[counter] = MC_chosenEle_PoP_loc.py();
ele_MC_chosenEle_PoP_pz[counter] = MC_chosenEle_PoP_loc.pz();
ele_MC_chosenEle_PoP_e[counter] = MC_chosenEle_PoP_loc.e();
ele_idPDGmother_MCEle[counter] = idPDG_mother_conv;
}
//photons (or pi0)
if(idPDG_pho == 22) {
ele_isMCPhoton[counter] = 1;
ele_MC_chosenPho_PoP_px[counter] = MC_chosenPho_PoP_loc.px();
ele_MC_chosenPho_PoP_py[counter] = MC_chosenPho_PoP_loc.py();
ele_MC_chosenPho_PoP_pz[counter] = MC_chosenPho_PoP_loc.pz();
ele_MC_chosenPho_PoP_e[counter] = MC_chosenPho_PoP_loc.e();
}
//hadrons
if(abs(idPDG_had) == 211 || abs(idPDG_had) == 321){
ele_isMCHadron[counter] = 1;
ele_MC_chosenHad_PoP_px[counter] = MC_chosenHad_PoP_loc.px();
ele_MC_chosenHad_PoP_py[counter] = MC_chosenHad_PoP_loc.py();
ele_MC_chosenHad_PoP_pz[counter] = MC_chosenHad_PoP_loc.pz();
ele_MC_chosenHad_PoP_e[counter] = MC_chosenHad_PoP_loc.e();
}
if(idPDG != 999999){
ele_idPDGMatch[counter] = idPDG;
ele_MC_closest_DR_px[counter] = MC_closest_DR_loc.px();
ele_MC_closest_DR_py[counter] = MC_closest_DR_loc.py();
ele_MC_closest_DR_pz[counter] = MC_closest_DR_loc.pz();
ele_MC_closest_DR_e[counter] = MC_closest_DR_loc.e();
}
//end standard MC matching
} // end if "MC"
++counter;
} // for loop on electrons
}
// ====================================================================================
void SimpleNtpleCustom::FillMuons(const edm::Event& iEvent, const edm::EventSetup& iSetup)
// ====================================================================================
{
// Beam spot
//Handle<reco::BeamSpot> beamSpotHandle;
//iEvent.getByLabel(InputTag("offlineBeamSpot"), beamSpotHandle);
edm::Handle<reco::BeamSpot> recoBeamSpotHandle ;
///iEvent.getByType(recoBeamSpotHandle) ;
const reco::BeamSpot bs = *recoBeamSpotHandle ;
// Muon Retrieving
Handle<View<reco::Muon> > MuonHandle;
iEvent.getByLabel(MuonTag_, MuonHandle);
TClonesArray &muons = *m_muons;
int mu_counter = 0;
// Get HZZ muon isolation
edm::Handle<edm::ValueMap<double> > isomuonmap;
// if(!aod_)
iEvent.getByLabel(MuonIso_HzzMapTag_, isomuonmap);
edm::Handle<edm::ValueMap<double> > isoTkmuonmap;
//if(!aod_)
iEvent.getByLabel(MuonIsoTk_HzzMapTag_, isoTkmuonmap);
edm::Handle<edm::ValueMap<double> > isoEcalmuonmap;
//if(!aod_)
iEvent.getByLabel(MuonIsoEcal_HzzMapTag_, isoEcalmuonmap);
edm::Handle<edm::ValueMap<double> > isoHcalmuonmap;
//if(!aod_)
iEvent.getByLabel(MuonIsoHcal_HzzMapTag_, isoHcalmuonmap);
// ----------------------------------------------
// Loop over Muons
// ----------------------------------------------
_muons_N = MuonHandle->size();
for (edm::View<reco::Muon>::const_iterator imuons=MuonHandle->begin(); imuons!=MuonHandle->end(); ++imuons) {
if(mu_counter>19) continue;
// 4-vector
//edm::Ref<reco::MuonCollection> muonEdmRef(MuonHandle,i);
setMomentum (myvector, imuons->p4());
new (muons[mu_counter]) TLorentzVector (myvector);
_muons_charge[mu_counter] = imuons->charge();
// Provenance
if(imuons->isTrackerMuon()) _muons_istracker[mu_counter] = 1;
if(imuons->isStandAloneMuon()) _muons_isstandalone[mu_counter] = 1;
if(imuons->isGlobalMuon()) _muons_isglobal[mu_counter] = 1;
// Quality cuts
reco::TrackRef gm = imuons->globalTrack();
reco::TrackRef tk = imuons->innerTrack();
if(imuons->isGlobalMuon()==1) {
_muons_dxy[mu_counter] = gm->dxy(bs.position()); //beamSpotHandle->position());
_muons_dz[mu_counter] = gm->dz(bs.position()); //beamSpotHandle->position());
_muons_dxyPV[mu_counter] = gm->dxy(math::XYZPoint(vertexPosition)); //beamSpotHandle->position());
_muons_dzPV[mu_counter] = gm->dz(math::XYZPoint(vertexPosition)); //beamSpotHandle->position());
_muons_normalizedChi2[mu_counter] = gm->normalizedChi2();
_muons_NmuonHits[mu_counter] = gm->hitPattern().numberOfValidMuonHits(); // muon hit matched to global fit
} // if Global Track
if(imuons->innerTrack().isAvailable()){
_muons_trkDxy[mu_counter]=imuons->innerTrack()->dxy();
_muons_trkDxyError[mu_counter]=imuons->innerTrack()->dxyError();
_muons_trkDxyB[mu_counter]=imuons->innerTrack()->dxy(bs.position()) ;
_muons_trkDz[mu_counter]=imuons->innerTrack()->dz();
_muons_trkDzError[mu_counter]=imuons->innerTrack()->dzError();
_muons_trkDzB[mu_counter]=imuons->innerTrack()->dz(bs.position());
_muons_trkChi2PerNdof[mu_counter]=imuons->innerTrack()->normalizedChi2();
_muons_trkCharge[mu_counter]=imuons->innerTrack()->charge();
_muons_trkNHits[mu_counter]=imuons->innerTrack()->numberOfValidHits();
_muons_trkNPixHits[mu_counter]=imuons->innerTrack()->hitPattern().numberOfValidPixelHits();
// Tracker muon properties
_muons_trkmuArbitration[mu_counter]=(muon::segmentCompatibility( (*imuons),reco::Muon::SegmentAndTrackArbitration));
_muons_trkmu2DCompatibilityLoose[mu_counter]=(muon::isGoodMuon( (*imuons),muon::TM2DCompatibilityLoose));
_muons_trkmu2DCompatibilityTight[mu_counter]=(muon::isGoodMuon( (*imuons),muon::TM2DCompatibilityTight));
_muons_trkmuOneStationLoose[mu_counter]=(muon::isGoodMuon( (*imuons),muon::TMOneStationLoose));
_muons_trkmuOneStationTight[mu_counter]=(muon::isGoodMuon( (*imuons),muon::TMOneStationTight));
_muons_trkmuLastStationLoose[mu_counter]=(muon::isGoodMuon( (*imuons),muon::TMLastStationLoose));
_muons_trkmuLastStationTight[mu_counter]=(muon::isGoodMuon( (*imuons),muon::TMLastStationTight));
_muons_trkmuOneStationAngLoose[mu_counter]=(muon::isGoodMuon( (*imuons),muon::TMOneStationAngLoose));
_muons_trkmuOneStationAngTight[mu_counter]=(muon::isGoodMuon( (*imuons),muon::TMOneStationAngTight));
_muons_trkmuLastStationAngLoose[mu_counter]=(muon::isGoodMuon( (*imuons),muon::TMLastStationAngLoose));
_muons_trkmuLastStationAngTight[mu_counter]=(muon::isGoodMuon( (*imuons),muon::TMLastStationAngTight));
_muons_trkmuLastStationOptimizedLowPtLoose[mu_counter]=(muon::isGoodMuon( (*imuons),muon::TMLastStationOptimizedLowPtLoose));
_muons_trkmuLastStationOptimizedLowPtTight[mu_counter]=(muon::isGoodMuon( (*imuons),muon::TMLastStationOptimizedLowPtTight));
}
if(imuons->isGlobalMuon()==1 || imuons->isTrackerMuon()==1) {
_muons_NtrackerHits[mu_counter] = tk->hitPattern().numberOfValidTrackerHits();
_muons_NpixelHits[mu_counter] = tk->hitPattern().numberOfValidPixelHits();
} // if Tracker track
_muons_Nmatches[mu_counter] = imuons->numberOfMatches(); // number of segments matched to muon stations
_muons_caloCompatibility[mu_counter] = imuons->caloCompatibility() ;
_muons_segmentCompatibility[mu_counter] = ( muon::segmentCompatibility ( (*imuons) , reco::Muon::SegmentAndTrackArbitration) ) ;
_muons_glbmuPromptTight[mu_counter] = ( muon::isGoodMuon( (*imuons) , muon::GlobalMuonPromptTight) );
// Isolation
_muons_nTkIsoR03[mu_counter] = imuons->isolationR03().nTracks;
_muons_nTkIsoR05[mu_counter] = imuons->isolationR05().nTracks;
_muons_tkIsoR03[mu_counter] = imuons->isolationR03().sumPt;
_muons_tkIsoR05[mu_counter] = imuons->isolationR05().sumPt;
_muons_emIsoR03[mu_counter] = imuons->isolationR03().emEt;
_muons_emIsoR05[mu_counter] = imuons->isolationR05().emEt;
_muons_hadIsoR03[mu_counter] = imuons->isolationR03().hadEt;
_muons_hadIsoR05[mu_counter] = imuons->isolationR05().hadEt;
// HZZ Isolation
//if(!aod_) {
edm::Ref<edm::View<reco::Muon> > muref(MuonHandle, mu_counter);
_muons_hzzIso[mu_counter] = (*isomuonmap)[muref];
_muons_hzzIsoTk[mu_counter] = (*isoTkmuonmap)[muref];
_muons_hzzIsoEcal[mu_counter] = (*isoEcalmuonmap)[muref];
_muons_hzzIsoHcal[mu_counter] = (*isoHcalmuonmap)[muref];
//} // if AOD
mu_counter++;
} // for loop on muons
if(mu_counter>9) { _muons_N = 10; cout << "Number of muons>100, muons_N set to 10" << endl;}
} // end of FillMuons
// ====================================================================================
void SimpleNtpleCustom::FillJets(const edm::Event& iEvent, const edm::EventSetup& iSetup)
// ====================================================================================
{
// --------------------------------------------------
// Calo Jets
// --------------------------------------------------
edm::Handle<reco::CaloJetCollection> calojets;
iEvent.getByLabel(CaloJetTag_, calojets);
_jets_calo_N = calojets->size();
int index_calo_jets = 0;
TClonesArray &jets_calo = *_m_jets_calo;
// Loop on Calo Jets
for ( reco::CaloJetCollection::const_iterator ijets=calojets->begin(); ijets!=calojets->end(); ijets++) {
if (index_calo_jets>99) continue;
setMomentum (myvector, ijets->p4());
new (jets_calo[index_calo_jets]) TLorentzVector(myvector);
// _jets_calo_E[index_calo_jets] = ijets->energy();
// _jets_calo_pT[index_calo_jets] = ijets->pt();
// _jets_calo_px[index_calo_jets] = ijets->px();
// _jets_calo_py[index_calo_jets] = ijets->py();
// _jets_calo_pz[index_calo_jets] = ijets->pz();
// _jets_calo_eta[index_calo_jets] = ijets->eta();
// _jets_calo_phi[index_calo_jets] = ijets->phi();
// // will add more variables in the future...
index_calo_jets++;
} // for loop on calo jets
if(index_calo_jets>99) { _jets_calo_N = 100; cout << "Number of calojets>100, RECO_CALOJETS_N set to 100" << endl;}
// --------------------------------------------------
// JPT Jets
// --------------------------------------------------
edm::Handle<reco::JPTJetCollection> jptjets;
iEvent.getByLabel(JPTJetTag_, jptjets);
_jets_jpt_N = jptjets->size();
int index_jpt_jets = 0;
TClonesArray &jets_jpt = *_m_jets_jpt;
// Loop on Jpt Jets
for ( reco::JPTJetCollection::const_iterator ijets=jptjets->begin(); ijets!=jptjets->end(); ijets++) {
if (index_jpt_jets>99) continue;
setMomentum (myvector, ijets->p4());
new (jets_jpt[index_jpt_jets]) TLorentzVector(myvector);
index_jpt_jets++;
} // for loop on jpt jets
if(index_jpt_jets>99) { _jets_jpt_N = 100; cout << "Number of jptjets>100, RECO_JPTJETS_N set to 100" << endl;}
// --------------------------------------------------
// PF Jets
// --------------------------------------------------
edm::Handle<reco::PFJetCollection> pfjets;
iEvent.getByLabel(PFJetTag_, pfjets);
_jets_pf_N = pfjets->size();
int index_pf_jets = 0;
TClonesArray &jets_pf = *_m_jets_pf;
// Loop on Pf Jets
for ( reco::PFJetCollection::const_iterator ijets=pfjets->begin(); ijets!=pfjets->end(); ijets++) {
if (index_pf_jets>99) continue;
setMomentum (myvector, ijets->p4());
new (jets_pf[index_pf_jets]) TLorentzVector(myvector);
jets_pf_chargedHadEFrac[index_pf_jets] = ijets->chargedHadronEnergyFraction ();
jets_pf_chargedEmEFrac[index_pf_jets] = ijets->chargedEmEnergyFraction ();
jets_pf_chargedMuEFrac[index_pf_jets] = ijets->chargedMuEnergyFraction ();
jets_pf_neutralHadEFrac[index_pf_jets] = ijets->neutralHadronEnergyFraction ();
jets_pf_neutralEmEFrac[index_pf_jets] = ijets->neutralEmEnergyFraction ();
jets_pf_PhotonEFrac[index_pf_jets] = ijets->photonEnergyFraction();
jets_pf_chargedHadMultiplicity[index_pf_jets] = ijets->chargedHadronMultiplicity ();
jets_pf_neutralHadMultiplicity[index_pf_jets] = ijets->neutralHadronMultiplicity ();
jets_pf_chargedMultiplicity[index_pf_jets] = ijets->chargedMultiplicity ();
jets_pf_neutralMultiplicity[index_pf_jets] = ijets->neutralMultiplicity ();
jets_pf_nConstituents[index_pf_jets] = ijets->nConstituents();
index_pf_jets++;
} // for loop on pf jets
if(index_pf_jets>99) { _jets_pf_N = 100; cout << "Number of pfjets>100, RECO_PFJETS_N set to 100" << endl;}
} // end of FillJets
// ====================================================================================
void SimpleNtpleCustom::FillSuperClusters(const edm::Event& iEvent, const edm::EventSetup& iSetup)
// ====================================================================================
{
//std::cout << "FillSuperClusters geometry " << std::endl;
// geometry
///const CaloGeometry * geometry;
unsigned long long cacheIDGeom = 0;
edm::ESHandle<CaloGeometry> theCaloGeom;
if(cacheIDGeom!=iSetup.get<CaloGeometryRecord>().cacheIdentifier()) {
cacheIDGeom = iSetup.get<CaloGeometryRecord>().cacheIdentifier();
iSetup.get<CaloGeometryRecord>().get(theCaloGeom);
}
///geometry = theCaloGeom.product() ;
//std::cout << "FillSuperClusters TPGTowerStatus " << std::endl;
// TPGTowerStatus
edm::ESHandle<EcalTPGTowerStatus> theEcalTPGTowerStatus_handle;
iSetup.get<EcalTPGTowerStatusRcd>().get(theEcalTPGTowerStatus_handle);
const EcalTPGTowerStatus * ecaltpgTowerStatus=theEcalTPGTowerStatus_handle.product();
const EcalTPGTowerStatusMap &towerMap=ecaltpgTowerStatus->getMap();
EcalTPGTowerStatusMapIterator it;
//for42x
unsigned long long cacheSevLevel = 0;
edm::ESHandle<EcalSeverityLevelAlgo> sevLevel;
if(cacheSevLevel != iSetup.get<EcalSeverityLevelAlgoRcd>().cacheIdentifier()){
cacheSevLevel = iSetup.get<EcalSeverityLevelAlgoRcd>().cacheIdentifier();
iSetup.get<EcalSeverityLevelAlgoRcd>().get(sevLevel);
}
const EcalSeverityLevelAlgo* sl=sevLevel.product();
// for H/E
//if (towerIso1_) delete towerIso1_ ; towerIso1_ = 0 ;
//if (towerIso2_) delete towerIso2_ ; towerIso2_ = 0 ;
//if (towersH_) delete towersH_ ; towersH_ = 0 ;
towersH_ = new edm::Handle<CaloTowerCollection>() ;
if (!iEvent.getByLabel(hcalTowers_,*towersH_))
{ edm::LogError("ElectronHcalHelper::readEvent")<<"failed to get the hcal towers of label "<<hcalTowers_ ; }
towerIso1_ = new EgammaTowerIsolation(hOverEConeSize_,0.,hOverEPtMin_,1,towersH_->product()) ;
towerIso2_ = new EgammaTowerIsolation(hOverEConeSize_,0.,hOverEPtMin_,2,towersH_->product()) ;
//std::cout << "FillSuperClusters Beam Spot " << std::endl;
// Beam Spot
edm::Handle<reco::BeamSpot> recoBeamSpotHandle ;
///iEvent.getByType(recoBeamSpotHandle) ;
const reco::BeamSpot bs = *recoBeamSpotHandle ;
//std::cout << "FillSuperClusters Isolation " << std::endl;
// Isolation
edm::Handle<TrackCollection> ctfTracksH;
iEvent.getByLabel("generalTracks", ctfTracksH); // ctfTracks_
// //get the tracks
// edm::Handle<reco::TrackCollection> tracks;
// e.getByLabel(trackInputTag_,tracks);
// if(!tracks.isValid()) {
// return;
// }
// const reco::TrackCollection* trackCollection = tracks.product();
//std::cout << "FillSuperClusters Iso Track " << std::endl;
// Iso Track
double isolationtrackThresholdB_Barrel = 0.7; //0.0;
double TrackConeOuterRadiusB_Barrel = 0.3;
double TrackConeInnerRadiusB_Barrel = 0.015; //0.04;
double isolationtrackEtaSliceB_Barrel = 0.015;
double longImpactParameterB_Barrel = 0.2;
double transImpactParameterB_Barrel = 999999.; //0.1;
double isolationtrackThresholdB_Endcap = 0.7; // 0.0
double TrackConeOuterRadiusB_Endcap = 0.3;
double TrackConeInnerRadiusB_Endcap = 0.015; //0.04;
double isolationtrackEtaSliceB_Endcap = 0.015;
double longImpactParameterB_Endcap = 0.2;
double transImpactParameterB_Endcap = 999999.; //0.1;
// double intRadiusBarrel = 0.015;
// double intRadiusEndcap = 0.015;
// double stripBarrel = 0.015;
// double stripEndcap = 0.015;
// double ptMin = 0.7;
// double maxVtxDist = 0.2;
// double drb = 999999999.; // maxDrbTk
//std::cout << "FillSuperClusters Iso HCAL " << std::endl;
// Iso HCAL
float egHcalIsoConeSizeOutSmall=0.3;
//float egHcalIsoConeSizeOutLarge=0.4;
int egHcalDepth1=1, egHcalDepth2=2; //float egHcalIsoConeSizeIn=intRadiusHcal_,egHcalIsoPtMin=etMinHcal_;
double egHcalIsoConeSizeIn = 0.15; //intRadiusHcal = 0.15;
double egHcalIsoPtMin = 0.0; // etMinHcal
EgammaTowerIsolation hadDepth1Isolation03(egHcalIsoConeSizeOutSmall,egHcalIsoConeSizeIn,egHcalIsoPtMin,egHcalDepth1,towersH_->product()) ;
EgammaTowerIsolation hadDepth2Isolation03(egHcalIsoConeSizeOutSmall,egHcalIsoConeSizeIn,egHcalIsoPtMin,egHcalDepth2,towersH_->product()) ;
//std::cout << "FillSuperClusters Iso ECAL " << std::endl;
// Iso ECAL
double egIsoConeSizeInBarrel = 3.0; // intRadiusEcalBarrel
double egIsoConeSizeInEndcap = 3.0; // intRadiusEcalEndcaps
double egIsoJurassicWidth = 1.5; // jurassicWidth
double egIsoPtMinBarrel = 0.0; // etMinBarrel
double egIsoEMinBarrel = 0.08; // eMinBarrel
double egIsoPtMinEndcap = 0.1; // etMinEndcaps
double egIsoEMinEndcap = 0.0; // egIsoEMinEndcaps
bool vetoClustered = false;
bool useNumCrystals = true;
// for SpikeRemoval -- not in 361p4 --
//int severityLevelCut = 4;
//double severityRecHitThreshold = 5.0;
//double spikeIdThreshold = 0.95;
//string spId = "kSwissCrossBordersIncluded"; // ikeIdString
//for42x
//EcalSeverityLevelAlgo::SpikeId spId = EcalSeverityLevelAlgo::kSwissCrossBordersIncluded;
//
//float extRadiusSmall=0.3, extRadiusLarge=0.4 ;
float egIsoConeSizeOutSmall=0.3; //, egIsoConeSizeOutLarge=0.4;
//std::cout << "FillSuperClusters EB SuperCluster " << std::endl;
// -----------------
// EB SuperCluster
// -----------------
// Retrieve SuperCluster
edm::Handle<reco::SuperClusterCollection> sc_coll_EB;
iEvent.getByLabel(edm::InputTag("correctedHybridSuperClusters"), sc_coll_EB);
//cout << " size EB = " << sc_coll_EB->size() << endl;
_sc_hybrid_N = sc_coll_EB->size();
int index_sc = 0;
//std::cout << "FillSuperClusters SpikeRemoval " << std::endl;
// Define stuff for SpikeRemoval
const CaloTopology * topology ;
///const EcalChannelStatus *chStatus ;
edm::Handle< EcalRecHitCollection > reducedEBRecHits;
edm::Handle< EcalRecHitCollection > reducedEERecHits;
unsigned long long cacheIDTopo_=0;
edm::ESHandle<CaloTopology> theCaloTopo;
if (cacheIDTopo_!=iSetup.get<CaloTopologyRecord>().cacheIdentifier()){
cacheIDTopo_=iSetup.get<CaloTopologyRecord>().cacheIdentifier();
iSetup.get<CaloTopologyRecord>().get(theCaloTopo);
}
topology = theCaloTopo.product() ;
edm::ESHandle<EcalChannelStatus> pChannelStatus;
iSetup.get<EcalChannelStatusRcd>().get(pChannelStatus);
///chStatus = pChannelStatus.product();
// reduced rechits
if(!aod_){
iEvent.getByLabel( edm::InputTag("ecalRecHit:EcalRecHitsEB"), reducedEBRecHits );
iEvent.getByLabel( edm::InputTag("ecalRecHit:EcalRecHitsEE"), reducedEERecHits );
}
else{
iEvent.getByLabel( edm::InputTag("reducedEcalRecHitsEB"), reducedEBRecHits );
iEvent.getByLabel( edm::InputTag("reducedEcalRecHitsEE"), reducedEERecHits );
}
// For L1
int nTow=0;
int nReg=0;
//std::cout << "FillSuperClusters Loop EB SuperCluster " << std::endl;
// --------------------------
// Loop on SuperClusters EB
// --------------------------
for( reco::SuperClusterCollection::const_iterator isc=sc_coll_EB->begin(); isc!=sc_coll_EB->end(); isc++) {
if(index_sc>24) continue;
double R = TMath::Sqrt(isc->x()*isc->x() + isc->y()*isc->y() +isc->z()*isc->z());
double Rt = TMath::Sqrt(isc->x()*isc->x() + isc->y()*isc->y());
_sc_hybrid_E[index_sc] = isc->energy();
_sc_hybrid_Et[index_sc] = isc->energy()*(Rt/R);
_sc_hybrid_Eta[index_sc] = isc->eta();
_sc_hybrid_Phi[index_sc] = isc->phi();
const EcalRecHitCollection * reducedRecHits = 0 ;
reducedRecHits = reducedEBRecHits.product() ;
//seed cluster analysis
const edm::Ptr<reco::CaloCluster> & seedCluster = isc->seed(); //(*EleHandle)[i].superCluster()->seed() ;
std::pair<DetId, float> id = EcalClusterTools::getMaximum(seedCluster->hitsAndFractions(),reducedRecHits);
const EcalRecHit & rh = getRecHit(id.first,reducedRecHits);
int flag = rh.recoFlag();
// Out of time
if (flag == EcalRecHit::kOutOfTime)
_sc_hybrid_outOfTimeSeed[index_sc] = 1;
else
_sc_hybrid_outOfTimeSeed[index_sc] = 0;
// Severity Level
//for42X
// int sev = EcalSeverityLevelAlgo::severityLevel(id.first,*reducedRecHits,*chStatus, 5., EcalSeverityLevelAlgo::kSwissCross,0.95) ;
int sev=sl->severityLevel(id.first,*reducedRecHits);
_sc_hybrid_severityLevelSeed[index_sc] = sev ;
// Old SpikeRemoval e1/e9
const reco::CaloCluster & seedCluster1 = *(isc->seed());
_sc_hybrid_e1[index_sc] = EcalClusterTools::eMax(seedCluster1,reducedRecHits) ;
_sc_hybrid_e33[index_sc] = EcalClusterTools::e3x3(seedCluster1,reducedRecHits,topology) ;
// H/E
reco::SuperCluster EmSCCand = *isc;
double HoE = towerIso1_->getTowerESum(&EmSCCand) + towerIso2_->getTowerESum(&EmSCCand) ;
HoE /= isc->energy() ;
_sc_hybrid_he[index_sc] = HoE ;
// SigmaIetaIeta
std::vector<float> localCovariances = EcalClusterTools::localCovariances(seedCluster1,reducedRecHits,topology) ;
_sc_hybrid_sigmaietaieta[index_sc] = sqrt(localCovariances[0]) ;
// std::cout << "FillSuperClusters Iso Track " << std::endl;
// Iso Track
//ElectronTkIsolation tkIsolation03(extRadiusSmall,intRadiusBarrel,intRadiusEndcap,stripBarrel,stripEndcap,ptMin,maxVtxDist,drb,ctfTracksH.product(),bs.position()) ;
//_sc_hybrid_tkSumPt_dr03[index_sc] = tkIsolation03.getPtTracks(isc);
// std::cout << "FillSuperClusters Iso HCAL " << std::endl;
// Iso HCAL
_sc_hybrid_hcalDepth1TowerSumEt_dr03[index_sc] = hadDepth1Isolation03.getTowerEtSum(&EmSCCand);
_sc_hybrid_hcalDepth2TowerSumEt_dr03[index_sc] = hadDepth2Isolation03.getTowerEtSum(&EmSCCand);
//std::cout << "FillSuperClusters Iso ECAL " << std::endl;
// Iso ECAL
EcalRecHitMetaCollection ecalBarrelHits(*reducedEBRecHits);
//for42x
// EgammaRecHitIsolation ecalBarrelIsol03(egIsoConeSizeOutSmall,egIsoConeSizeInBarrel,egIsoJurassicWidth,egIsoPtMinBarrel,egIsoEMinBarrel,theCaloGeom,&ecalBarrelHits,DetId::Ecal);
EgammaRecHitIsolation ecalBarrelIsol03(egIsoConeSizeOutSmall,egIsoConeSizeInBarrel,egIsoJurassicWidth,egIsoPtMinBarrel,egIsoEMinBarrel,theCaloGeom,&ecalBarrelHits,sevLevel.product(),DetId::Ecal);
ecalBarrelIsol03.setUseNumCrystals(useNumCrystals);
ecalBarrelIsol03.setVetoClustered(vetoClustered);
//for42x
// // !!! Spike Removal... not in 361p4! Have to add it after !!!
// ecalBarrelIsol03.doSpikeRemoval(reducedEBRecHits.product(),pChannelStatus.product(),severityLevelCut,severityRecHitThreshold,spId,spikeIdThreshold);
//std::cout << "FillSuperClusters ugly " << std::endl;
// ugly...
reco::RecoEcalCandidate * cand = new RecoEcalCandidate();
math::XYZPoint v(0,0,0); math::XYZVector p = isc->energy() * (isc->position() -v).unit(); double t = sqrt(0. + p.mag2());
cand->setCharge(0); cand->setVertex(v); cand->setP4(reco::Candidate::LorentzVector(p.x(), p.y(), p.z(), t));
const reco::SuperClusterRef sc_ref(sc_coll_EB, index_sc);
cand->setSuperCluster(sc_ref);
//reco::SuperClusterRef sc = cand->get<reco::SuperClusterRef>();
_sc_hybrid_ecalRecHitSumEt_dr03[index_sc] = ecalBarrelIsol03.getEtSum(cand);
// std::cout << "FillSuperClusters Track Isolation " << std::endl;
// Track Isolation
// Calculate hollow cone track isolation, CONE 0.3
reco::Photon * newPhoton = new Photon();
newPhoton->setVertex(v); newPhoton->setCharge(0); newPhoton->setMass(0);
newPhoton->setP4(reco::Candidate::LorentzVector(p.x(), p.y(), p.z(), isc->energy()));
//int ntrk_03 = 0.;
double trkiso_hc_03 = 0.;
///int counter = 0;
double ptSum = 0.;
PhotonTkIsolation phoIso(TrackConeOuterRadiusB_Barrel, //RCone,
TrackConeInnerRadiusB_Barrel, //RinnerCone,
isolationtrackEtaSliceB_Barrel, //etaSlice,
isolationtrackThresholdB_Barrel, //pTThresh,
longImpactParameterB_Barrel, //lip ,
transImpactParameterB_Barrel, //d0,
ctfTracksH.product(), //trackCollection, ctfTracksH.product(),bs.position()
bs.position()); //math::XYZPoint(vertexBeamSpot.x0(),vertexBeamSpot.y0(),vertexBeamSpot.z0()));
///counter = phoIso.getIso(newPhoton).first;
ptSum = phoIso.getIso(newPhoton).second;
trkiso_hc_03 = ptSum;
_sc_hybrid_trkiso_dr03[index_sc] = trkiso_hc_03;
// std::cout << "FillSuperClusters SC EB -- modif-alex l1 matching " << std::endl;
if(!aod_){
// ____________________________
// SC EB -- modif-alex l1 matching
// LOOP MATCHING ON L1 trigger
// ____________________________
nTow=0;
nReg=0;
for(int icc = 0; icc < 50; ++icc) {
_sc_hybrid_TTetaVect[index_sc][icc] = -999;
_sc_hybrid_TTphiVect[index_sc][icc] = -999;
_sc_hybrid_TTetVect[index_sc][icc] = 0.;
}
for(int icc = 0; icc < 10; ++icc) {
_sc_hybrid_RCTetaVect[index_sc][icc] = -999;
_sc_hybrid_RCTphiVect[index_sc][icc] = -999;
_sc_hybrid_RCTetVect[index_sc][icc] = 0.;
_sc_hybrid_RCTL1isoVect[index_sc][icc] = -999;
_sc_hybrid_RCTL1nonisoVect[index_sc][icc] = -999;
}
for (reco::CaloCluster_iterator clus = isc->clustersBegin () ;
clus != isc->clustersEnd () ;
++clus){
std::vector<std::pair<DetId, float> > clusterDetIds = (*clus)->hitsAndFractions() ; //get these from the cluster
//loop on xtals in cluster
for (std::vector<std::pair<DetId, float> >::const_iterator detitr = clusterDetIds.begin () ;
detitr != clusterDetIds.end () ;
++detitr)
{
//Here I use the "find" on a digi collection... I have been warned...
if ( (detitr -> first).det () != DetId::Ecal)
{
std::cout << " det is " << (detitr -> first).det () << std::endl ;
continue ;
}
EcalRecHitCollection::const_iterator thishit;
EcalRecHit myhit;
EcalTrigTowerDetId towid;
float thetahit;
//if ( (detitr -> first).subdetId () == EcalBarrel)
//{
thishit = reducedRecHits->find ( (detitr -> first) ) ;
if (thishit == reducedRecHits->end ()) continue;
myhit = (*thishit) ;
EBDetId detid(thishit->id());
towid= detid.tower();
thetahit = theBarrelGeometry_->getGeometry((detitr -> first))->getPosition().theta();
//}//barrel rechit
// else {
// if ( (detitr -> first).subdetId () == EcalEndcap)
// {
// thishit = reducedRecHits->find ( (detitr -> first) ) ;
// if (thishit == reducedRecHits->end ()) continue;
// myhit = (*thishit) ;
// EEDetId detid(thishit->id());
// towid= (*eTTmap_).towerOf(detid);
// thetahit = theEndcapGeometry_->getGeometry((detitr -> first))->getPosition().theta();
// }
// else continue;
// }//endcap rechit
int iETA=towid.ieta();
int iPHI=towid.iphi();
int iReta=getGCTRegionEta(iETA);
int iRphi=getGCTRegionPhi(iPHI);
double iET=myhit.energy()*sin(thetahit);
bool newTow = true;
if(nTow>0) {
for (int iTow=0; iTow<nTow; ++iTow) {
if(_sc_hybrid_TTetaVect[index_sc][iTow] == iETA && _sc_hybrid_TTphiVect[index_sc][iTow] == iPHI) {
newTow = false;
_sc_hybrid_TTetVect[index_sc][iTow] += iET;
}
}
} // if nTow>0
if(newTow) {
_sc_hybrid_TTetaVect[index_sc][nTow] = iETA;
_sc_hybrid_TTphiVect[index_sc][nTow] = iPHI;
_sc_hybrid_TTetVect[index_sc][nTow] = iET;
nTow++;
} // if newTow
bool newReg = true;
if(nReg>0) {
for (int iReg=0; iReg<nReg; ++iReg) {
if(_sc_hybrid_RCTetaVect[index_sc][iReg] == iReta && _sc_hybrid_RCTphiVect[index_sc][iReg] == iRphi) {
newReg = false;
_sc_hybrid_RCTetVect[index_sc][iReg] += iET;
}
}
} // if newreg>0
if(newReg) {
_sc_hybrid_RCTetaVect[index_sc][nReg] = iReta;
_sc_hybrid_RCTphiVect[index_sc][nReg] = iRphi;
_sc_hybrid_RCTetVect[index_sc][nReg] = iET;
for(int il1=0; il1<_trig_L1emIso_N; ++il1) {
if(_trig_L1emIso_iphi[il1] == iRphi && _trig_L1emIso_ieta[il1] == iReta) _sc_hybrid_RCTL1isoVect[index_sc][nReg] = _trig_L1emIso_rank[il1];
}
for(int il1=0; il1<_trig_L1emNonIso_N; ++il1) {
if(_trig_L1emNonIso_iphi[il1] == iRphi && _trig_L1emNonIso_ieta[il1] == iReta) _sc_hybrid_RCTL1nonisoVect[index_sc][nReg] = _trig_L1emNonIso_rank[il1];
}
nReg++;
} // if newReg
}//loop crystal
}//loop cluster
//double TTetmax=0.;
//int iTTmax=-1;
double TTetmax2 = 0.;
int iTTmax2 = -1;
for (int iTow=0; iTow<nTow; ++iTow) {
bool nomaskTT = true;
for (it=towerMap.begin();it!=towerMap.end();++it) {
if ((*it).second > 0) {
EcalTrigTowerDetId ttId((*it).first);
if(ttId.ieta() == _sc_hybrid_TTetaVect[index_sc][iTow] && ttId.iphi() == _sc_hybrid_TTphiVect[index_sc][iTow]) {
nomaskTT=false;
} // if ttId ieta
} // if ut.second>0
}//loop trigger towers
if(nomaskTT && _sc_hybrid_TTetVect[index_sc][iTow] > TTetmax2) {
iTTmax2 = iTow;
TTetmax2 = _sc_hybrid_TTetVect[index_sc][iTow];
} // if nomaskTT
} // for loop on towers
//int TTetamax = getGCTRegionEta(_sc_hybrid_TTetaVect[index_sc][iTTmax]);
//int TTphimax = getGCTRegionPhi(_sc_hybrid_TTphiVect[index_sc][iTTmax]);
//_sc_hybrid_RCTeta[index_sc]=TTetamax;
//_sc_hybrid_RCTphi[index_sc]=TTphimax;
//for(int il1=0; il1<_trig_L1emIso_N; ++il1) {
//if(_trig_L1emIso_iphi[il1] == TTphimax && _trig_L1emIso_ieta[il1] == TTetamax) _sc_hybrid_RCTL1iso[index_sc] = _trig_L1emIso_rank[il1];
//}
//for(int il1=0; il1<_trig_L1emNonIso_N; ++il1) {
//if(_trig_L1emNonIso_iphi[il1] == TTphimax && _trig_L1emNonIso_ieta[il1] == TTetamax) _sc_hybrid_RCTL1noniso[index_sc] = _trig_L1emNonIso_rank[il1];
//}
if(iTTmax2>=0) {
int TTetamax2 = getGCTRegionEta(_sc_hybrid_TTetaVect[index_sc][iTTmax2]);
int TTphimax2 = getGCTRegionPhi(_sc_hybrid_TTphiVect[index_sc][iTTmax2]);
_sc_hybrid_RCTeta[index_sc] = TTetamax2;
_sc_hybrid_RCTphi[index_sc] = TTphimax2;
for(int il1=0; il1<_trig_L1emIso_N; ++il1) {
if(_trig_L1emIso_iphi[il1] == TTphimax2 && _trig_L1emIso_ieta[il1] == TTetamax2) _sc_hybrid_RCTL1iso[index_sc] = _trig_L1emIso_rank[il1];
}
for(int il1=0; il1<_trig_L1emNonIso_N; ++il1) {
if(_trig_L1emNonIso_iphi[il1] == TTphimax2 && _trig_L1emNonIso_ieta[il1] == TTetamax2) _sc_hybrid_RCTL1noniso[index_sc] = _trig_L1emNonIso_rank[il1];
}
} // if iTTmax2
}//!AOD
index_sc++;
} // for loop on super clusters
if(index_sc>24) { _sc_hybrid_N = 25; cout << "Number of SuperCluster > 25; _sc_hybrid_N set to 25" << endl;}
// std::cout << "FillSuperClusters EE SuperCluster " << std::endl;
// -----------------
// EE SuperCluster
// -----------------
edm::Handle<reco::SuperClusterCollection> sc_coll_EE;
iEvent.getByLabel(edm::InputTag("correctedMulti5x5SuperClustersWithPreshower"), sc_coll_EE);
_sc_multi55_N = sc_coll_EE->size();
//cout << " size EE = " << sc_coll_EE->size() << endl;
int index_sc_EE = 0;
for( reco::SuperClusterCollection::const_iterator isc=sc_coll_EE->begin(); isc!=sc_coll_EE->end(); isc++) {
if(index_sc_EE>24) continue;
const EcalRecHitCollection * reducedRecHits = 0 ;
reducedRecHits = reducedEERecHits.product() ;
//seed cluster analysis
const reco::CaloCluster & seedCluster1 = *(isc->seed());
// 4-vector
double R = TMath::Sqrt(isc->x()*isc->x() + isc->y()*isc->y() +isc->z()*isc->z());
double Rt = TMath::Sqrt(isc->x()*isc->x() + isc->y()*isc->y());
_sc_multi55_E[index_sc_EE] = isc->energy();
_sc_multi55_Et[index_sc_EE] = isc->energy()*(Rt/R);
_sc_multi55_Eta[index_sc_EE] = isc->eta();
_sc_multi55_Phi[index_sc_EE] = isc->phi();
// H/E
reco::SuperCluster EmSCCand = *isc;
double HoE = towerIso1_->getTowerESum(&EmSCCand) + towerIso2_->getTowerESum(&EmSCCand) ;
HoE /= isc->energy() ;
_sc_multi55_he[index_sc_EE] = HoE;
// SigmaIetaIeta
std::vector<float> localCovariances = EcalClusterTools::localCovariances(seedCluster1,reducedRecHits,topology) ;
_sc_multi55_sigmaietaieta[index_sc_EE] = sqrt(localCovariances[0]) ;
// Iso HCAL
_sc_multi55_hcalDepth1TowerSumEt_dr03[index_sc_EE] = hadDepth1Isolation03.getTowerEtSum(&EmSCCand);
_sc_multi55_hcalDepth2TowerSumEt_dr03[index_sc_EE] = hadDepth2Isolation03.getTowerEtSum(&EmSCCand);
// Iso ECAL
EcalRecHitMetaCollection ecalEndcapHits(*reducedEERecHits);
//for42x
// EgammaRecHitIsolation ecalEndcapIsol03(egIsoConeSizeOutSmall,egIsoConeSizeInEndcap,egIsoJurassicWidth,egIsoPtMinEndcap,egIsoEMinEndcap,theCaloGeom,&ecalEndcapHits,DetId::Ecal);
EgammaRecHitIsolation ecalEndcapIsol03(egIsoConeSizeOutSmall,egIsoConeSizeInEndcap,egIsoJurassicWidth,egIsoPtMinEndcap,egIsoEMinEndcap,theCaloGeom,&ecalEndcapHits,sevLevel.product(),DetId::Ecal);
ecalEndcapIsol03.setUseNumCrystals(useNumCrystals);
ecalEndcapIsol03.setVetoClustered(vetoClustered);
// ugly...
reco::RecoEcalCandidate * cand = new RecoEcalCandidate();
math::XYZPoint v(0,0,0); math::XYZVector p = isc->energy() * (isc->position() -v).unit(); double t = sqrt(0. + p.mag2());
cand->setCharge(0); cand->setVertex(v);
cand->setP4(reco::Candidate::LorentzVector(p.x(), p.y(), p.z(), t));
const reco::SuperClusterRef sc_ref(sc_coll_EE, index_sc_EE);
cand->setSuperCluster(sc_ref);
_sc_multi55_ecalRecHitSumEt_dr03[index_sc_EE] = ecalEndcapIsol03.getEtSum(cand);
// Track Isolation
// Calculate hollow cone track isolation, CONE 0.3
reco::Photon * newPhoton = new Photon();
newPhoton->setVertex(v); newPhoton->setCharge(0); newPhoton->setMass(0);
newPhoton->setP4(reco::Candidate::LorentzVector(p.x(), p.y(), p.z(), isc->energy()));
//int ntrk_03 = 0.;
double trkiso_hc_03 = 0.;
///int counter = 0;
double ptSum = 0.;
PhotonTkIsolation phoIso(TrackConeOuterRadiusB_Endcap, //RCone,
TrackConeInnerRadiusB_Endcap, //RinnerCone,
isolationtrackEtaSliceB_Endcap, //etaSlice,
isolationtrackThresholdB_Endcap, //pTThresh,
longImpactParameterB_Endcap, //lip ,
transImpactParameterB_Endcap, //d0,
ctfTracksH.product(), //trackCollection, ctfTracksH.product(),bs.position()
bs.position()); //math::XYZPoint(vertexBeamSpot.x0(),vertexBeamSpot.y0(),vertexBeamSpot.z0()));
///counter = phoIso.getIso(newPhoton).first;
ptSum = phoIso.getIso(newPhoton).second;
trkiso_hc_03 = ptSum;
_sc_multi55_trkiso_dr03[index_sc_EE] = trkiso_hc_03;
//std::cout << "FillSuperClusters SC EE -- modif-alex l1 matching " << std::endl;
// ____________________________
// SC EE -- modif-alex l1 matching
// LOOP MATCHING ON L1 trigger
// ____________________________
if(!aod_){
nTow = 0;
nReg = 0;
for(int icc = 0; icc < 50; ++icc) {
_sc_multi55_TTetaVect[index_sc_EE][icc] = -999;
_sc_multi55_TTphiVect[index_sc_EE][icc] = -999;
_sc_multi55_TTetVect[index_sc_EE][icc] = 0.;
}
for(int icc = 0; icc < 10; ++icc) {
_sc_multi55_RCTetaVect[index_sc_EE][icc] = -999;
_sc_multi55_RCTphiVect[index_sc_EE][icc] = -999;
_sc_multi55_RCTetVect[index_sc_EE][icc] = 0.;
_sc_multi55_RCTL1isoVect[index_sc_EE][icc] = -999;
_sc_multi55_RCTL1nonisoVect[index_sc_EE][icc] = -999;
}
for (reco::CaloCluster_iterator clus = isc->clustersBegin () ;
clus != isc->clustersEnd () ;
++clus){
std::vector<std::pair<DetId, float> > clusterDetIds = (*clus)->hitsAndFractions() ; //get these from the cluster
//loop on xtals in cluster
for (std::vector<std::pair<DetId, float> >::const_iterator detitr = clusterDetIds.begin () ;
detitr != clusterDetIds.end () ;
++detitr)
{
//Here I use the "find" on a digi collection... I have been warned...
if ( (detitr -> first).det () != DetId::Ecal)
{
std::cout << " det is " << (detitr -> first).det () << std::endl ;
continue ;
}
EcalRecHitCollection::const_iterator thishit;
EcalRecHit myhit;
EcalTrigTowerDetId towid;
float thetahit;
// if ( (detitr -> first).subdetId () == EcalEndcap)
// {
thishit = reducedRecHits->find ( (detitr -> first) ) ;
if (thishit == reducedRecHits->end ()) continue;
myhit = (*thishit) ;
EEDetId detid(thishit->id());
towid= (*eTTmap_).towerOf(detid);
thetahit = theEndcapGeometry_->getGeometry((detitr -> first))->getPosition().theta();
// }
// else continue;
// }//endcap rechit
int iETA=towid.ieta();
int iPHI=towid.iphi();
int iReta=getGCTRegionEta(iETA);
int iRphi=getGCTRegionPhi(iPHI);
double iET=myhit.energy()*sin(thetahit);
bool newTow = true;
if(nTow>0) {
for (int iTow=0; iTow<nTow; ++iTow) {
if(_sc_multi55_TTetaVect[index_sc_EE][iTow] == iETA && _sc_multi55_TTphiVect[index_sc_EE][iTow] == iPHI) {
newTow = false;
_sc_multi55_TTetVect[index_sc_EE][iTow] += iET;
}
}
} // if nTow>0
if(newTow) {
_sc_multi55_TTetaVect[index_sc_EE][nTow] = iETA;
_sc_multi55_TTphiVect[index_sc_EE][nTow] = iPHI;
_sc_multi55_TTetVect[index_sc_EE][nTow] = iET;
nTow++;
} // if newTow
bool newReg = true;
if(nReg>0) {
for (int iReg=0; iReg<nReg; ++iReg) {
if(_sc_multi55_RCTetaVect[index_sc_EE][iReg] == iReta && _sc_multi55_RCTphiVect[index_sc_EE][iReg] == iRphi) {
newReg = false;
_sc_multi55_RCTetVect[index_sc_EE][iReg] += iET;
}
}
} // if newreg>0
if(newReg) {
_sc_multi55_RCTetaVect[index_sc_EE][nReg] = iReta;
_sc_multi55_RCTphiVect[index_sc_EE][nReg] = iRphi;
_sc_multi55_RCTetVect[index_sc_EE][nReg] = iET;
for(int il1=0; il1<_trig_L1emIso_N; ++il1) {
if(_trig_L1emIso_iphi[il1] == iRphi && _trig_L1emIso_ieta[il1] == iReta) _sc_multi55_RCTL1isoVect[index_sc_EE][nReg] = _trig_L1emIso_rank[il1];
}
for(int il1=0; il1<_trig_L1emNonIso_N; ++il1) {
if(_trig_L1emNonIso_iphi[il1] == iRphi && _trig_L1emNonIso_ieta[il1] == iReta) _sc_multi55_RCTL1nonisoVect[index_sc_EE][nReg] = _trig_L1emNonIso_rank[il1];
}
nReg++;
} // if newReg
}//loop crystal
}//loop cluster
//double TTetmax=0.;
//int iTTmax=-1;
double TTetmax2 = 0.;
int iTTmax2 = -1;
for (int iTow=0; iTow<nTow; ++iTow) {
bool nomaskTT = true;
for (it=towerMap.begin();it!=towerMap.end();++it) {
if ((*it).second > 0) {
EcalTrigTowerDetId ttId((*it).first);
if(ttId.ieta() == _sc_multi55_TTetaVect[index_sc_EE][iTow] && ttId.iphi() == _sc_multi55_TTphiVect[index_sc_EE][iTow]) {
nomaskTT=false;
} // if ttId ieta
} // if ut.second>0
}//loop trigger towers
if(nomaskTT && _sc_multi55_TTetVect[index_sc_EE][iTow] > TTetmax2) {
iTTmax2 = iTow;
TTetmax2 = _sc_multi55_TTetVect[index_sc_EE][iTow];
} // if nomaskTT
} // for loop on towers
if(iTTmax2>=0) {
int TTetamax2 = getGCTRegionEta(_sc_multi55_TTetaVect[index_sc_EE][iTTmax2]);
int TTphimax2 = getGCTRegionPhi(_sc_multi55_TTphiVect[index_sc_EE][iTTmax2]);
_sc_multi55_RCTeta[index_sc_EE] = TTetamax2;
_sc_multi55_RCTphi[index_sc_EE] = TTphimax2;
for(int il1=0; il1<_trig_L1emIso_N; ++il1) {
if(_trig_L1emIso_iphi[il1] == TTphimax2 && _trig_L1emIso_ieta[il1] == TTetamax2) _sc_multi55_RCTL1iso[index_sc_EE] = _trig_L1emIso_rank[il1];
}
for(int il1=0; il1<_trig_L1emNonIso_N; ++il1) {
if(_trig_L1emNonIso_iphi[il1] == TTphimax2 && _trig_L1emNonIso_ieta[il1] == TTetamax2) _sc_multi55_RCTL1noniso[index_sc_EE] = _trig_L1emNonIso_rank[il1];
}
} // if iTTmax2
}
index_sc_EE++;
} // for loop on super clusters
if(index_sc_EE>24) { _sc_multi55_N = 25; cout << "Number of SuperCluster > 25; _sc_multi55_N set to 25" << endl;}
} // FillSuperCluster
// ====================================================================================
void SimpleNtpleCustom::FillTruth(const edm::Event& iEvent, const edm::EventSetup& iSetup)
// ====================================================================================
{
// get gen particle candidates
edm::Handle<GenParticleCollection> genCandidatesCollection;
iEvent.getByLabel("genParticles", genCandidatesCollection);
TClonesArray &MC_gen_V = *_m_MC_gen_V;
TClonesArray &MC_gen_leptons = *_m_MC_gen_leptons;
int counter = 0;
int counter_daughters = 0;
// ----------------------------
// Loop on particles
// ----------------------------
for( GenParticleCollection::const_iterator p = genCandidatesCollection->begin();p != genCandidatesCollection->end(); ++ p ) {
if (p->pdgId() == 23 || fabs(p->pdgId())==24) {
if(p->status()==3) {
// Fill truth W,Z
setMomentum (myvector,p->p4());
new (MC_gen_V[counter]) TLorentzVector(myvector);
_MC_gen_V_pdgid[counter] = p->pdgId();
//size_t nfirstdau = p->numberOfDaughters();
// Loop on daughters
for(unsigned int i=0;i<p->numberOfDaughters();i++) {
bool islep = false;
if(fabs(p->daughter(i)->pdgId())==11) { _MC_flavor[counter] = 0; islep=true;} // electron
if(fabs(p->daughter(i)->pdgId())==13) { _MC_flavor[counter] = 1; islep=true;} // muon
if(fabs(p->daughter(i)->pdgId())==15) { _MC_flavor[counter] = 2; islep=true;} // taus
if(islep) { // p->daughter(i)->status()==1) { ?!
setMomentum(myvector, p->daughter(i)->p4());
new (MC_gen_leptons[counter_daughters]) TLorentzVector(myvector);
_MC_gen_leptons_pdgid[counter_daughters] = p->daughter(i)->pdgId();
counter_daughters++;
} // if is lepton
} // for loop on daughters
counter++;
} // if status stable
} // if W or Z
} // for loop on particles
} // end of FillTruth
// ====================================================================================
void SimpleNtpleCustom::FillTipLipIp(const edm::Event& iEvent, const edm::EventSetup& iSetup)
// ====================================================================================
{
//Get the B-field
edm::ESHandle<MagneticField> magneticField;
iSetup.get<IdealMagneticFieldRecord>().get(magneticField);
//Get Beam Spot
edm::Handle<reco::BeamSpot> recoBeamSpotHandle ;
///iEvent.getByType(recoBeamSpotHandle) ;
const reco::BeamSpot bs = *recoBeamSpotHandle ;
GlobalPoint BSVertex(bs.position().x(),bs.position().y(),bs.position().z());
Basic3DVector<double> BSVertexErr(bs.x0Error(),bs.y0Error(),bs.z0Error());
reco::Vertex::Point BSp(bs.position().x(),bs.position().y(),bs.position().z());
reco::Vertex::Error BSe;
BSe(0,0) = bs.x0Error()*bs.x0Error();
BSe(1,1) = bs.y0Error()*bs.y0Error();
BSe(2,2) = bs.z0Error()*bs.z0Error();
reco::Vertex BSprimVertex = reco::Vertex(BSp,BSe,1,1,1);
// get the track builder
ESHandle<TransientTrackBuilder> trackBuilder;
iSetup.get<TransientTrackRecord>().get("TransientTrackBuilder",trackBuilder);
//Get Vertices
edm::Handle<reco::VertexCollection> recoPrimaryVertexCollection;
iEvent.getByLabel(VerticesTag_,recoPrimaryVertexCollection);
reco::Vertex primVertex;
bool pvfound = (recoPrimaryVertexCollection->size() != 0);
if (pvfound)
{
PrimaryVertexSorter pvs;
vector<reco::Vertex> sortedList = pvs.sortedList(*(recoPrimaryVertexCollection.product()) );
primVertex = (sortedList.front());
} else {
//creating a dummy PV
reco::Vertex::Point p(0,0,0);
reco::Vertex::Error e;
e(0,0) = 0.0015*0.0015;
e(1,1) = 0.0015*0.0015;
e(2,2) = 15.*15.;
primVertex = reco::Vertex(p,e,1,1,1);
}
//
GlobalPoint pVertex(primVertex.position().x(),primVertex.position().y(),primVertex.position().z());
Basic3DVector<double> pVertexErr(primVertex.xError(),primVertex.yError(),primVertex.zError());
//--------------- for propagation
// electrons:
//const MultiTrajectoryStateTransform *theMtsTransform = new MultiTrajectoryStateTransform;
const GsfPropagatorAdapter *theGeomPropBw = new GsfPropagatorAdapter(AnalyticalPropagator(magneticField.product(),oppositeToMomentum));
// muons:
//const TrajectoryStateTransform *theTransform = new TrajectoryStateTransform;
Propagator *thePropBw = new AnalyticalPropagator(magneticField.product(),oppositeToMomentum);
//
//edm::ESHandle<TrackerGeometry> trackerHandle;
//iSetup.get<TrackerDigiGeometryRecord>().get(trackerHandle);
//
float muTip,muLip,muSTip,muSLip,muTipSignif,muLipSignif,muSignificance3D,muValue3D,muError3D ;
float eleTip,eleLip,eleSTip,eleSLip,eleTipSignif,eleLipSignif,eleSignificance3D,eleValue3D,eleError3D;
//
//
//--track refs
TrackRef mutrack;
GsfTrackRef eletrack;
//--transient tracks
reco::TransientTrack mutranstrack;
reco::TransientTrack eletranstrack;
// =============================================================================
// Muons
// =============================================================================
Handle<View<reco::Muon> > MuonHandle;
iEvent.getByLabel(MuonTag_, MuonHandle);
unsigned int indexmu=0;
for (edm::View<reco::Muon>::const_iterator muCand = MuonHandle->begin(); muCand != MuonHandle->end(); ++muCand){
if (indexmu>19) continue;
mutrack = muCand->get<TrackRef>();
if (mutrack.isNull()){
cout <<"tracker trackref is null since muon is STA" << endl;
mutrack=muCand->get<TrackRef,reco::StandAloneMuonTag>();
}
mutranstrack = trackBuilder->build( mutrack );
TrajectoryStateOnSurface innerMuTSOS;
if (useBeamSpot_==true){
//innerMuTSOS = mutranstrack.stateOnSurface(BSVertex);
innerMuTSOS = IPTools::transverseExtrapolate(mutranstrack.impactPointState(), BSVertex, mutranstrack.field());
}
else {
//innerMuTSOS = mutranstrack.stateOnSurface(pVertex);
innerMuTSOS = IPTools::transverseExtrapolate(mutranstrack.impactPointState(), pVertex, mutranstrack.field());
}
// get initial TSOS (now protected against STA muons):
//if (!mutrack.isNull())
//{
//innerMuTSOS = theTransform->innerStateOnSurface(*mutrack, *trackerHandle.product(), magneticField.product());
//}
if (innerMuTSOS.isValid() && !mutrack.isNull() ){
//-- get propagated the inner TSOS to the PV:
TrajectoryStateOnSurface vtxMuTSOS;
if (useBeamSpot_==true){
vtxMuTSOS = TransverseImpactPointExtrapolator(*thePropBw).extrapolate(innerMuTSOS,BSVertex);
}
else {
vtxMuTSOS = TransverseImpactPointExtrapolator(*thePropBw).extrapolate(innerMuTSOS,pVertex);
}
//
if (!vtxMuTSOS.isValid()){
vtxMuTSOS = innerMuTSOS; //-protection for eventual failing extrapolation
}
//-- get the distances (transverse & longitudinal) between extrapolated position and PV position
GlobalPoint mimpP = vtxMuTSOS.globalPosition();
GlobalVector mdistV;
GlobalVector direction=vtxMuTSOS.globalDirection();
if (useBeamSpot_==true){
mdistV = mimpP - BSVertex;
}
else {
mdistV = mimpP - pVertex;
}
GlobalVector transverseIP(mdistV.x(),mdistV.y(),0.);
double ps = transverseIP.dot(direction);
muTip = mdistV.perp()*((ps!=0)?ps/abs(ps):1.); //signed by definition
muLip = mdistV.z(); // signed by definition
// compute full error calculation:
// - diagonal terms first:
AlgebraicSymMatrix33 mvtxerrM;
if (useBeamSpot_==true){
mvtxerrM(0,0) = BSVertexErr.x()*BSVertexErr.x();
mvtxerrM(1,1) = BSVertexErr.y()*BSVertexErr.y();
mvtxerrM(2,2) = BSVertexErr.z()*BSVertexErr.z();
}
else {
mvtxerrM(0,0) = pVertexErr.x()*pVertexErr.x();
mvtxerrM(1,1) = pVertexErr.y()*pVertexErr.y();
mvtxerrM(2,2) = pVertexErr.z()*pVertexErr.z();
}
// - off-diagonal terms:
AlgebraicSymMatrix33 merrorM = mvtxerrM + vtxMuTSOS.cartesianError().matrix().Sub<AlgebraicSymMatrix33>(0,0);
AlgebraicVector2 mjacobianTranV;
AlgebraicVector1 mjacobianLongV;
mjacobianTranV[0] = mdistV.x()/mdistV.perp();
mjacobianTranV[1] = mdistV.y()/mdistV.perp();
mjacobianLongV[0] = 1.;
//- errors:
muSTip = sqrt(ROOT::Math::Similarity(merrorM.Sub<AlgebraicSymMatrix22>(0,0),mjacobianTranV));
muSLip = sqrt(ROOT::Math::Similarity(merrorM.Sub<AlgebraicSymMatrix11>(2,2),mjacobianLongV));
//
muTipSignif=muTip/muSTip;
muLipSignif=muLip/muSLip;
muons_Tip[indexmu] = muTip ;
muons_Lip[indexmu] = muLip ;
muons_STip[indexmu] = muSTip ;
muons_SLip[indexmu] = muSLip ;
muons_TipSignif[indexmu] = muTipSignif ;
muons_LipSignif[indexmu] = muLipSignif ;
}
//if (mutrack.isNull()){
//mutrack=muCand->get<TrackRef,reco::StandAloneMuonTag>();
//}
//mutranstrack = trackBuilder->build( mutrack ) ;
// -------------
// 3DIP & SIP
// -------------
TrajectoryStateOnSurface muTSOS;
if (useBeamSpot_==true){
//muTSOS = mutranstrack.stateOnSurface(BSVertex);
muTSOS = IPTools::transverseExtrapolate(mutranstrack.impactPointState(), BSVertex, mutranstrack.field());
}
else {
//muTSOS = mutranstrack.stateOnSurface(pVertex);
muTSOS = IPTools::transverseExtrapolate(mutranstrack.impactPointState(), pVertex, mutranstrack.field());
}
if (muTSOS.isValid()){
std::pair<bool,Measurement1D> muIPpair;
if (useBeamSpot_==true){
//muIPpair = IPTools::signedImpactParameter3D(mutranstrack, muTSOS.globalDirection(), BSprimVertex);
muIPpair = IPTools::absoluteImpactParameter3D(mutranstrack, BSprimVertex);
}
else {
//muIPpair = IPTools::signedImpactParameter3D(mutranstrack, muTSOS.globalDirection(), primVertex);
muIPpair = IPTools::absoluteImpactParameter3D(mutranstrack, primVertex);
}
if (muIPpair.first){
muSignificance3D = muIPpair.second.significance();
muValue3D = muIPpair.second.value();
muError3D = muIPpair.second.error();
muons_Significance3D[indexmu] = muSignificance3D ;
muons_Value3D[indexmu] = muValue3D ;
muons_Error3D[indexmu] = muError3D ;
}
}
++indexmu;
} //-- muon loop closed
// =============================================================================
// Electrons
// =============================================================================
Handle<edm::View<GsfElectron> > eleCandidates;
iEvent.getByLabel(EleTag_.label(),eleCandidates);
unsigned int indexele=0;
for (edm::View<reco::GsfElectron>::const_iterator eleCand = eleCandidates->begin(); eleCand != eleCandidates->end(); ++eleCand){
if (indexele>9) continue;
eletrack = eleCand->get<GsfTrackRef>();
eletranstrack = trackBuilder->build( eletrack ) ;
//
// get initial TSOS:
TrajectoryStateOnSurface innerTSOS;
if (useBeamSpot_==true){
//innerTSOS = eletranstrack.stateOnSurface(BSVertex);
innerTSOS = IPTools::transverseExtrapolate(eletranstrack.impactPointState(), BSVertex, eletranstrack.field());
}
else {
//innerTSOS = eletranstrack.stateOnSurface(pVertex);
innerTSOS = IPTools::transverseExtrapolate(eletranstrack.impactPointState(), pVertex, eletranstrack.field());
}
//= theMtsTransform->innerStateOnSurface(*eletrack, *trackerHandle.product(), magneticField.product());
//
if (innerTSOS.isValid()){
//-- get propagated the inner TSOS to the PV:
TrajectoryStateOnSurface vtxTSOS;
if (useBeamSpot_==true){
vtxTSOS = TransverseImpactPointExtrapolator(*theGeomPropBw).extrapolate(innerTSOS,BSVertex);
}
else {
vtxTSOS = TransverseImpactPointExtrapolator(*theGeomPropBw).extrapolate(innerTSOS,pVertex);
}
//
if (!vtxTSOS.isValid()){
vtxTSOS = innerTSOS; //-protection for eventual failing extrapolation
}
//
//-- get the distances (transverse & longitudinal) between extrapolated position and PV position
GlobalPoint impP = vtxTSOS.globalPosition();
GlobalVector distV;
GlobalVector direction=vtxTSOS.globalDirection();
if (useBeamSpot_==true){
distV = impP - BSVertex;
}
else {
distV = impP - pVertex;
}
GlobalVector transverseIPele(distV.x(),distV.y(),0.);
double psele = transverseIPele.dot(direction);
eleTip = distV.perp()*((psele!=0)?psele/abs(psele):1.); // signed by definition
eleLip = distV.z(); // signed by definition
// compute full error calculation:
// - diagonal terms first:
AlgebraicSymMatrix33 vtxerrM;
if (useBeamSpot_==true){
vtxerrM(0,0) = BSVertexErr.x()*BSVertexErr.x();
vtxerrM(1,1) = BSVertexErr.y()*BSVertexErr.y();
vtxerrM(2,2) = BSVertexErr.z()*BSVertexErr.z();
}
else {
vtxerrM(0,0) = pVertexErr.x()*pVertexErr.x();
vtxerrM(1,1) = pVertexErr.y()*pVertexErr.y();
vtxerrM(2,2) = pVertexErr.z()*pVertexErr.z();
}
// - off-diagonal terms:
AlgebraicSymMatrix33 errorM = vtxerrM + vtxTSOS.cartesianError().matrix().Sub<AlgebraicSymMatrix33>(0,0);
AlgebraicVector2 jacobianTranV;
AlgebraicVector1 jacobianLongV;
jacobianTranV[0] = distV.x()/distV.perp();
jacobianTranV[1] = distV.y()/distV.perp();
jacobianLongV[0] = 1.;
//- errors:
eleSTip = sqrt(ROOT::Math::Similarity(errorM.Sub<AlgebraicSymMatrix22>(0,0),jacobianTranV));
eleSLip = sqrt(ROOT::Math::Similarity(errorM.Sub<AlgebraicSymMatrix11>(2,2),jacobianLongV));
eleTipSignif=eleTip/eleSTip;
eleLipSignif=eleLip/eleSLip;
ele_Tip[indexele] = eleTip ;
ele_Lip[indexele] = eleLip ;
ele_STip[indexele] = eleSTip ;
ele_SLip[indexele] = eleSLip ;
ele_TipSignif[indexele] = eleTipSignif ;
ele_LipSignif[indexele] = eleLipSignif ;
}
// -----------------
// 3DIP & SIP
// -----------------
//eletranstrack = trackBuilder->build( eletrack ) ;
TrajectoryStateOnSurface eleTSOS;
if (useBeamSpot_==true){
//eleTSOS = eletranstrack.stateOnSurface(BSVertex);
eleTSOS = IPTools::transverseExtrapolate(eletranstrack.impactPointState(), BSVertex, eletranstrack.field());
}
else {
//eleTSOS = eletranstrack.stateOnSurface(pVertex);
eleTSOS = IPTools::transverseExtrapolate(eletranstrack.impactPointState(), pVertex, eletranstrack.field());
}
if (eleTSOS.isValid()){
std::pair<bool,Measurement1D> eleIPpair;
if (useBeamSpot_==true){
eleIPpair = IPTools::signedImpactParameter3D(eletranstrack, eleTSOS.globalDirection(), BSprimVertex);
}
else {
eleIPpair = IPTools::signedImpactParameter3D(eletranstrack, eleTSOS.globalDirection(), primVertex);
}
if (eleIPpair.first){
eleSignificance3D = eleIPpair.second.significance();
eleValue3D = eleIPpair.second.value();
eleError3D = eleIPpair.second.error();
ele_Significance3D[indexele] = eleSignificance3D ;
ele_Value3D[indexele] = eleValue3D ;
ele_Error3D[indexele] = eleError3D ;
}
}
//
++indexele;
} //-- ele loop closed
}
// ====================================================================================
void SimpleNtpleCustom::Init()
// ====================================================================================
{
ele_N = 0;
ele_nSeed = 0;
nEvent = 0;
nRun = 0;
nLumi = 0;
//Pile-up
_PU_N = 0;
_PU_rho = 0.;
_PU_sigma = 0.;
// Skim
_skim_is1lepton = 0;
_skim_is2leptons = 0;
_skim_is3leptons = 0;
// Vertices
_vtx_N = 0;
for(int iv=0;iv<15;iv++) {
_vtx_normalizedChi2[iv] = 0.;
_vtx_ndof[iv] = 0.;
_vtx_nTracks[iv] = 0.;
_vtx_d0[iv] = 0.;
_vtx_x[iv] = 0.;
_vtx_y[iv] = 0.;
_vtx_z[iv] = 0.;
}// for loop on vertices
// Beam Spot
BS_x = 0.;
BS_y = 0.;
BS_z = 0.;
BS_dz = 0.;
BS_dxdz = 0.;
BS_dydz = 0.;
BS_bw_x = 0.;
BS_bw_y = 0.;
// MC truth
_MC_pthat = 0.;
_MC_flavor[0] = 10;
_MC_flavor[1] = 10;
// Trigger towers
_trig_tower_N = 0;
_trig_tower_N_modif = 0;
_trig_tower_N_emul = 0;
for(int i=0 ; i<4032 ; i++) {
_trig_tower_ieta[i]=-999;
_trig_tower_iphi[i]=-999;
_trig_tower_adc[i]=-999;
_trig_tower_sFGVB[i]=-999;
_trig_tower_ieta_modif[i]=-999;
_trig_tower_iphi_modif[i]=-999;
_trig_tower_adc_modif[i]=-999;
_trig_tower_sFGVB_modif[i]=-999;
_trig_tower_ieta_emul[i]=-999;
_trig_tower_iphi_emul[i]=-999;
for(int j=0 ; j<5 ; j++) {
_trig_tower_adc_emul[i][j]=-999;
_trig_tower_sFGVB_emul[i][j]=-999;
}
}
// Trigger
for (int i=0;i<250;i++)
trig_hltInfo[i] = 0;
trig_isUnbiased = 0 ;
trig_isPhoton10 = 0;
trig_isPhoton15 = 0;
trig_isL1SingleEG2 = 0;
trig_isL1SingleEG5 = 0;
trig_isL1SingleEG8 = 0;
trig_isEle10_LW = 0;
trig_isEle15_LW = 0;
_trig_isEleHLTpath = 0;
_trig_isMuonHLTpath = 0;
// L1
_trig_L1emIso_N = 0;
_trig_L1emNonIso_N = 0;
_trig_L1emIso_N_M = 0;
_trig_L1emNonIso_N_M = 0;
_trig_preL1emIso_N = 0;
_trig_preL1emNonIso_N = 0;
_trig_postL1emIso_N = 0;
_trig_postL1emNonIso_N = 0;
// max set to 4
for(int il1=0;il1<4;il1++) {
// Used by Clemy
_trig_L1emIso_ieta[il1] = 0;
_trig_L1emIso_iphi[il1] = 0;
_trig_L1emIso_rank[il1] = 0;
_trig_L1emIso_ieta_M[il1] = 0;
_trig_L1emIso_iphi_M[il1] = 0;
_trig_L1emIso_rank_M[il1] = 0;
// From Trigger twiki
_trig_L1emIso_eta[il1] = 0.;
_trig_L1emIso_phi[il1] = 0.;
_trig_L1emIso_energy[il1] = 0.;
_trig_L1emIso_et[il1] = 0.;
_trig_L1emIso_eta_M[il1] = 0.;
_trig_L1emIso_phi_M[il1] = 0.;
_trig_L1emIso_energy_M[il1] = 0.;
_trig_L1emIso_et_M[il1] = 0.;
// Used by Clemy
_trig_L1emNonIso_ieta[il1] = 0;
_trig_L1emNonIso_iphi[il1] = 0;
_trig_L1emNonIso_rank[il1] = 0;
_trig_L1emNonIso_ieta_M[il1] = 0;
_trig_L1emNonIso_iphi_M[il1] = 0;
_trig_L1emNonIso_rank_M[il1] = 0;
// From Trigger twiki
_trig_L1emNonIso_eta[il1] = 0.;
_trig_L1emNonIso_phi[il1] = 0.;
_trig_L1emNonIso_energy[il1] = 0.;
_trig_L1emNonIso_et[il1] = 0.;
_trig_L1emNonIso_eta_M[il1] = 0.;
_trig_L1emNonIso_phi_M[il1] = 0.;
_trig_L1emNonIso_energy_M[il1] = 0.;
_trig_L1emNonIso_et_M[il1] = 0.;
// Used by Clemy
_trig_preL1emIso_ieta[il1] = 0;
_trig_preL1emIso_iphi[il1] = 0;
_trig_preL1emIso_rank[il1] = 0;
// Used by Clemy
_trig_preL1emNonIso_ieta[il1] = 0;
_trig_preL1emNonIso_iphi[il1] = 0;
_trig_preL1emNonIso_rank[il1] = 0;
// Used by Clemy
_trig_postL1emIso_ieta[il1] = 0;
_trig_postL1emIso_iphi[il1] = 0;
_trig_postL1emIso_rank[il1] = 0;
// Used by Clemy
_trig_postL1emNonIso_ieta[il1] = 0;
_trig_postL1emNonIso_iphi[il1] = 0;
_trig_postL1emNonIso_rank[il1] = 0;
} // for loop on L1 cand
// HLT
_trig_HLT_N = 0;
for(int ihlt=0;ihlt<20;ihlt++) {
_trig_HLT_eta[ihlt] = 0.;
_trig_HLT_phi[ihlt] = 0.;
_trig_HLT_energy[ihlt] = 0.;
_trig_HLT_pt[ihlt] = 0.;
_trig_HLT_name[ihlt] = -1;
} // for loop on hlt
// Masked Towers
_trig_nMaskedRCT=0;
_trig_nMaskedCh=0;
for (int ii=0;ii<100;ii++)
{
_trig_iMaskedRCTeta[ii] = -999;
_trig_iMaskedRCTphi[ii] = -999;
_trig_iMaskedRCTcrate[ii] = -999;
_trig_iMaskedTTeta[ii] = -999;
_trig_iMaskedTTphi[ii] = -999;
}//loop masks
for (int ii=0;ii<10;ii++)
{
_ele_RCTeta[ii] = -999;
_ele_RCTphi[ii] = -999;
_ele_RCTL1iso[ii] = -999;
_ele_RCTL1noniso[ii] = -999;
_ele_RCTL1iso_M[ii] = -999;
_ele_RCTL1noniso_M[ii] = -999;
}//loop electron rct region
// Offline Electrons
for (int i=0;i<10;i++)
{
ele_MC_chosenEle_PoP_px[i] = 0.;
ele_MC_chosenEle_PoP_py[i] = 0.;
ele_MC_chosenEle_PoP_pz[i] = 0.;
ele_MC_chosenEle_PoP_e[i] = 0.;
ele_MC_chosenPho_PoP_px[i] = 0.;
ele_MC_chosenPho_PoP_py[i] = 0.;
ele_MC_chosenPho_PoP_pz[i] = 0.;
ele_MC_chosenPho_PoP_e[i] = 0.;
ele_MC_chosenHad_PoP_px[i] = 0.;
ele_MC_chosenHad_PoP_py[i] = 0.;
ele_MC_chosenHad_PoP_pz[i] = 0.;
ele_MC_chosenHad_PoP_e[i] = 0.;
ele_MC_closest_DR_px[i] = 0.;
ele_MC_closest_DR_py[i] = 0.;
ele_MC_closest_DR_pz[i] = 0.;
ele_MC_closest_DR_e[i] = 0.;
_ele_he_00615_0[i] = 0.; //
_ele_he_005_0[i] = 0.; //
_ele_he_005_1[i] = 0.; //HoE_005_1 ;
_ele_he_005_15[i] = 0.; //HoE_005_15 ;
_ele_he_01_0[i] = 0.; //HoE_01_0 ;
_ele_he_01_1[i] = 0.; //HoE_01_1 ;
_ele_he_01_15[i] = 0.; //HoE_01_15 ;
//_ele_he_015_0[i] 0.; //= HoE_01_0 ;
_ele_he_015_1[i] = 0.; //HoE_015_1 ;
_ele_he_015_15[i] = 0.; //HoE_015_15 ;
ele_eidVeryLoose[i] = 0.;
ele_eidLoose[i] = 0.;
ele_eidMedium[i] = 0.;
ele_eidTight[i] = 0.;
ele_eidSuperTight[i] = 0.;
ele_eidHyperTight1[i] = 0.;
ele_eidHyperTight2[i] = 0.;
ele_eidHyperTight3[i] = 0.;
ele_eidHyperTight4[i] = 0.;
ele_echarge[i]=0;
ele_he[i]=0;
ele_eseedpout[i]=0;
ele_ep[i]=0;
ele_eseedp[i]=0;
ele_eelepout[i]=0;
ele_pin_mode[i]=0;
ele_pout_mode[i]=0;
ele_pin_mean[i]=0;
ele_pout_mean[i]=0;
ele_calo_energy[i]=0;
ele_sclRawE[i]=0;
ele_sclE[i]=0;
ele_sclEt[i]=0;
ele_sclEta[i]=0;
ele_sclPhi[i]=0;
ele_sclX[i]=0;
ele_sclY[i]=0;
ele_sclZ[i]=0;
ele_sclErr[i]=0;
ele_sclErr_pos[i]=0;
ele_sclErr_neg[i]=0;
ele_trErr[i]=0;
ele_momErr[i]=0;
ele_newmomErr[i]=0;
ele_newmom[i]=0;
ele_tr_atcaloX[i]=0;
ele_tr_atcaloY[i]=0;
ele_tr_atcaloZ[i]=0;
ele_firsthit_X[i]=0;
ele_firsthit_Y[i]=0;
ele_firsthit_Z[i]=0;
ele_pTin_mode[i]=0;
ele_pTout_mode[i]=0;
ele_pTin_mean[i]=0; ;
ele_pTout_mean[i]=0;
ele_deltaetaseed[i]=0;
ele_deltaetaele[i]=0;
ele_deltaphiseed[i]=0;
ele_deltaphiele[i]=0;
ele_deltaetain[i]=0;
ele_deltaphiin[i]=0;
ele_sigmaietaieta[i]=0;
ele_sigmaetaeta[i]=0;
ele_e15[i]=0;
ele_e25max[i]=0;
ele_e55[i]=0;
ele_e1[i]=0;
ele_e33[i]=0;
ele_e2overe9[i]=0;
ele_fbrem[i]=0 ;
ele_mva[i]=0 ;
ele_isbarrel[i]=0;
ele_isendcap[i]=0;
ele_isEBetaGap[i]=0;
ele_isEBphiGap[i]=0;
ele_isEEdeeGap[i]=0;
ele_isEEringGap[i]=0;
ele_isecalDriven[i]=0;
ele_istrackerDriven[i]=0;
ele_eClass[i]=0;
ele_missing_hits[i]=0;
ele_dxy[i]=0 ;
ele_dz[i]=0 ;
ele_dsz[i]=0.;
ele_dxyB[i]=0 ;
ele_dzB[i]=0 ;
ele_dszB[i]=0 ;
ele_dxyPV[i]=0 ;
ele_dzPV[i]=0 ;
ele_dszPV[i]=0 ;
ele_dxyPV_error[i]=0 ;
ele_dzPV_error[i]=0 ;
ele_dszPV_error[i]=0 ;
ele_isConversion[i] = 0;
ele_convFound[i] = 0;
ele_conv_dist[i] = 0.;
ele_conv_dcot[i] = 0.;
ele_track_x[i] = 0.;
ele_track_y[i] = 0.;
ele_track_z[i] = 0.;
ele_lost_hits[i]=0;
ele_chi2_hits[i]=0;
ele_vertex_x[i]=0;
ele_vertex_y[i]=0;
ele_vertex_z[i]=0;
ele_tkSumPt_dr03[i]=0;
ele_ecalRecHitSumEt_dr03[i]=0;
ele_hcalDepth1TowerSumEt_dr03[i]=0;
ele_hcalDepth2TowerSumEt_dr03[i]=0;
ele_hcalDepth1plus2TowerSumEt_00615dr03[i]=0;
ele_hcalDepth1plus2TowerSumEt_005dr03[i]=0;
ele_hcalDepth1plus2TowerSumEt_0dr03[i]=0;
ele_tkSumPt_dr04[i]=0;
ele_ecalRecHitSumEt_dr04[i]=0;
ele_hcalDepth1TowerSumEt_dr04[i]=0;
ele_hcalDepth2TowerSumEt_dr04[i]=0;
ele_tkSumPtTdrHzz_dr025[i]=0;
ele_tkSumPtoPtTdrHzz_dr025[i]=0;
ele_hcalSumEtTdrHzz_dr02[i]=0;
ele_hcalSumEtoPtTdrHzz_dr02[i]=0;
ele_tkSumPtEg4Hzz_dr03[i]=0;
ele_ecalSumEtEg4Hzz_dr03[i]=0;
ele_hcalSumEtEg4Hzz_dr04[i]=0;
ele_tkSumPtoPtEg4Hzz_dr03[i]=0;
ele_ecalSumEtoPtEg4Hzz_dr03[i]=0;
ele_hcalSumEtoPtEg4Hzz_dr04[i]=0;
ele_ambiguousGsfTracks[i]=0;
ele_ECAL_fbrem[i]=0;
ele_PFcomb[i]=0;
ele_PFcomb_Err[i]=0;
ele_PF_SCenergy[i]=0;
ele_PF_SCenergy_Err[i]=0;
for (int j=0;j<5;j++)
{
ele_ambiguousGsfTracksdxy[i][j]=0 ;
ele_ambiguousGsfTracksdz[i][j]=0 ;
ele_ambiguousGsfTracksdxyB[i][j]=0 ;
ele_ambiguousGsfTracksdzB[i][j]=0 ;
}
ele_seedSubdet2[i] = -1;
ele_seedDphi2Pos[i] = -20.;
ele_seedDrz2Pos[i] = -20.;
ele_seedDphi2Neg[i] = -20.;
ele_seedDrz2Neg[i] = -20.;
ele_seedSubdet1[i] = -1;
ele_seedDphi1Pos[i] = -20.;
ele_seedDrz1Pos[i] = -20.;
ele_seedDphi1Neg[i] = -20.;
ele_seedDrz1Neg[i] = -20.;
ele_isMCEle[i] = 0;
ele_isMCPhoton[i] = 0;
ele_isMCHadron[i] = 0;
ele_isSIM[i] = 0;
ele_isSIMEle[i] = 0;
ele_idPDGMatch[i] = 0;
ele_idPDGmother_MCEle[i] = 0;
ele_idPDGMatchSim[i] = 0;
// Flags for Spike, etc...
ele_severityLevelSeed[i] = 0.;
ele_severityLevelClusters[i] = 0.;
ele_outOfTimeSeed[i] = 0.;
ele_outOfTimeClusters[i] = 0.;
ele_expected_inner_hits[i]=-1;
//tkIso03Rel[i]=-999.;
// ecalIso03Rel[i]=-999.;
//hcalIso03Rel[i]=-999.;
ele_sclNclus[i]=-1;
ele_chargeGsfSC[i]=-1;
ele_chargeGsfCtf[i]=-1;
ele_chargeGsfCtfSC[i]=-1;
ele_CtfTrackExists[i]=-1;
ele_chargeDPhiInnEle[i]=-999.;
ele_chargeDPhiInnEleCorr[i]=-999.;
ele_chargeQoverPGsfVtx[i]=-999.;
ele_chargeQoverPCtf[i]=-999.;
} // for loop on Ele
for(int i=0; i<100; ++i){
ele_SeedIsEcalDriven[i] = 0;
ele_SeedIsTrackerDriven[i] = 0;
ele_SeedSubdet1[i] = -1;
ele_SeedDphi1Pos[i] = -20.;
ele_SeedDrz1Pos[i] = -20.;
ele_SeedDphi1Neg[i] = -20.;
ele_SeedDrz1Neg[i] = -20.;
ele_SeedSubdet2[i] = -1;
ele_SeedDphi2Pos[i] = -20.;
ele_SeedDrz2Pos[i] = -20.;
ele_SeedDphi2Neg[i] = -20.;
ele_SeedDrz2Neg[i] = -20.;
} // ele Seed
// MET
_met_calo_et = 0.;
_met_calo_px = 0.;
_met_calo_py = 0.;
_met_calo_phi = 0.;
_met_calo_set = 0.;
_met_calo_sig = 0.;
_met_calomu_et = 0.;
_met_calomu_px = 0.;
_met_calomu_py = 0.;
_met_calomu_phi = 0.;
_met_calomu_set = 0.;
_met_calomu_sig = 0;
_met_tc_et = 0.;
_met_tc_px = 0.;
_met_tc_py = 0.;
_met_tc_phi = 0.;
_met_tc_set = 0.;
_met_tc_sig = 0.;
_met_pf_et = 0.;
_met_pf_px = 0.;
_met_pf_py = 0.;
_met_pf_phi = 0.;
_met_pf_set = 0.;
_met_pf_sig = 0.;
// Muons
_muons_N = 0;
for(int im=0;im<20;im++) {
_muons_charge[im] = 0;
// Provenance
_muons_istracker[im] = 0;
_muons_isstandalone[im] = 0;
_muons_isglobal[im] = 0;
// Quality cuts
_muons_dxy[im] = 0.;
_muons_dz[im] = 0.;
_muons_dxyPV[im] = 0.;
_muons_dzPV[im] = 0.;
_muons_normalizedChi2[im] = 0.;
_muons_NtrackerHits[im] = 0;
_muons_NpixelHits[im] = 0;
_muons_NmuonHits[im] = 0;
_muons_Nmatches[im] = 0;
// Isolation
_muons_nTkIsoR03[im] = 0;
_muons_nTkIsoR05[im] = 0;
_muons_tkIsoR03[im] = 0.;
_muons_tkIsoR05[im] = 0.;
_muons_emIsoR03[im] = 0.;
_muons_emIsoR05[im] = 0.;
_muons_hadIsoR03[im] = 0.;
_muons_hadIsoR05[im] = 0.;
_muons_trkDxy[im] = 0.;
_muons_trkDxyError[im] = 0.;
_muons_trkDxyB[im] = 0.;
_muons_trkDz[im] = 0.;
_muons_trkDzError[im] = 0.;
_muons_trkDzB[im] = 0.;
_muons_trkChi2PerNdof[im] = 0.;
_muons_trkCharge[im] = 0.;
_muons_trkNHits[im] = 0.;
_muons_trkNPixHits[im] = 0.;
_muons_trkmuArbitration[im] = 0.;
_muons_trkmu2DCompatibilityLoose[im] = 0.;
_muons_trkmu2DCompatibilityTight[im] = 0.;
_muons_trkmuOneStationLoose[im] = 0.;
_muons_trkmuOneStationTight[im] = 0.;
_muons_trkmuLastStationLoose[im] = 0.;
_muons_trkmuLastStationTight[im] = 0.;
_muons_trkmuOneStationAngLoose[im] = 0.;
_muons_trkmuOneStationAngTight[im] = 0.;
_muons_trkmuLastStationAngLoose[im] = 0.;
_muons_trkmuLastStationAngTight[im] = 0.;
_muons_trkmuLastStationOptimizedLowPtLoose[im] = 0.;
_muons_trkmuLastStationOptimizedLowPtTight[im] = 0.;
_muons_caloCompatibility[im] = 0.;
_muons_segmentCompatibility[im] = 0.;
_muons_glbmuPromptTight[im] = 0.;
_muons_hzzIso[im] = 0.;
_muons_hzzIsoTk[im] = 0.;
_muons_hzzIsoEcal[im] = 0.;
_muons_hzzIsoHcal[im] = 0.;
muons_Tip[im] = -999. ;
muons_Lip[im] = -999. ;
muons_STip[im] = -999. ;
muons_SLip[im] = -999. ;
muons_TipSignif[im] = -999. ;
muons_LipSignif[im] = -999. ;
muons_Significance3D[im] = -999. ;
muons_Value3D[im] = -999. ;
muons_Error3D[im] = -999. ;
} // for loop on muons
// Calo Jets
_jets_calo_N = 0;
// JPT Jets
_jets_jpt_N = 0;
// PF Jets
_jets_pf_N = 0;
for(int ipfjet=0;ipfjet<100;ipfjet++) {
jets_pf_chargedHadEFrac[ipfjet] = 0.;
jets_pf_chargedEmEFrac[ipfjet] = 0.;
jets_pf_chargedMuEFrac[ipfjet] = 0.;
jets_pf_neutralHadEFrac[ipfjet] = 0.;
jets_pf_neutralEmEFrac[ipfjet] = 0.;
jets_pf_PhotonEFrac[ipfjet] = 0.;
jets_pf_chargedHadMultiplicity[ipfjet] = 0;
jets_pf_neutralHadMultiplicity[ipfjet] = 0;
jets_pf_chargedMultiplicity[ipfjet] = 0;
jets_pf_neutralMultiplicity[ipfjet] = 0;
jets_pf_nConstituents[ipfjet] = 0;
} // for loop on PFjets
// SuperClusters
_sc_hybrid_N = 0;
for(int isc=0;isc<25;isc++) {
_sc_hybrid_E[isc] = 0.;
_sc_hybrid_Et[isc] = 0.;
_sc_hybrid_Eta[isc] = 0.;
_sc_hybrid_Phi[isc] = 0.;
_sc_hybrid_outOfTimeSeed[isc] = 0;
_sc_hybrid_severityLevelSeed[isc] = 0;
_sc_hybrid_e1[isc] = 0.;
_sc_hybrid_e33[isc] = 0.;
_sc_hybrid_he[isc] = -10.;
_sc_hybrid_sigmaietaieta[isc] = 0.;
_sc_hybrid_hcalDepth1TowerSumEt_dr03[isc] = 0.;
_sc_hybrid_hcalDepth2TowerSumEt_dr03[isc] = 0.;
_sc_hybrid_ecalRecHitSumEt_dr03[isc] = 0.;
_sc_hybrid_trkiso_dr03[isc] = 0.;
_sc_hybrid_RCTeta[isc]=-999;
_sc_hybrid_RCTphi[isc]=-999;
_sc_hybrid_RCTL1iso[isc] = -999;
_sc_hybrid_RCTL1noniso[isc] = -999;
for (int li=0;li<50;li++) {
_sc_hybrid_TTetaVect[isc][li]=-999;
_sc_hybrid_TTphiVect[isc][li]=-999;
_sc_hybrid_TTetVect[isc][li]=0.;
} // for loop on 50
for (int li=0;li<10;li++) {
_sc_hybrid_RCTetaVect[isc][li]=-999;
_sc_hybrid_RCTphiVect[isc][li]=-999;
_sc_hybrid_RCTetVect[isc][li]=0.;
_sc_hybrid_RCTL1isoVect[isc][li]=-999;
_sc_hybrid_RCTL1nonisoVect[isc][li]=-999;
} // for loop on 10
} // for loop on EB superclusters
_sc_multi55_N = 0;
for(int isc=0;isc<25;isc++) {
_sc_multi55_E[isc] = 0.;
_sc_multi55_Et[isc] = 0.;
_sc_multi55_Eta[isc] = 0.;
_sc_multi55_Phi[isc] = 0.;
_sc_multi55_he[isc] = -10.;
_sc_multi55_sigmaietaieta[isc] = 0.;
_sc_multi55_hcalDepth1TowerSumEt_dr03[isc] = 0.;
_sc_multi55_hcalDepth2TowerSumEt_dr03[isc] = 0.;
_sc_multi55_ecalRecHitSumEt_dr03[isc] = 0.;
_sc_multi55_trkiso_dr03[isc] = 0.;
_sc_multi55_RCTeta[isc]=-999;
_sc_multi55_RCTphi[isc]=-999;
_sc_multi55_RCTL1iso[isc] = -999;
_sc_multi55_RCTL1noniso[isc] = -999;
for (int li=0;li<50;li++) {
_sc_multi55_TTetaVect[isc][li]=-999;
_sc_multi55_TTphiVect[isc][li]=-999;
_sc_multi55_TTetVect[isc][li]=0.;
} // for loop on 50
for (int li=0;li<10;li++) {
_sc_multi55_RCTetaVect[isc][li]=-999;
_sc_multi55_RCTphiVect[isc][li]=-999;
_sc_multi55_RCTetVect[isc][li]=0.;
_sc_multi55_RCTL1isoVect[isc][li]=-999;
_sc_multi55_RCTL1nonisoVect[isc][li]=-999;
} // for loop on 10
} // for loop on EE superclusters
// Generated W, Z & leptons
for(int igen=0;igen<10;igen++) {
_MC_gen_V_pdgid[igen] = 0.;
_MC_gen_leptons_pdgid[igen] = 0.;
} // for loop on igen
for(int i=0;i<10;++i) {
ele_Tip[i] = -999. ;
ele_Lip[i] = -999. ;
ele_STip[i] = -999. ;
ele_SLip[i] = -999. ;
ele_TipSignif[i] = -999. ;
ele_LipSignif[i] = -999. ;
ele_Significance3D[i] = -999. ;
ele_Value3D[i] = -999. ;
ele_Error3D[i] = -999. ;
}
}
// ====================================================================================
void SimpleNtpleCustom::beginJob(const edm::ParameterSet& conf)
// ====================================================================================
{
//hcalhelper_ = new ElectronHcalHelper(conf);
//edm::Ref<reco::GsfElectronCollection> electronEdmRef(EleHandle,i);
// reco::SuperCluster EmSCCand1; // = *isc;
//reco::RecoEcalCandidate EcalCand;
//sc_struct = new converter::SuperClusterToCandidate(conf);
}
// ====================================================================================
void SimpleNtpleCustom::endJob() {}
// ====================================================================================
// ====================================================================================
void SimpleNtpleCustom::setMomentum (TLorentzVector &myvector, const LorentzVector & mom)
// ====================================================================================
{
myvector.SetPx (mom.Px());
myvector.SetPy (mom.Py());
myvector.SetPz (mom.Pz());
myvector.SetE (mom.E());
}
// ====================================================================================
bool SimpleNtpleCustom::IsConv (const reco::GsfElectron & eleRef) //edm::Ref<reco::GsfElectronCollection> eleRef)
// ====================================================================================
{
bool isAmbiguous = true, isNotFromPixel = true;
if (eleRef.ambiguousGsfTracksSize() == 0 ) {isAmbiguous = false;}
/*
TrackingRecHitRef rhit = eleRef->gsfTrack()->extra()->recHit(0);
int subdetId = rhit->geographicalId().subdetId();
int layerId = 0;
DetId id = rhit->geographicalId();
if (id.subdetId()==3) layerId = ((TIBDetId)(id)).layer();
if (id.subdetId()==5) layerId = ((TOBDetId)(id)).layer();
if (id.subdetId()==1) layerId = ((PXBDetId)(id)).layer();
if (id.subdetId()==4) layerId = ((TIDDetId)(id)).wheel();
if (id.subdetId()==6) layerId = ((TECDetId)(id)).wheel();
if (id.subdetId()==2) layerId = ((PXFDetId)(id)).disk();
//std::cout << " subdetIdele layerIdele = " << id.subdetId() << " " << layerId << std::endl;
if ((id.subdetId()==1 && layerId == 1) || (id.subdetId()==2 && layerId == 1)) {isNotFromPixel = false;}
*/
int mishits = eleRef.gsfTrack()->trackerExpectedHitsInner().numberOfHits();
//std::cout << "mishits = " << mishits << std::endl;
if (mishits == 0){isNotFromPixel = false;}
//
bool is_conversion = false;
if(isAmbiguous || isNotFromPixel) is_conversion = true;
return is_conversion;
}
// ====================================================================================
const EcalRecHit SimpleNtpleCustom::getRecHit(DetId id, const EcalRecHitCollection *recHits)
// ====================================================================================
{
if ( id == DetId(0) ) {
return EcalRecHit();
} else {
EcalRecHitCollection::const_iterator it = recHits->find( id );
if ( it != recHits->end() ) {
return (*it);
} else {
//throw cms::Exception("EcalRecHitNotFound") << "The recHit corresponding to the DetId" << id.rawId() << " not found in the EcalRecHitCollection";
// the recHit is not in the collection (hopefully zero suppressed)
return EcalRecHit();
}
}
return EcalRecHit();
}
//modif-alex
//GETTING RCT regions
// ====================================================================================
int SimpleNtpleCustom::getGCTRegionPhi(int ttphi)
// ====================================================================================
{
int gctphi=0;
gctphi = (ttphi+1)/4;
if(ttphi<=2) gctphi=0;
if(ttphi>=71) gctphi=0;
return gctphi;
}
// ====================================================================================
int SimpleNtpleCustom::getGCTRegionEta(int tteta)
// ====================================================================================
{
int gcteta = 0;
if(tteta>0) gcteta = (tteta-1)/4 + 11;
else if(tteta<0) gcteta = (tteta+1)/4 + 10;
return gcteta;
}
/*
// ===============================================================================================
// unified acces to isolations
std::pair<int,double> ElectronTkIsolation::getIso(const reco::GsfElectron* electron) const
// ===============================================================================================
{
int counter =0 ;
double ptSum =0.;
//Take the electron track
reco::GsfTrackRef tmpTrack = electron->gsfTrack() ;
math::XYZVector tmpElectronMomentumAtVtx = (*tmpTrack).momentum () ;
double tmpElectronEtaAtVertex = (*tmpTrack).eta();
for ( reco::TrackCollection::const_iterator itrTr = (*trackCollection_).begin() ;
itrTr != (*trackCollection_).end() ;
++itrTr ) {
math::XYZVector tmpTrackMomentumAtVtx = (*itrTr).momentum () ;
double this_pt = (*itrTr).pt();
if ( this_pt < ptLow_ ) continue;
double dzCut = 0;
switch( dzOption_ ) {
case egammaisolation::EgammaTrackSelector::dz : dzCut = fabs( (*itrTr).dz() - (*tmpTrack).dz() ); break;
case egammaisolation::EgammaTrackSelector::vz : dzCut = fabs( (*itrTr).vz() - (*tmpTrack).vz() ); break;
case egammaisolation::EgammaTrackSelector::bs : dzCut = fabs( (*itrTr).dz(beamPoint_) - (*tmpTrack).dz(beamPoint_) ); break;
case egammaisolation::EgammaTrackSelector::vtx: dzCut = fabs( (*itrTr).dz(tmpTrack->vertex()) ); break;
default : dzCut = fabs( (*itrTr).vz() - (*tmpTrack).vz() ); break;
}
if (dzCut > lip_ ) continue;
if (fabs( (*itrTr).dxy(beamPoint_) ) > drb_ ) continue;
double dr = ROOT::Math::VectorUtil::DeltaR(itrTr->momentum(),tmpElectronMomentumAtVtx) ;
double deta = (*itrTr).eta() - tmpElectronEtaAtVertex;
if (fabs(tmpElectronEtaAtVertex) < 1.479) {
if ( fabs(dr) < extRadius_ && fabs(dr) >= intRadiusBarrel_ && fabs(deta) >= stripBarrel_)
{
++counter ;
ptSum += this_pt;
}
}
else {
if ( fabs(dr) < extRadius_ && fabs(dr) >= intRadiusEndcap_ && fabs(deta) >= stripEndcap_)
{
++counter ;
ptSum += this_pt;
}
}
}//end loop over tracks
std::pair<int,double> retval;
retval.first = counter;
retval.second = ptSum;
return retval;
} // end of get TrkIso
*/
// ====================================================================================
float SimpleNtpleCustom::E2overE9( const DetId id, const EcalRecHitCollection & recHits,
float recHitEtThreshold, float recHitEtThreshold2 ,
bool avoidIeta85, bool KillSecondHit)
// ====================================================================================
// taken from CMSSW/RecoLocalCalo/EcalRecAlgos/src/EcalSeverityLevelAlgo.cc CMSSW_3_9_0_pre5
{
// compute e2overe9
//
// | | | |
// +-+-+-+
// | |1|2|
// +-+-+-+
// | | | |
//
// 1 - input hit, 2 - highest energy hit in a 3x3 around 1
//
// rechit 1 must have E_t > recHitEtThreshold
// rechit 2 must have E_t > recHitEtThreshold2
//
// function returns value of E2/E9 centered around 1 (E2=energy of hits 1+2) if energy of 1>2
//
// if energy of 2>1 and KillSecondHit is set to true, function returns value of E2/E9 centered around 2
// *provided* that 1 is the highest energy hit in a 3x3 centered around 2, otherwise, function returns 0
if ( id.subdetId() == EcalBarrel ) {
EBDetId ebId( id );
// avoid recHits at |eta|=85 where one side of the neighbours is missing
if ( abs(ebId.ieta())==85 && avoidIeta85){ return 0;}
// select recHits with Et above recHitEtThreshold
float e1 = recHitE( id, recHits );
float ete1=recHitApproxEt( id, recHits );
// check that rechit E_t is above threshold
if (ete1 < std::min(recHitEtThreshold,recHitEtThreshold2) ) { return 0;}
if (ete1 < recHitEtThreshold && !KillSecondHit ) {return 0;}
float e2=-1;
float ete2=0;
float s9 = 0;
// coordinates of 2nd hit relative to central hit
int e2eta=0;
int e2phi=0;
// LOOP OVER 3x3 ARRAY CENTERED AROUND HIT 1
for ( int deta = -1; deta <= +1; ++deta ) {
for ( int dphi = -1; dphi <= +1; ++dphi ) {
// compute 3x3 energy
float etmp=recHitE( id, recHits, deta, dphi );
s9 += etmp;
EBDetId idtmp=EBDetId::offsetBy(id,deta,dphi);
float eapproxet=recHitApproxEt( idtmp, recHits );
// remember 2nd highest energy deposit (above threshold) in 3x3 array
if (etmp>e2 && eapproxet>recHitEtThreshold2 && !(deta==0 && dphi==0)) {
e2=etmp;
ete2=eapproxet;
e2eta=deta;
e2phi=dphi;
}
}
}
if ( e1 == 0 ) { return 0;}
// return 0 if 2nd hit is below threshold
if ( e2 == -1 ) {return 0;}
// compute e2/e9 centered around 1st hit
float e2nd=e1+e2;
float e2e9=0;
if (s9!=0) e2e9=e2nd/s9;
// if central hit has higher energy than 2nd hit
// return e2/e9 if 1st hit is above E_t threshold
if (e1 > e2 && ete1>recHitEtThreshold) return e2e9;
// if second hit has higher energy than 1st hit
if ( e2 > e1 ) {
// return 0 if user does not want to flag 2nd hit, or
// hits are below E_t thresholds - note here we
// now assume the 2nd hit to be the leading hit.
if (!KillSecondHit || ete2<recHitEtThreshold || ete1<recHitEtThreshold2) {
return 0;
}
else {
// LOOP OVER 3x3 ARRAY CENTERED AROUND HIT 2
float s92nd=0;
float e2nd_prime=0;
int e2prime_eta=0;
int e2prime_phi=0;
EBDetId secondid=EBDetId::offsetBy(id,e2eta,e2phi);
for ( int deta = -1; deta <= +1; ++deta ) {
for ( int dphi = -1; dphi <= +1; ++dphi ) {
// compute 3x3 energy
float etmp=recHitE( secondid, recHits, deta, dphi );
s92nd += etmp;
if (etmp>e2nd_prime && !(deta==0 && dphi==0)) {
e2nd_prime=etmp;
e2prime_eta=deta;
e2prime_phi=dphi;
}
}
}
// if highest energy hit around E2 is not the same as the input hit, return 0;
if (!(e2prime_eta==-e2eta && e2prime_phi==-e2phi))
{
return 0;
}
// compute E2/E9 around second hit
float e2e9_2=0;
if (s92nd!=0) e2e9_2=e2nd/s92nd;
// return the value of E2/E9 calculated around 2nd hit
return e2e9_2;
}
}
} else if ( id.subdetId() == EcalEndcap ) {
// only used for EB at the moment
return 0;
}
return 0;
}
// ====================================================================================
float SimpleNtpleCustom::recHitE( const DetId id, const EcalRecHitCollection &recHits )
// ====================================================================================
{
if ( id == DetId(0) ) {
return 0;
} else {
EcalRecHitCollection::const_iterator it = recHits.find( id );
if ( it != recHits.end() ) return (*it).energy();
}
return 0;
}
// ====================================================================================
float SimpleNtpleCustom::recHitE( const DetId id, const EcalRecHitCollection & recHits,
int di, int dj )
// ====================================================================================
{
// in the barrel: di = dEta dj = dPhi
// in the endcap: di = dX dj = dY
DetId nid;
if( id.subdetId() == EcalBarrel) nid = EBDetId::offsetBy( id, di, dj );
else if( id.subdetId() == EcalEndcap) nid = EEDetId::offsetBy( id, di, dj );
return ( nid == DetId(0) ? 0 : recHitE( nid, recHits ) );
}
// ====================================================================================
float SimpleNtpleCustom::recHitApproxEt( const DetId id, const EcalRecHitCollection &recHits )
// ====================================================================================
{
// for the time being works only for the barrel
if ( id.subdetId() == EcalBarrel ) {
return recHitE( id, recHits ) / cosh( EBDetId::approxEta( id ) );
}
return 0;
}
| [
"[email protected]"
]
| |
fd8ad2b8d8d4042e47770e7b10aeb6f4846560f7 | 8abcbf3689dc398cf489daf275879b4205fca3f8 | /test_hw_code/read_rtc_arduinoall/read_rtc_arduinoall.ino | 143534082cbfa0fa97705840706a845789e84f1a | []
| no_license | banpot408/smart_pump_project | 0a5a38c7e7756752e98524a30908114b864f3b55 | f18418af92b01fc62ee17ced86a7b08a7c131c4c | refs/heads/master | 2022-10-28T12:37:29.089239 | 2020-06-15T15:25:33 | 2020-06-15T15:25:33 | 262,183,103 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,177 | ino | // Date, Time and Alarm functions using a DS3231 RTC connected via I2C and Wire lib
#include "Wire.h"
#include "SPI.h" // not used here, but needed to prevent a RTClib compile error
#include "RTClib.h"
#include <LiquidCrystal_I2C.h>
RTC_DS3231 RTC;
LiquidCrystal_I2C lcd(0x3F, 20, 4);
void display_time(){
DateTime now = RTC.now();
int year_now = now.year();
int month_now = now.month();
int day_now = now.day();
int hour_now = now.hour();
int minute_now = now.minute();
int second_now = now.second();
float temp_now = RTC.getTemperature();
lcd.setCursor(0, 3);
lcd.print(hour_now, DEC);
lcd.print(":");
if (minute_now < 10)
{
Serial.print("0");
}
lcd.print(minute_now, DEC);
lcd.print(":");
if (second_now < 10)
{
Serial.print("0");
}
lcd.print(second_now, DEC);
lcd.print(" ");
lcd.print(day_now, DEC);
lcd.print("/");
lcd.print(month_now, DEC);
lcd.print("/");
lcd.print(year_now, DEC);
lcd.setCursor(15, 0);
lcd.print(temp_now, 1);
lcd.print("C");
}
void setup () {
Serial.begin(9600);
Wire.begin();
RTC.begin();
lcd.begin();
lcd.print(" Welcome To System ");
lcd.setCursor(0, 1);
lcd.print(" Designed By B.S.E ");
delay(3000);
lcd.clear();
// RTC.adjust(DateTime(__DATE__, __TIME__));
// if (! RTC.isrunning()) {
// Serial.println("RTC is NOT running!");
// // following line sets the RTC to the date & time this sketch was compiled
// RTC.adjust(DateTime(__DATE__, __TIME__));
// }
}
void loop () {
DateTime now = RTC.now();
Serial.print(now.year(), DEC);
Serial.print('/');
Serial.print(now.month(), DEC);
Serial.print('/');
Serial.print(now.day(), DEC);
Serial.print(' ');
Serial.print(now.hour(), DEC);
Serial.print(':');
Serial.print(now.minute(), DEC);
Serial.print(':');
Serial.print(now.second(), DEC);
Serial.println();
Serial.print("Tempeature = ");
Serial.print(RTC.getTemperature()); // คำสั่งดึงอุณหภูมิออกมาแสดง
Serial.println(" C");
Serial.println("By ArduinoALL");
Serial.println();
display_time();
delay(1000);
}
| [
"[email protected]"
]
| |
e352dd6f1ee0818d859526b84640245fb9507784 | 7cb9c888e98e3a00781f3e8fe2af8129880fe361 | /performance_test/src/communication_abstractions/ros2_callback_communicator.hpp | 843375e7dc85a37f9380666ea64e27d9169b5520 | [
"Apache-2.0"
]
| permissive | gaoethan/performance_test | 5898d529dc4518008ee094216bdbb2de2f608bf7 | 4ccab61ef91495c370f755a384f64e7aa5d50c8d | refs/heads/master | 2020-03-25T04:47:02.236235 | 2018-08-02T19:33:26 | 2018-08-02T19:33:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,835 | hpp | // Copyright 2017 Apex.AI, 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.
#ifndef COMMUNICATION_ABSTRACTIONS__ROS2_CALLBACK_COMMUNICATOR_HPP_
#define COMMUNICATION_ABSTRACTIONS__ROS2_CALLBACK_COMMUNICATOR_HPP_
#include <rclcpp/rclcpp.hpp>
#include <memory>
#include <atomic>
#include "../experiment_configuration/topics.hpp"
#include "../experiment_configuration/qos_abstraction.hpp"
#include "communicator.hpp"
#include "resource_manager.hpp"
namespace performance_test
{
/// Translates abstract QOS settings to specific QOS settings for ROS 2.
class ROS2QOSAdapter
{
public:
/**
* \brief The constructor which will save the provided abstract QOS.
* \param qos The abstract QOS to derive the settings from.
*/
explicit ROS2QOSAdapter(const QOSAbstraction qos)
: m_qos(qos)
{}
/// Gets a ROS 2 QOS profile derived from the stored abstract QOS.
inline rmw_qos_profile_t get() const
{
rmw_qos_profile_t ros_qos;
if (m_qos.reliability == QOSAbstraction::Reliability::BEST_EFFORT) {
ros_qos.reliability = rmw_qos_reliability_policy_t::RMW_QOS_POLICY_RELIABILITY_BEST_EFFORT;
} else if (m_qos.reliability == QOSAbstraction::Reliability::RELIABLE) {
ros_qos.reliability = rmw_qos_reliability_policy_t::RMW_QOS_POLICY_RELIABILITY_RELIABLE;
} else {
throw std::runtime_error("Unsupported QOS!");
}
if (m_qos.durability == QOSAbstraction::Durability::VOLATILE) {
ros_qos.durability = rmw_qos_durability_policy_t::RMW_QOS_POLICY_DURABILITY_VOLATILE;
} else if (m_qos.durability == QOSAbstraction::Durability::TRANSIENT_LOCAL) {
ros_qos.durability = rmw_qos_durability_policy_t::RMW_QOS_POLICY_DURABILITY_TRANSIENT_LOCAL;
} else {
throw std::runtime_error("Unsupported QOS!");
}
if (m_qos.history_kind == QOSAbstraction::HistoryKind::KEEP_ALL) {
ros_qos.history = rmw_qos_history_policy_t::RMW_QOS_POLICY_HISTORY_KEEP_ALL;
} else if (m_qos.history_kind == QOSAbstraction::HistoryKind::KEEP_LAST) {
ros_qos.history = rmw_qos_history_policy_t::RMW_QOS_POLICY_HISTORY_KEEP_LAST;
} else {
throw std::runtime_error("Unsupported QOS!");
}
ros_qos.depth = m_qos.history_depth;
return ros_qos;
}
private:
const QOSAbstraction m_qos;
};
/// Communication plugin for ROS 2 using ROS 2 callbacks for the subscription side.
template<class Topic>
class ROS2CallbackCommunicator : public Communicator
{
public:
/// The data type to publish and subscribe to.
using DataType = typename Topic::RosType;
/// Constructor which takes a reference \param lock to the lock to use.
explicit ROS2CallbackCommunicator(SpinLock & lock)
: Communicator(lock),
m_node(ResourceManager::get().ros2_node()),
m_publisher(nullptr),
m_subscription(nullptr)
{
m_executor.add_node(m_node);
}
/**
* \brief Publishes the provided data.
*
* The first time this function is called it also creates the publisher.
* Further it updates all internal counters while running.
*
* \param data The data to publish.
* \param time The time to fill into the data field.
*/
void publish(DataType & data, const std::chrono::duration<double> time)
{
if (!m_publisher) {
const auto qos = ROS2QOSAdapter(m_ec.qos()).get();
m_publisher = m_node->create_publisher<DataType>(Topic::topic_name(), qos);
}
lock();
data.time = time.count();
data.id = next_sample_id();
increment_sent(); // We increment before publishing so we don't have to lock twice.
unlock();
m_publisher->publish(data);
}
/// Reads received data from ROS 2 using callbacks
void update_subscription()
{
if (!m_subscription) {
const auto qos = ROS2QOSAdapter(m_ec.qos()).get();
m_subscription = m_node->create_subscription<DataType>(Topic::topic_name(),
std::bind(&ROS2CallbackCommunicator::callback, this, std::placeholders::_1), qos);
}
lock();
m_executor.spin_once(std::chrono::milliseconds(100));
unlock();
}
/// Returns the accumulated data size in bytes.
std::size_t data_received()
{
return num_received_samples() * sizeof(DataType);
}
private:
/**
* \brief Callback handler which handles the received data.
*
* * Verifies that the data arrived in the right order, chronologically and also consistent with the publishing order.
* * Counts recieved and lost samples.
* * Calculates the latency of the samples received and updates the statistics accordingly.
*
* \param data The data received.
*/
void callback(const typename DataType::SharedPtr data)
{
if (m_prev_timestamp >= data->time) {
throw std::runtime_error(
"Data consistency violated. Received sample with not strictly older timestamp");
}
m_prev_timestamp = data->time;
update_lost_samples_counter(data->id);
add_latency_to_statistics(data->time);
increment_received();
}
std::shared_ptr<rclcpp::Node> m_node;
rclcpp::executors::SingleThreadedExecutor m_executor;
std::shared_ptr<::rclcpp::Publisher<DataType, std::allocator<void>>> m_publisher;
std::shared_ptr<::rclcpp::Subscription<DataType, std::allocator<void>>> m_subscription;
};
} // namespace performance_test
#endif // COMMUNICATION_ABSTRACTIONS__ROS2_CALLBACK_COMMUNICATOR_HPP_
| [
"[email protected]"
]
| |
2c7d3fd907ea108edaf89e432c7319bcaa83ccad | 7f3e95e825b894a8d015b5905592757a0040220f | /2013/utils/Atil/Inc/Point3d.h | 77405ddf6e2dd7e677d2daa74a7f9ee588bb21ea | [
"MIT"
]
| permissive | AliClouds/ObjectARXCore | b06e2d4bb59df2b45e56ec76d3abb843c7131009 | ce09e150aa7d87675ca15c9416497c0487e3d4d4 | refs/heads/master | 2021-05-28T05:19:12.593781 | 2014-05-08T01:23:33 | 2014-05-08T01:23:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,691 | h | ///////////////////////////////////////////////////////////////////////////////
//
// (C) Autodesk, Inc. 2007-2011. All rights reserved.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
///////////////////////////////////////////////////////////////////////////////
#ifndef ATILDEFS_H
#include "AtilDefs.h"
#endif
#ifndef POINT3D_H
#define POINT3D_H
#if __GNUC__ >= 4
#pragma GCC visibility push(default)
#endif
namespace Atil
{
///<summary> A simple three-dimensional point class. Point3d holds double X, Y, and Z values, all of which
/// are public members. Consult Point3d.h for more information.</summary>
class Point3d
{
public:
///<summary>The x value.</summary>
double x;
///<summary>The y value.</summary>
double y;
///<summary>The z value.</summary>
double z;
public:
///<summary>The constructor.</summary>
Point3d() ;
///<summary>The constructor.</summary>
///<param name='x'>The value to set into the X value.</param>
///<param name='y'>The value to set into the Y value.</param>
///<param name='z'>The value to set into the Z value.</param>
Point3d( int x, int y, int z );
///<summary>The constructor.</summary>
///<param name='x'>The value to set into the X value.</param>
///<param name='y'>The value to set into the Y value.</param>
///<param name='z'>The value to set into the Z value.</param>
Point3d( double x, double y, double z );
///<summary>The destructor.</summary>
~Point3d() ;
///<summary>This sets the point.</summary>
///<param name='x'>The value to set into the X value.</param>
///<param name='y'>The value to set into the Y value.</param>
///<param name='z'>The value to set into the Z value.</param>
///<returns>A reference to "this".</returns>
const Point3d& set( int x, int y, int z );
///<summary>This sets the point.</summary>
///<param name='x'>The value to set into the X value.</param>
///<param name='y'>The value to set into the Y value.</param>
///<param name='z'>The value to set into the Z value.</param>
///<returns>A reference to "this".</returns>
const Point3d& set( double x, double y, double z );
///<summary>The eguals operator.</summary>
///<param name='rhs'>The <c>Point3d</c> to compare.</param>
///<returns>This returns true if the points match.</returns>
bool operator==(const Point3d& rhs) const;
///<summary>The not eguals operator.</summary>
///<param name='rhs'>The <c>Point3d</c> to compare.</param>
///<returns>This returns true if the points don't match.</returns>
bool operator!=(const Point3d& rhs) const;
};
} //end of namespace
#if __GNUC__ >= 4
#pragma GCC visibility pop
#endif
#endif
| [
"[email protected]"
]
| |
cef2966e0bf94e1096504109e6a1a3a44f2fe7b7 | 5a55209ad40c6f20b8e588ec2c0f731a22d81b06 | /codeforces/1535/B.cpp | fb44465cf2a3cdf376fafc5cbe69ce108565d5ac | []
| no_license | nabil0day/Problem-Solving | f5a5509d746a263cca02dd4af779e6ffa2ee8732 | a2e65bcf958d3bfe9d309575ae31358024785855 | refs/heads/master | 2023-08-19T20:22:11.133469 | 2021-10-22T14:47:00 | 2021-10-24T07:36:26 | 399,927,072 | 10 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,950 | cpp | /***************************************************************************************************************************************************
__Bismillahir Rahmanir Rahim__
American International University Bangladesh (AIUB)
Hadiur Rahman Nabil
******************************************************************************************************************************************************/
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double ld;
typedef vector <int> vi;
#define pb push_back
#define mp make_pair
#define gcd(a,b) __gcd(a,b)
#define endl "\n"
const int mod = 1e9 + 7;
const double PI = 3.1415926535897932384626;
const int mod_2 = 998244353;
const int MAX=100005;
void solve()
{
ll n;
cin>>n;
vector<ll>a;
for(int i=0;i<n;i++)
{
ll x;
cin>>x;
if(x%2)
a.push_back(x);
}
ll y= a.size(), sol= n*(n-1)/2;
for(int i=0;i<y;i++)
for(int j=i+1;j<y;j++)
if(gcd(a[i],a[j])==1)
sol--;
cout<<sol<<"\n";
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
#ifndef ONLINE_JUDGE
//freopen("input.txt", "r", stdin);
//freopen("output.txt", "w", stdout);
#endif
ll t;
cin>>t;
while(t--)
{
solve();
}
return 0;
} | [
"[email protected]"
]
| |
500b60f5b71520cfaa06a86cf1c394dd79c23531 | a9a8f411f1ef885a40e77002891712eedfe136e3 | /Rebel/Rect.cpp | 0c741d73b3f244101b85447143dd6ac86ba155bb | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | oxnz/Rebel | 24a0ad57b22c82f5bc2f512b82a27add6b644665 | 5bc91d039dec0c360b4576fc20a828b29d24c32b | refs/heads/master | 2020-05-04T21:28:49.585390 | 2019-04-04T10:45:21 | 2019-04-04T10:45:21 | 179,477,723 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 147 | cpp | //
// Shape.cpp
// Rebel
//
// Created by 云心逸 on 2019/3/23.
// Copyright © 2019 云心逸. All rights reserved.
//
#include "Rect.hpp"
| [
"[email protected]"
]
| |
cee2a1d8e326470bedd136402ea5dea087cb1c13 | 452be58b4c62e6522724740cac332ed0fe446bb8 | /src/cobalt/renderer/backend/egl/graphics_system.cc | 8e48f7e6c75645ed972ee9b0acd197fe0ddc14af | [
"Apache-2.0"
]
| permissive | blockspacer/cobalt-clone-cab7770533804d582eaa66c713a1582f361182d3 | b6e802f4182adbf6a7451a5d48dc4e158b395107 | 0b72f93b07285f3af3c8452ae2ceaf5860ca7c72 | refs/heads/master | 2020-08-18T11:32:21.458963 | 2019-10-17T13:09:35 | 2019-10-17T13:09:35 | 215,783,613 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 9,646 | cc | // Copyright 2015 The Cobalt Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <memory>
#include "cobalt/renderer/backend/egl/graphics_system.h"
#include "base/debug/leak_annotations.h"
#if defined(ENABLE_GLIMP_TRACING)
#include "base/trace_event/trace_event.h"
#endif
#include "starboard/common/optional.h"
#if defined(GLES3_SUPPORTED)
#include "cobalt/renderer/backend/egl/texture_data_pbo.h"
#else
#include "cobalt/renderer/backend/egl/texture_data_cpu.h"
#endif
#include "cobalt/renderer/backend/egl/display.h"
#include "cobalt/renderer/backend/egl/graphics_context.h"
#include "cobalt/renderer/backend/egl/texture.h"
#include "cobalt/renderer/backend/egl/utils.h"
#if defined(ENABLE_GLIMP_TRACING)
#include "glimp/tracing/tracing.h"
#endif
#include "cobalt/renderer/egl_and_gles.h"
namespace cobalt {
namespace renderer {
namespace backend {
#if defined(ENABLE_GLIMP_TRACING)
// Hookup glimp tracing to Chromium's base trace_event tracing.
class GlimpToBaseTraceEventBridge : public glimp::TraceEventImpl {
public:
void BeginTrace(const char* name) override {
TRACE_EVENT_BEGIN0("glimp", name);
}
void EndTrace(const char* name) override { TRACE_EVENT_END0("glimp", name); }
};
GlimpToBaseTraceEventBridge s_glimp_to_base_trace_event_bridge;
#endif // #if defined(ENABLE_GLIMP_TRACING)
namespace {
struct ChooseConfigResult {
ChooseConfigResult() : window_surface(EGL_NO_SURFACE) {}
EGLConfig config;
// This will be EGL_NO_SURFACE if no window was provided to find a config to
// match with.
EGLSurface window_surface;
};
// Returns a config that matches the |attribute_list|. Optionally,
// |system_window| can also be provided in which case the config returned will
// also be guaranteed to match with it, and a EGLSurface will be returned
// for that window.
base::Optional<ChooseConfigResult> ChooseConfig(
EGLDisplay display, EGLint* attribute_list,
system_window::SystemWindow* system_window) {
if (!system_window) {
// If there is no system window provided then this task is much easier,
// just return the first config that matches the provided attributes.
EGLint num_configs;
EGLConfig config;
EGL_CALL_SIMPLE(
eglChooseConfig(display, attribute_list, &config, 1, &num_configs));
DCHECK_GE(1, num_configs);
if (num_configs == 1) {
ChooseConfigResult results;
results.config = config;
return results;
} else {
LOG(ERROR) << "Could not find a EGLConfig compatible with the specified "
<< "attributes.";
return base::nullopt;
}
}
// Retrieve *all* configs that match the attribute list, and for each of them
// test to see if we can successfully call eglCreateWindowSurface() with them.
// Return the first config that succeeds the above test.
EGLint num_configs = 0;
EGL_CALL(eglChooseConfig(display, attribute_list, NULL, 0, &num_configs));
CHECK_LT(0, num_configs);
std::unique_ptr<EGLConfig[]> configs(new EGLConfig[num_configs]);
EGL_CALL_SIMPLE(eglChooseConfig(display, attribute_list, configs.get(),
num_configs, &num_configs));
EGLNativeWindowType native_window =
(EGLNativeWindowType)(system_window->GetWindowHandle());
for (EGLint i = 0; i < num_configs; ++i) {
EGLSurface surface = EGL_CALL_SIMPLE(
eglCreateWindowSurface(display, configs[i], native_window, NULL));
if (EGL_SUCCESS == EGL_CALL_SIMPLE(eglGetError())) {
// We did it, we found a config that allows us to successfully create
// a surface. Return the config along with the created surface.
ChooseConfigResult result;
result.config = configs[i];
result.window_surface = surface;
return result;
}
}
// We could not find a config with the provided window, return a failure.
LOG(ERROR) << "Could not find a EGLConfig compatible with the specified "
<< "EGLNativeWindowType object and attributes.";
return base::nullopt;
}
} // namespace
GraphicsSystemEGL::GraphicsSystemEGL(
system_window::SystemWindow* system_window) {
#if defined(ENABLE_GLIMP_TRACING)
// If glimp tracing is enabled, hook up glimp trace calls to Chromium's
// base trace_event calls.
glimp::SetTraceEventImplementation(&s_glimp_to_base_trace_event_bridge);
#endif // #if defined(ENABLE_GLIMP_TRACING)
display_ = EGL_CALL_SIMPLE(eglGetDisplay(EGL_DEFAULT_DISPLAY));
CHECK_NE(EGL_NO_DISPLAY, display_);
CHECK_EQ(EGL_SUCCESS, EGL_CALL_SIMPLE(eglGetError()));
{
// Despite eglTerminate() being used in the destructor, the current
// mesa egl drivers still leak memory.
ANNOTATE_SCOPED_MEMORY_LEAK;
EGL_CALL(eglInitialize(display_, NULL, NULL));
}
// Setup our configuration to support RGBA and compatibility with PBuffer
// objects (for offscreen rendering).
EGLint attribute_list[] = {
EGL_SURFACE_TYPE, // this must be first
EGL_WINDOW_BIT | EGL_PBUFFER_BIT
#if defined(COBALT_RENDER_DIRTY_REGION_ONLY)
| EGL_SWAP_BEHAVIOR_PRESERVED_BIT
#endif // #if defined(COBALT_RENDER_DIRTY_REGION_ONLY)
,
EGL_RED_SIZE,
8,
EGL_GREEN_SIZE,
8,
EGL_BLUE_SIZE,
8,
EGL_ALPHA_SIZE,
8,
EGL_RENDERABLE_TYPE,
#if defined(GLES3_SUPPORTED)
EGL_OPENGL_ES3_BIT,
#else
EGL_OPENGL_ES2_BIT,
#endif // #if defined(GLES3_SUPPORTED)
EGL_NONE
};
base::Optional<ChooseConfigResult> choose_config_results =
ChooseConfig(display_, attribute_list, system_window);
#if defined(COBALT_RENDER_DIRTY_REGION_ONLY)
// Try to allow preservation of the frame contents between swap calls --
// this will allow rendering of only parts of the frame that have changed.
DCHECK_EQ(EGL_SURFACE_TYPE, attribute_list[0]);
EGLint& surface_type_value = attribute_list[1];
// Swap buffer preservation may not be supported. If we failed to find a
// config with the EGL_SWAP_BEHAVIOR_PRESERVED_BIT attribute, try again
// without it.
if (!choose_config_results) {
surface_type_value &= ~EGL_SWAP_BEHAVIOR_PRESERVED_BIT;
choose_config_results =
ChooseConfig(display_, attribute_list, system_window);
}
#endif // #if defined(COBALT_RENDER_DIRTY_REGION_ONLY)
DCHECK(choose_config_results);
config_ = choose_config_results->config;
system_window_ = system_window;
window_surface_ = choose_config_results->window_surface;
#if defined(GLES3_SUPPORTED)
resource_context_.emplace(display_, config_);
#endif
}
GraphicsSystemEGL::~GraphicsSystemEGL() {
resource_context_.reset();
if (window_surface_ != EGL_NO_SURFACE) {
EGL_CALL_SIMPLE(eglDestroySurface(display_, window_surface_));
}
EGL_CALL_SIMPLE(eglTerminate(display_));
}
std::unique_ptr<Display> GraphicsSystemEGL::CreateDisplay(
system_window::SystemWindow* system_window) {
EGLSurface surface;
if (system_window == system_window_ && window_surface_ != EGL_NO_SURFACE) {
// Hand-off our precreated window into the display being created.
surface = window_surface_;
window_surface_ = EGL_NO_SURFACE;
} else {
EGLNativeWindowType native_window =
(EGLNativeWindowType)(system_window->GetWindowHandle());
surface = EGL_CALL_SIMPLE(
eglCreateWindowSurface(display_, config_, native_window, NULL));
CHECK_EQ(EGL_SUCCESS, EGL_CALL_SIMPLE(eglGetError()));
}
return std::unique_ptr<Display>(new DisplayEGL(display_, surface));
}
std::unique_ptr<GraphicsContext> GraphicsSystemEGL::CreateGraphicsContext() {
// If GLES3 is supported, we will make use of PBOs to allocate buffers for
// texture data and populate them on separate threads. In order to access
// that data from graphics contexts created through this method, we must
// enable sharing between them and the resource context, which is why we
// must pass it in here.
#if defined(GLES3_SUPPORTED)
ResourceContext* resource_context = &(resource_context_.value());
#else
ResourceContext* resource_context = NULL;
#endif
return std::unique_ptr<GraphicsContext>(
new GraphicsContextEGL(this, display_, config_, resource_context));
}
std::unique_ptr<TextureDataEGL> GraphicsSystemEGL::AllocateTextureData(
const math::Size& size, GLenum format) {
#if defined(GLES3_SUPPORTED)
std::unique_ptr<TextureDataEGL> texture_data(
new TextureDataPBO(&(resource_context_.value()), size, format));
#else
std::unique_ptr<TextureDataEGL> texture_data(
new TextureDataCPU(size, format));
#endif
if (texture_data->CreationError()) {
return std::unique_ptr<TextureDataEGL>();
} else {
return std::move(texture_data);
}
}
std::unique_ptr<RawTextureMemoryEGL>
GraphicsSystemEGL::AllocateRawTextureMemory(size_t size_in_bytes,
size_t alignment) {
#if defined(GLES3_SUPPORTED)
return std::unique_ptr<RawTextureMemoryEGL>(new RawTextureMemoryPBO(
&(resource_context_.value()), size_in_bytes, alignment));
#else
return std::unique_ptr<RawTextureMemoryEGL>(
new RawTextureMemoryCPU(size_in_bytes, alignment));
#endif
}
} // namespace backend
} // namespace renderer
} // namespace cobalt
| [
"[email protected]"
]
| |
21574c7d54acb481e4feb7c0a60186af1e2ecfc5 | 8dc84558f0058d90dfc4955e905dab1b22d12c08 | /third_party/blink/renderer/core/layout/ng/ng_positioned_float.h | 09ac96614e93133f13177fcb40981f9d4c92af43 | [
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause",
"LGPL-2.0-only",
"BSD-2-Clause",
"LGPL-2.1-only"
]
| permissive | meniossin/src | 42a95cc6c4a9c71d43d62bc4311224ca1fd61e03 | 44f73f7e76119e5ab415d4593ac66485e65d700a | refs/heads/master | 2022-12-16T20:17:03.747113 | 2020-09-03T10:43:12 | 2020-09-03T10:43:12 | 263,710,168 | 1 | 0 | BSD-3-Clause | 2020-05-13T18:20:09 | 2020-05-13T18:20:08 | null | UTF-8 | C++ | false | false | 833 | h | // Copyright 2017 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 NGPositionedFloat_h
#define NGPositionedFloat_h
#include "base/memory/scoped_refptr.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/layout/ng/geometry/ng_bfc_offset.h"
namespace blink {
class NGLayoutResult;
// Contains the information necessary for copying back data to a FloatingObject.
struct CORE_EXPORT NGPositionedFloat {
NGPositionedFloat(scoped_refptr<NGLayoutResult> layout_result,
const NGBfcOffset& bfc_offset);
~NGPositionedFloat();
scoped_refptr<NGLayoutResult> layout_result;
NGBfcOffset bfc_offset;
};
} // namespace blink
#endif // NGPositionedFloat_h
| [
"[email protected]"
]
| |
20951957b21a465d9bbcca1ec1b89e26d403b9fe | ba2192869cfe650a0006cb663b8a0f225621afbf | /si-unit-test/si-unit-test/quantity-test.cpp | c6dfe21191f3e1813a81d1127a343fafb9ebe455 | []
| no_license | rtdoherty/si-units | dc603049cd00e45de5ac468a3a96b856c1ada773 | 6129c95191adda9cfbe7a149ff14b62c0cead00c | refs/heads/develop | 2021-08-26T09:25:57.753505 | 2017-11-22T20:09:39 | 2017-11-22T20:09:39 | 111,733,099 | 0 | 0 | null | 2017-11-22T21:15:37 | 2017-11-22T21:15:37 | null | UTF-8 | C++ | false | false | 1,276 | cpp | #include "units.hpp"
#include "quantity-test.hpp"
// compile-time unit tests
namespace
{
using namespace si;
// is_quantity
static_assert( !is_quantity< int >, "" );
static_assert( is_quantity< none >, "" );
static_assert( is_quantity< mass >, "" );
static_assert( is_quantity< distance >, "" );
static_assert( is_quantity< time >, "" );
static_assert( is_quantity< current >, "" );
static_assert( is_quantity< const temperature >, "" );
static_assert( is_quantity< volatile luminous_intensity >, "" );
static_assert( is_quantity< const volatile angle >, "" );
// multiply_quantity
static_assert( std::is_same<quantity_t<4,6>, multiply_quantity<quantity_t<1,2>,quantity_t<3,4>>>::value, "" );
// power_quantity
static_assert( std::is_same<quantity_t<3,-6>, power_quantity<quantity_t<1,-2>,3>>::value, "" );
// reciprocal_quantity
static_assert( std::is_same<quantity_t<-1>, reciprocal_quantity<mass>>::value, "" );
// divide_quantity
static_assert( std::is_same<quantity_t<1,-1>, divide_quantity<mass,distance>>::value, "" );
// root_quantity
static_assert( std::is_same<quantity_t<2,-1>, root_quantity<quantity_t<4,-2>,2>>::value, "" );
} // end of anonymous namespace
void si::run_quantity_tests()
{
// there are currently no run-time unit tests for units_t
}
| [
"[email protected]"
]
| |
a046833ff5e903c499d853406409bdffb176d36b | 59c94d223c8e1eb1720d608b9fc040af22f09e3a | /garnet/drivers/gpu/msd-vsl-gc/src/msd_vsl_buffer.cc | aca78a79dde8cfb09e22863c3e161a3b043603ac | [
"BSD-3-Clause"
]
| permissive | bootingman/fuchsia2 | 67f527712e505c4dca000a9d54d3be1a4def3afa | 04012f0aa1edd1d4108a2ac647a65e59730fc4c2 | refs/heads/master | 2022-12-25T20:28:37.134803 | 2019-05-14T08:26:08 | 2019-05-14T08:26:08 | 186,606,695 | 1 | 1 | BSD-3-Clause | 2022-12-16T21:17:16 | 2019-05-14T11:17:16 | C++ | UTF-8 | C++ | false | false | 1,229 | cc | // Copyright 2018 The Fuchsia 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 "msd_vsl_buffer.h"
std::unique_ptr<MsdVslBuffer> MsdVslBuffer::Import(uint32_t handle)
{
auto platform_buf = magma::PlatformBuffer::Import(handle);
if (!platform_buf)
return DRETP(nullptr, "failed to import buffer handle 0x%x", handle);
return std::make_unique<MsdVslBuffer>(std::move(platform_buf));
}
std::unique_ptr<MsdVslBuffer> MsdVslBuffer::Create(uint64_t size, const char* name)
{
auto platform_buf = magma::PlatformBuffer::Create(size, name);
if (!platform_buf)
return DRETP(nullptr, "failed to create buffer size %lu", size);
return std::make_unique<MsdVslBuffer>(std::move(platform_buf));
}
//////////////////////////////////////////////////////////////////////////////
msd_buffer_t* msd_buffer_import(uint32_t handle)
{
auto buffer = MsdVslBuffer::Import(handle);
if (!buffer)
return DRETP(nullptr, "failed to import buffer handle 0x%x", handle);
return new MsdVslAbiBuffer(std::move(buffer));
}
void msd_buffer_destroy(msd_buffer_t* buf) { delete MsdVslAbiBuffer::cast(buf); }
| [
"[email protected]"
]
| |
fc2f527fbfeb6a781ca4f6cc4047ba6134306342 | d04ac609bf554a8976baae98328d068fd1603ed0 | /demo/src/main.cpp | d00c168db00e6d31a1448b9d48dd92b2fedb39d2 | []
| no_license | L4STeam/l4sdemo | bb6b7a50efdc83b4e0cdb879c2470e65b3b7e8b1 | 382774b6d7523f48a770fea62e19fdc5c0916a78 | refs/heads/master | 2022-06-12T20:23:29.735581 | 2020-06-14T13:22:39 | 2020-06-14T13:22:39 | 176,830,414 | 7 | 6 | null | 2020-06-09T23:58:22 | 2019-03-20T23:05:26 | C | UTF-8 | C++ | false | false | 491 | cpp | #include "mainwindow.h"
#include <QApplication>
#include <QWidget>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QPushButton>
#include <QStyleFactory>
int main( int argc, char **argv )
{
QApplication a( argc, argv );
QApplication::setStyle(QStyleFactory::create("Fusion"));
QPalette p = QApplication::palette();
p.setColor(QPalette::Background, Qt::white);
QApplication::setPalette(p);
MainWindow mainWindow;
mainWindow.show();
return a.exec();
}
| [
"[email protected]"
]
| |
2ccdfe6d1d2520bea0b90ce8de40331e82cab735 | 961fec09ba58b2b94e71ddbe3a1e5d1f2738bcf2 | /src/UCTRave.h | 3a016cc90b0a522dec239bb255037ca36594eb75 | []
| no_license | dpiponi/SpellCaster | a3631b3f60e9f7f171788ca3f9deafbca6c4d696 | 6aa6e6edb3403b49c60be30044ae45aa916de013 | refs/heads/master | 2021-01-19T11:54:28.300555 | 2018-01-09T21:35:41 | 2018-01-09T21:35:41 | 88,007,960 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,515 | h | #ifndef UCTRAVE_H
#define UCTRAVE_H
#include <set>
#include <map>
#include <vector>
#include <cassert>
#include <iostream>
#include <ctime>
#include <thread>
#include <future>
#include <chrono>
#include <cmath>
using std::set;
using std::map;
using std::vector;
using std::shared_ptr;
using std::make_shared;
using std::cout;
using std::endl;
using std::exp;
enum McRaveSchedule {
HAND_SELECTED,
MINIMUM_MSE
};
class UCTParameters {
public:
double allowed_time;
double c;
McRaveSchedule schedule;
int k;
double bias;
float heuristic_amaf_multiplier;
float heuristic_mc_multiplier;
bool use_heuristic;
};
const double NON_TERMINAL = 9999.0;
double score(const UCTParameters ¶ms,
bool optimistic,
int nparent, int nchild, double qchild, int nidchild, int qidchild);
template<class Game>
class Node {
public:
map<typename Game::Move, shared_ptr<Node>> children;
Node *parent;
private:
public:
int ntot;
// q_mc's are values for nextPlayer
// vector<typename Game::Move> moves;
map<typename Game::Move, int> n_avail;
map<typename Game::Move, int> n_mc;
map<typename Game::Move, float> q_mc;
map<typename Game::Move, int> n_amaf;
map<typename Game::Move, float> q_amaf;
~Node() { }
typename Game::Move bestChild(const UCTParameters ¶ms, const vector<typename Game::Move> &moves, bool optimistic) {
float best_score = -1e8;
typename Game::Move best_id(-1, 0, 0);
for (auto p : moves) {
auto id = p;
float s = score(params, optimistic, n_avail[id],
n_mc[id], q_mc[id], n_amaf[id], q_amaf[id]);
if (s > best_score) {
best_score = s;
best_id = id;
}
}
assert(best_score > -1e8);
return best_id;
}
Node(const UCTParameters ¶ms, Node *p)
: parent(p), ntot(0) { }
// XXX inefficient
bool isThereUntried(const vector<typename Game::Move> &moves) {
for (auto p : moves) {
if (children.find(p) == children.end()) {
return true;
}
}
return false;
}
// Assumes an untried exists
typename Game::Move findFirstUntried(
const vector<typename Game::Move> &moves) {
for (auto p : moves) {
if (children.find(p) == children.end()) {
return p;
}
}
assert(false);
__builtin_unreachable();
}
shared_ptr<Node> expand(const UCTParameters ¶ms,
typename Game::Move untriedMove,
shared_ptr<Game> position,
const vector<typename Game::Move> &moves,
vector<typename Game::Move> &ids) {
ids.push_back(untriedMove);
position->checkConsistency();
position->doMove(untriedMove);
auto child = make_shared<Node>(params, this);
children[untriedMove] = child;
return child;
}
static shared_ptr<Node>
treePolicy(const UCTParameters ¶ms,
shared_ptr<Game> position,
shared_ptr<Node> v,
vector<typename Game::Move> &ids) {
position->checkConsistency();
float value = position->evaluate();
auto moves = position->legalMoves();
if (value == NON_TERMINAL) {
if (v->isThereUntried(moves)) {
auto untriedMove = v->findFirstUntried(moves);
++v->n_avail[untriedMove]; // ??
if (params.use_heuristic) {
assert(v->n_mc[untriedMove] == 0);
auto h = position->heuristicValue(untriedMove);
v->n_mc[untriedMove] = params.heuristic_mc_multiplier*h.second;
v->q_mc[untriedMove] = params.heuristic_mc_multiplier*h.first;
}
position->checkConsistency();
return v->expand(params, untriedMove, position, moves, ids);
} else {
for (auto p : moves) {
++v->n_avail[p];
}
auto b = v->bestChild(params, moves, true);
ids.push_back(b);
v = v->children[b];
position->doMove(b);
position->checkConsistency();
return treePolicy(params, position, v, ids);
}
}
return v;
}
// ids is moves from root of current search
// When first called, the vertex should have no children.
// Have to go up one to get to a vertex with children.
void backupNegamax(float leaf_value,
vector<typename Game::Move> &ids, int firstMove) {
int leaf_player = ids[firstMove-1].getPlayer();
Node *v = this;
//typename Game::Move thisChild;
++v->ntot;
// value is value for person moving to v
// So we store +value in parent
while (v->parent) {
--firstMove;
//thisChild = v->moveThatGotUsHere;
//typename Game::Move idThatGotUsHere = v->parent->moves[thisChild];
typename Game::Move idThatGotUsHere = ids[firstMove];
v = v->parent;
float value2 = idThatGotUsHere.getPlayer() == leaf_player ? leaf_value : -leaf_value;
++v->ntot;
typename Game::Move thisMove = idThatGotUsHere;
++v->n_mc[thisMove];
v->q_mc[thisMove] += value2;
set<typename Game::Move> s;
// XXX assumes simple alternation YYY
for (int k = firstMove; k < ids.size(); k += 2) {
s.insert(ids[k]);
}
for (auto q : s) {
++v->n_amaf[q];
v->q_amaf[q] += value2;
assert(q.getPlayer() == thisMove.getPlayer());
}
}
assert(firstMove == 0);
}
#if 1
void diagnostics(shared_ptr<Game> game, const UCTParameters ¶ms) {
cout << "Diagnostics:" << endl;
for (auto p : n_mc) {
typename Game::Move id = p.first;
float s = score(params, false, n_avail[id],
n_mc[id], q_mc[id], n_amaf[id], q_amaf[id]);
game->describeId(id);
cout << " n = " << ntot << ": " << s
<< " mc: " << q_mc[id] << '/' << n_mc[id]
<< " amaf: " << q_amaf[id] << '/' << n_amaf[id]
<< " avail: " << n_avail[id] << endl;
}
cout << "End of diagnostics" << endl;
cout.flush();
}
#endif
};
//
// position->evaluate() is value for player that got to position
// Not for position->nextPlayer.
// Value of defaultPolicy(positin, ...) is like position->evaluate()
template<class Game>
void defaultPolicy(shared_ptr<Node<Game>> v, int treeMoves,
shared_ptr<Game> game, vector<typename Game::Move> &ids,
float sign = 1.0, bool gameIsOriginal = true) {
while (true) {
float value = game->evaluate();
// Return if terminal...
if (value != NON_TERMINAL) {
v->backupNegamax(sign*value, ids, treeMoves);
return;
}
vector<typename Game::Move> moves = game->legalMoves();
int n_mc = moves.size();
if (n_mc == 0) {
game->show();
cout << "No legal moves" << endl;
exit(1);
}
#if HEURISTIC_ROLLOUT
vector<double> probs;
double t = 0.0;
double lambda = 1.0;
for (int k = 0; k < n_mc; ++k) {
double value = game->heuristicValue(moves[k]).first;
double p = exp(lambda*(value >= 0));
probs.push_back(p);
t += p;
}
double r = t*(rand()/double(RAND_MAX));
int i = 0;
for (i = 0; i < n_mc-1; ++i) {
r -= probs[i];
if (r <= 0) {
break;
}
}
#else
int i = rand() % n_mc;
#endif
typename Game::Move chosen = moves[i];
ids.push_back(chosen);
game->doMove(chosen);
gameIsOriginal = false;
sign = -sign;
}
//defaultPolicy(v, treeMoves, game, ids, sign, gameIsOriginal);
}
template<class Game>
class Best {
public:
shared_ptr<Node<Game>> root;
typename Game::Move move;
};
template<class Game>
Best<Game> uctSearch(const UCTParameters ¶ms,
shared_ptr<Game> start, bool verbose = true) {
using std::chrono::steady_clock;
assert(start->evaluate() == NON_TERMINAL);
auto root = make_shared<Node<Game>>(params, (Node<Game> *)NULL);
auto c_start = steady_clock::now();
cout << "Start thinking..." << endl;
int count = 0;
bool did_some_work = false;
while ((steady_clock::now()-c_start).count()*
steady_clock::period::num/static_cast<float>(steady_clock::period::den)
< params.allowed_time) {
vector<typename Game::Move> ids;
auto determinised = make_shared<Game>(*start);
determinised->determinise();
determinised->checkConsistency();
auto treePolicyTree = Node<Game>::treePolicy(params, determinised, root, ids);
int treeMoves = ids.size();
defaultPolicy(treePolicyTree, treeMoves, determinised, ids);
// ids[0..treeMoves-1] came from tree policy
// ids[treeMoves ..] came from default policy
++count;
did_some_work = true;
}
cout << "!!!!!!!!!!!!!! Considered " << count << " plays" << endl;
assert(did_some_work);
if (verbose) {
root->diagnostics(start, params);
}
#if 0 // Check consistency
for (auto p = root->n_avail.begin(); p != root->n_avail.end(); ++p) {
assert(p->first.getPlayer() == start->nextPlayer);
}
for (auto p = root->q_mc.begin(); p != root->q_mc.end(); ++p) {
assert(p->first.getPlayer() == start->nextPlayer);
}
for (auto p = root->n_mc.begin(); p != root->n_mc.end(); ++p) {
assert(p->first.getPlayer() == start->nextPlayer);
}
for (auto p = root->q_amaf.begin(); p != root->q_amaf.end(); ++p) {
assert(p->first.getPlayer() == start->nextPlayer);
}
for (auto p = root->n_amaf.begin(); p != root->n_amaf.end(); ++p) {
assert(p->first.getPlayer() == start->nextPlayer);
}
#endif
auto moves = start->legalMoves();
auto bestMove = root->bestChild(params, moves, false);
return Best<Game>{root, bestMove};
}
template<class Game>
shared_ptr<Node<Game>>
uctSearch0(const UCTParameters ¶ms,
shared_ptr<Game> start, bool verbose = true) {
using std::chrono::steady_clock;
auto root = make_shared<Node<Game>>(params, (Node<Game> *)0, start);
auto c_start = steady_clock::now();
int count = 0;
while ((steady_clock::now()-c_start).count()*
steady_clock::period::num/static_cast<float>(steady_clock::period::den)
< params.allowed_time) {
vector<typename Game::Move> ids;
shared_ptr<Node<Game>> v = Node<Game>::treePolicy(params, root, ids);
int treeMoves = ids.size();
defaultPolicy(v, treeMoves, v->position, ids);
// ids[0..treeMoves-1] came from tree policy
// is[treeMoves ..] came from default policy
// v->backupNegamax(value, ids, treeMoves);
++count;
}
cout << "Considered " << count << " plays" << endl;
if (false && verbose) {
root->diagnostics(params);
}
return root;
}
template<class X> void sum_vector(vector<X> &a, const vector<X> &b) {
for (int i = 0; i < a.size(); ++i) {
a[i] += b[i];
}
}
template<class X, class Y> void sum_map(map<X, Y> &a, const map<X, Y> &b) {
for (auto p : b) {
a[p.first] += p->second;
}
}
template<class Game>
Best<Game> uctSearch1(const UCTParameters ¶ms, shared_ptr<Game> start, bool verbose = true) {
auto froot0 = std::async(std::launch::async, [¶ms, start, verbose]() {
return uctSearch0(params, start, verbose);
});
auto froot1 = std::async(std::launch::async, [¶ms, start, verbose]() {
return uctSearch0(params, start, verbose);
});
auto froot2 = std::async(std::launch::async, [¶ms, start, verbose]() {
return uctSearch0(params, start, verbose);
});
auto froot3 = std::async(std::launch::async, [¶ms, start, verbose]() {
return uctSearch0(params, start, verbose);
});
froot0.wait();
froot1.wait();
froot1.wait();
froot3.wait();
shared_ptr<Node<Game>> root0 = froot0.get();
shared_ptr<Node<Game>> root1 = froot1.get();
shared_ptr<Node<Game>> root2 = froot2.get();
shared_ptr<Node<Game>> root3 = froot3.get();
root0->ntot += root1->ntot;
root0->ntot += root2->ntot;
root0->ntot += root3->ntot;
sum_vector(root0->n_mc, root1->n_mc);
sum_vector(root0->n_mc, root2->n_mc);
sum_vector(root0->n_mc, root3->n_mc);
sum_vector(root0->q_mc, root1->q_mc);
sum_vector(root0->q_mc, root2->q_mc);
sum_vector(root0->q_mc, root3->q_mc);
sum_map(root0->n_amaf, root1->n_amaf);
sum_map(root0->n_amaf, root2->n_amaf);
sum_map(root0->n_amaf, root3->n_amaf);
sum_map(root0->q_amaf, root1->q_amaf);
sum_map(root0->q_amaf, root2->q_amaf);
sum_map(root0->q_amaf, root3->q_amaf);
//delete root1;
int i = root0->bestChild(params, false);
typename Game::Move bestMove = root0->moves[i];
return Best<Game>{root0, bestMove};
}
#if 0
template<class Game>
void examineTree(const UCTParameters ¶ms, shared_ptr<Node<Game>> tree0) {
Node<Game> *root = tree0.get();
Node<Game> *tree = root;
string cmd;
while (true) {
tree->position->show();
// tree->diagnostics(params);
cout << "cmd: ";
getline(cin, cmd);
#if 0
if (cmd[0] >= '0' && cmd[0] <= '9') {
istrstream cmd_line(cmd.c_str());
int n_mc;
cmd_line >> n_mc;
tree = tree->children[n_mc].get();
} else if (cmd[0] == 'u') {
if (tree->parent) {
tree = tree->parent;
} else {
cout << "At root" << endl;
}
} else
#endif
if (cmd[0] == 'r') {
tree = root;
} else return;
}
}
#endif
#endif
| [
"[email protected]"
]
| |
f4f980c3421be7156bb200278b1486ca008319dc | 1c6cd19017a2d13a215c29d43781819e216dc652 | /clang/darwin-x86_64/include/clang/Sema/AttrParsedAttrImpl.inc | 8cad26db6131db63e29855a750663513c44525cc | []
| no_license | konkers/u-prebuilts-prelfs | acea63676c26c6fad3a8b8fdf9b23961660c6c6e | 7751fffcce5aeba0f9d730d5f34c06ea6881f977 | refs/heads/main | 2021-01-22T07:48:58.030314 | 2017-02-13T16:49:31 | 2017-02-13T16:49:31 | 81,854,609 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 90,744 | inc | /*===- TableGen'erated file -------------------------------------*- C++ -*-===*\
|* *|
|* Parsed attribute helpers *|
|* *|
|* Automatically generated file, do not edit! *|
|* *|
\*===----------------------------------------------------------------------===*/
static bool defaultAppertainsTo(Sema &, const AttributeList &,const Decl *) {
return true;
}
static bool defaultDiagnoseLangOpts(Sema &, const AttributeList &) {
return true;
}
static bool defaultTargetRequirements(const TargetInfo &) {
return true;
}
static unsigned defaultSpellingIndexToSemanticSpelling(const AttributeList &Attr) {
return UINT_MAX;
}
static bool checkAMDGPUNumSGPRAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<FunctionDecl>(D)) {
S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedKernelFunction;
return false;
}
return true;
}
static bool checkAMDGPUNumVGPRAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<FunctionDecl>(D)) {
S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedKernelFunction;
return false;
}
return true;
}
static bool isTargetarmthumbx86x86_64msp430mipsmipsel(const TargetInfo &Target) {
const llvm::Triple &T = Target.getTriple();
return (T.getArch() == llvm::Triple::arm || T.getArch() == llvm::Triple::thumb || T.getArch() == llvm::Triple::x86 || T.getArch() == llvm::Triple::x86_64 || T.getArch() == llvm::Triple::msp430 || T.getArch() == llvm::Triple::mips || T.getArch() == llvm::Triple::mipsel);
}
static bool isStruct(const Decl *D) {
if (const auto *S = dyn_cast<RecordDecl>(D))
return !S->isUnion();
return false;
}
static bool checkAbiTagAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isStruct(D) && !isa<VarDecl>(D) && !isa<FunctionDecl>(D) && !isa<NamespaceDecl>(D)) {
S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedStructClassVariableFunctionOrInlineNamespace;
return false;
}
return true;
}
static bool checkAcquireCapabilityAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<FunctionDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedFunction;
return false;
}
return true;
}
static unsigned AcquireCapabilityAttrSpellingMap(const AttributeList &Attr) {
enum Spelling {
GNU_acquire_capability = 0,
CXX11_clang_acquire_capability = 1,
GNU_acquire_shared_capability = 2,
CXX11_clang_acquire_shared_capability = 3,
GNU_exclusive_lock_function = 4,
GNU_shared_lock_function = 5
};
unsigned Idx = Attr.getAttributeSpellingListIndex();
switch (Idx) {
default: llvm_unreachable("Unknown spelling list index");
case 0: return GNU_acquire_capability;
case 1: return CXX11_clang_acquire_capability;
case 2: return GNU_acquire_shared_capability;
case 3: return CXX11_clang_acquire_shared_capability;
case 4: return GNU_exclusive_lock_function;
case 5: return GNU_shared_lock_function;
}
}
static bool isSharedVar(const Decl *D) {
if (const auto *S = dyn_cast<VarDecl>(D))
return S->hasGlobalStorage() && !S->getTLSKind();
return false;
}
static bool checkAcquiredAfterAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<FieldDecl>(D) && !isSharedVar(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedFieldOrGlobalVar;
return false;
}
return true;
}
static bool checkAcquiredBeforeAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<FieldDecl>(D) && !isSharedVar(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedFieldOrGlobalVar;
return false;
}
return true;
}
static bool isGlobalVar(const Decl *D) {
if (const auto *S = dyn_cast<VarDecl>(D))
return S->hasGlobalStorage();
return false;
}
static bool checkAliasAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<FunctionDecl>(D) && !isGlobalVar(D)) {
S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedFunctionGlobalVarMethodOrProperty;
return false;
}
return true;
}
static bool checkAlignValueAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<VarDecl>(D) && !isa<TypedefNameDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedVariableOrTypedef;
return false;
}
return true;
}
static unsigned AlignedAttrSpellingMap(const AttributeList &Attr) {
enum Spelling {
GNU_aligned = 0,
CXX11_gnu_aligned = 1,
Declspec_align = 2,
Keyword_alignas = 3,
Keyword_Alignas = 4
};
unsigned Idx = Attr.getAttributeSpellingListIndex();
switch (Idx) {
default: llvm_unreachable("Unknown spelling list index");
case 0: return GNU_aligned;
case 1: return CXX11_gnu_aligned;
case 2: return Declspec_align;
case 3: return Keyword_alignas;
case 4: return Keyword_Alignas;
}
}
static bool checkAlwaysInlineAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<FunctionDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedFunction;
return false;
}
return true;
}
static unsigned AlwaysInlineAttrSpellingMap(const AttributeList &Attr) {
enum Spelling {
GNU_always_inline = 0,
CXX11_gnu_always_inline = 1,
Keyword_forceinline = 2
};
unsigned Idx = Attr.getAttributeSpellingListIndex();
switch (Idx) {
default: llvm_unreachable("Unknown spelling list index");
case 0: return GNU_always_inline;
case 1: return CXX11_gnu_always_inline;
case 2: return Keyword_forceinline;
}
}
static bool checkArcWeakrefUnavailableAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<ObjCInterfaceDecl>(D)) {
S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedObjectiveCInterface;
return false;
}
return true;
}
static unsigned ArgumentWithTypeTagAttrSpellingMap(const AttributeList &Attr) {
enum Spelling {
GNU_argument_with_type_tag = 0,
GNU_pointer_with_type_tag = 1
};
unsigned Idx = Attr.getAttributeSpellingListIndex();
switch (Idx) {
default: llvm_unreachable("Unknown spelling list index");
case 0: return GNU_argument_with_type_tag;
case 1: return GNU_pointer_with_type_tag;
}
}
static bool checkAssertCapabilityAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<FunctionDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedFunction;
return false;
}
return true;
}
static unsigned AssertCapabilityAttrSpellingMap(const AttributeList &Attr) {
enum Spelling {
GNU_assert_capability = 0,
CXX11_clang_assert_capability = 1,
GNU_assert_shared_capability = 2,
CXX11_clang_assert_shared_capability = 3
};
unsigned Idx = Attr.getAttributeSpellingListIndex();
switch (Idx) {
default: llvm_unreachable("Unknown spelling list index");
case 0: return GNU_assert_capability;
case 1: return CXX11_clang_assert_capability;
case 2: return GNU_assert_shared_capability;
case 3: return CXX11_clang_assert_shared_capability;
}
}
static bool checkAssertExclusiveLockAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<FunctionDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedFunction;
return false;
}
return true;
}
static bool checkAssertSharedLockAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<FunctionDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedFunction;
return false;
}
return true;
}
static bool checkAssumeAlignedAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<ObjCMethodDecl>(D) && !isa<FunctionDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedFunctionOrMethod;
return false;
}
return true;
}
static bool checkCFAuditedTransferAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<FunctionDecl>(D)) {
S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedFunction;
return false;
}
return true;
}
static bool checkCFConsumedAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<ParmVarDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedParameter;
return false;
}
return true;
}
static bool checkCFUnknownTransferAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<FunctionDecl>(D)) {
S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedFunction;
return false;
}
return true;
}
static bool checkCUDAConstantAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<VarDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedVariable;
return false;
}
return true;
}
static bool checkCUDALangOpts(Sema &S, const AttributeList &Attr) {
if (S.LangOpts.CUDA)
return true;
S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
return false;
}
static bool checkCUDADeviceAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedVariableOrFunction;
return false;
}
return true;
}
static bool checkCUDAGlobalAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<FunctionDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedFunction;
return false;
}
return true;
}
static bool checkCUDAHostAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<FunctionDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedFunction;
return false;
}
return true;
}
static bool checkCUDAInvalidTargetAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<FunctionDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedFunction;
return false;
}
return true;
}
static bool isFunctionLike(const Decl *D) {
if (const auto *S = dyn_cast<Decl>(D))
return S->getFunctionType(false) != nullptr;
return false;
}
static bool checkCUDALaunchBoundsAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<ObjCMethodDecl>(D) && !isFunctionLike(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedFunctionOrMethod;
return false;
}
return true;
}
static bool checkCUDASharedAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<VarDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedVariable;
return false;
}
return true;
}
static bool checkCXX11NoReturnAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<FunctionDecl>(D)) {
S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedFunction;
return false;
}
return true;
}
static bool checkCallableWhenAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<CXXMethodDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedMethod;
return false;
}
return true;
}
static bool checkCapabilityAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<RecordDecl>(D) && !isa<TypedefNameDecl>(D)) {
S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedStructOrUnionOrTypedef;
return false;
}
return true;
}
static unsigned CapabilityAttrSpellingMap(const AttributeList &Attr) {
enum Spelling {
GNU_capability = 0,
CXX11_clang_capability = 1,
GNU_shared_capability = 2,
CXX11_clang_shared_capability = 3
};
unsigned Idx = Attr.getAttributeSpellingListIndex();
switch (Idx) {
default: llvm_unreachable("Unknown spelling list index");
case 0: return GNU_capability;
case 1: return CXX11_clang_capability;
case 2: return GNU_shared_capability;
case 3: return CXX11_clang_shared_capability;
}
}
static bool checkCarriesDependencyAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<ParmVarDecl>(D) && !isa<ObjCMethodDecl>(D) && !isa<FunctionDecl>(D)) {
S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedFunctionMethodOrParameter;
return false;
}
return true;
}
static bool checkCleanupAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<VarDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedVariable;
return false;
}
return true;
}
static bool checkColdAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<FunctionDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedFunction;
return false;
}
return true;
}
static bool checkCommonAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<VarDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedVariable;
return false;
}
return true;
}
static bool checkConstructorAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<FunctionDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedFunction;
return false;
}
return true;
}
static bool checkConsumableAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<CXXRecordDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedClass;
return false;
}
return true;
}
static bool checkConsumableAutoCastAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<CXXRecordDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedClass;
return false;
}
return true;
}
static bool checkConsumableSetOnReadAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<CXXRecordDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedClass;
return false;
}
return true;
}
static bool checkDLLExportAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D) && !isa<CXXRecordDecl>(D) && !isa<ObjCInterfaceDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << (S.getLangOpts().CPlusPlus ? ((S.getLangOpts().ObjC1 || S.getLangOpts().ObjC2) ? ExpectedFunctionVariableClassOrObjCInterface : ExpectedFunctionVariableOrClass) : ((S.getLangOpts().ObjC1 || S.getLangOpts().ObjC2) ? ExpectedFunctionVariableOrObjCInterface : ExpectedVariableOrFunction));
return false;
}
return true;
}
static bool isTargetx86x86_64armthumbWin32(const TargetInfo &Target) {
const llvm::Triple &T = Target.getTriple();
return (T.getArch() == llvm::Triple::x86 || T.getArch() == llvm::Triple::x86_64 || T.getArch() == llvm::Triple::arm || T.getArch() == llvm::Triple::thumb) && (T.getOS() == llvm::Triple::Win32);
}
static bool checkDLLImportAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D) && !isa<CXXRecordDecl>(D) && !isa<ObjCInterfaceDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << (S.getLangOpts().CPlusPlus ? ((S.getLangOpts().ObjC1 || S.getLangOpts().ObjC2) ? ExpectedFunctionVariableClassOrObjCInterface : ExpectedFunctionVariableOrClass) : ((S.getLangOpts().ObjC1 || S.getLangOpts().ObjC2) ? ExpectedFunctionVariableOrObjCInterface : ExpectedVariableOrFunction));
return false;
}
return true;
}
static bool checkDestructorAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<FunctionDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedFunction;
return false;
}
return true;
}
static bool checkDisableTailCallsAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<FunctionDecl>(D) && !isa<ObjCMethodDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedFunctionOrMethod;
return false;
}
return true;
}
static bool checkEmptyBasesAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<CXXRecordDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedClass;
return false;
}
return true;
}
static bool isTargetx86x86_64armthumbMicrosoft(const TargetInfo &Target) {
const llvm::Triple &T = Target.getTriple();
return (T.getArch() == llvm::Triple::x86 || T.getArch() == llvm::Triple::x86_64 || T.getArch() == llvm::Triple::arm || T.getArch() == llvm::Triple::thumb) && (Target.getCXXABI().getKind() == TargetCXXABI::Microsoft);
}
static bool checkEnableIfAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<FunctionDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedFunction;
return false;
}
return true;
}
static bool checkExclusiveTrylockFunctionAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<FunctionDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedFunction;
return false;
}
return true;
}
static bool checkExtVectorTypeAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<TypedefNameDecl>(D)) {
S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedType;
return false;
}
return true;
}
static bool checkFlagEnumAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<EnumDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedEnum;
return false;
}
return true;
}
static bool checkNotCPlusPlusLangOpts(Sema &S, const AttributeList &Attr) {
if (!S.LangOpts.CPlusPlus)
return true;
S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
return false;
}
static bool checkFlattenAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<FunctionDecl>(D)) {
S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedFunction;
return false;
}
return true;
}
static bool isHasFunctionProto(const Decl *D) {
if (const auto *S = dyn_cast<Decl>(D))
return (S->getFunctionType(true) != nullptr &&
isa<FunctionProtoType>(S->getFunctionType())) ||
isa<ObjCMethodDecl>(S) ||
isa<BlockDecl>(S);
return false;
}
static bool checkFormatAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<ObjCMethodDecl>(D) && !isa<BlockDecl>(D) && !isHasFunctionProto(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedFunctionWithProtoType;
return false;
}
return true;
}
static bool checkFormatArgAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<ObjCMethodDecl>(D) && !isHasFunctionProto(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedFunctionWithProtoType;
return false;
}
return true;
}
static bool checkGNUInlineAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<FunctionDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedFunction;
return false;
}
return true;
}
static bool checkGuardedByAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<FieldDecl>(D) && !isSharedVar(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedFieldOrGlobalVar;
return false;
}
return true;
}
static bool checkGuardedVarAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<FieldDecl>(D) && !isSharedVar(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedFieldOrGlobalVar;
return false;
}
return true;
}
static bool checkHotAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<FunctionDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedFunction;
return false;
}
return true;
}
static bool isObjCInstanceMethod(const Decl *D) {
if (const auto *S = dyn_cast<ObjCMethodDecl>(D))
return S->isInstanceMethod();
return false;
}
static bool checkIBActionAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isObjCInstanceMethod(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedObjCInstanceMethod;
return false;
}
return true;
}
static bool checkIFuncAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<FunctionDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedFunction;
return false;
}
return true;
}
static bool checkInitPriorityAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<VarDecl>(D)) {
S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedVariable;
return false;
}
return true;
}
static bool checkInternalLinkageAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D) && !isa<CXXRecordDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << (S.getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass : ExpectedVariableOrFunction);
return false;
}
return true;
}
static bool checkLTOVisibilityPublicAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<RecordDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << (S.getLangOpts().CPlusPlus ? ExpectedStructOrUnionOrClass : ExpectedStructOrUnion);
return false;
}
return true;
}
static bool checkLayoutVersionAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<CXXRecordDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedClass;
return false;
}
return true;
}
static bool checkLockReturnedAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<FunctionDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedFunction;
return false;
}
return true;
}
static bool checkLockableAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<RecordDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << (S.getLangOpts().CPlusPlus ? ExpectedStructOrUnionOrClass : ExpectedStructOrUnion);
return false;
}
return true;
}
static bool checkLocksExcludedAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<FunctionDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedFunction;
return false;
}
return true;
}
static unsigned LoopHintAttrSpellingMap(const AttributeList &Attr) {
enum Spelling {
Pragma_clang_loop = 0,
Pragma_unroll = 1,
Pragma_nounroll = 2
};
unsigned Idx = Attr.getAttributeSpellingListIndex();
switch (Idx) {
default: llvm_unreachable("Unknown spelling list index");
case 0: return Pragma_clang_loop;
case 1: return Pragma_unroll;
case 2: return Pragma_nounroll;
}
}
static bool checkMicrosoftExtLangOpts(Sema &S, const AttributeList &Attr) {
if (S.LangOpts.MicrosoftExt)
return true;
S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
return false;
}
static unsigned MSInheritanceAttrSpellingMap(const AttributeList &Attr) {
enum Spelling {
Keyword_single_inheritance = 0,
Keyword_multiple_inheritance = 1,
Keyword_virtual_inheritance = 2,
Keyword_unspecified_inheritance = 3
};
unsigned Idx = Attr.getAttributeSpellingListIndex();
switch (Idx) {
default: llvm_unreachable("Unknown spelling list index");
case 0: return Keyword_single_inheritance;
case 1: return Keyword_multiple_inheritance;
case 2: return Keyword_virtual_inheritance;
case 3: return Keyword_unspecified_inheritance;
}
}
static bool checkMSNoVTableAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<CXXRecordDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedClass;
return false;
}
return true;
}
static bool checkMSStructAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<RecordDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << (S.getLangOpts().CPlusPlus ? ExpectedStructOrUnionOrClass : ExpectedStructOrUnion);
return false;
}
return true;
}
static bool checkMinSizeAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<FunctionDecl>(D) && !isa<ObjCMethodDecl>(D)) {
S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedFunctionOrMethod;
return false;
}
return true;
}
static bool checkMips16AppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<FunctionDecl>(D)) {
S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedFunction;
return false;
}
return true;
}
static bool isTargetmipsmipsel(const TargetInfo &Target) {
const llvm::Triple &T = Target.getTriple();
return (T.getArch() == llvm::Triple::mips || T.getArch() == llvm::Triple::mipsel);
}
static bool checkModeAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<VarDecl>(D) && !isa<EnumDecl>(D) && !isa<TypedefNameDecl>(D) && !isa<FieldDecl>(D)) {
S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedVariableEnumFieldOrTypedef;
return false;
}
return true;
}
static bool checkNSConsumedAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<ParmVarDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedParameter;
return false;
}
return true;
}
static bool checkNSConsumesSelfAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<ObjCMethodDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedMethod;
return false;
}
return true;
}
static bool checkNakedAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<FunctionDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedFunction;
return false;
}
return true;
}
static bool checkNoAliasAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<FunctionDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedFunction;
return false;
}
return true;
}
static bool checkNoCommonAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<VarDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedVariable;
return false;
}
return true;
}
static bool isNonParmVar(const Decl *D) {
if (const auto *S = dyn_cast<VarDecl>(D))
return S->getKind() != Decl::ParmVar;
return false;
}
static bool checkNoDebugAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isFunctionLike(D) && !isa<ObjCMethodDecl>(D) && !isNonParmVar(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedVariableOrFunction;
return false;
}
return true;
}
static bool checkNoDuplicateAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<FunctionDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedFunction;
return false;
}
return true;
}
static bool checkNoInlineAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<FunctionDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedFunction;
return false;
}
return true;
}
static bool checkNoInstrumentFunctionAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<FunctionDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedFunction;
return false;
}
return true;
}
static bool checkNoMips16AppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<FunctionDecl>(D)) {
S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedFunction;
return false;
}
return true;
}
static bool checkNoSanitizeAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<FunctionDecl>(D) && !isa<ObjCMethodDecl>(D)) {
S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedFunctionOrMethod;
return false;
}
return true;
}
static bool checkNoSanitizeSpecificAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<FunctionDecl>(D)) {
S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedFunction;
return false;
}
return true;
}
static bool checkNoSplitStackAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<FunctionDecl>(D)) {
S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedFunction;
return false;
}
return true;
}
static bool checkNoThreadSafetyAnalysisAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<FunctionDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedFunction;
return false;
}
return true;
}
static bool checkNonNullAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<ObjCMethodDecl>(D) && !isHasFunctionProto(D) && !isa<ParmVarDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedFunctionMethodOrParameter;
return false;
}
return true;
}
static bool checkNotTailCalledAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<FunctionDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedFunction;
return false;
}
return true;
}
static bool checkObjCBoxableAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<RecordDecl>(D)) {
S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedStructOrUnion;
return false;
}
return true;
}
static bool checkObjCBridgeAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<RecordDecl>(D) && !isa<TypedefNameDecl>(D)) {
S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedStructOrUnionOrTypedef;
return false;
}
return true;
}
static bool checkObjCBridgeMutableAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<RecordDecl>(D)) {
S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
<< Attr.getName() << (S.getLangOpts().CPlusPlus ? ExpectedStructOrUnionOrClass : ExpectedStructOrUnion);
return false;
}
return true;
}
static bool checkObjCBridgeRelatedAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<RecordDecl>(D)) {
S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
<< Attr.getName() << (S.getLangOpts().CPlusPlus ? ExpectedStructOrUnionOrClass : ExpectedStructOrUnion);
return false;
}
return true;
}
static bool isObjCInterfaceDeclInitMethod(const Decl *D) {
if (const auto *S = dyn_cast<ObjCMethodDecl>(D))
return S->getMethodFamily() == OMF_init &&
(isa<ObjCInterfaceDecl>(S->getDeclContext()) ||
(isa<ObjCCategoryDecl>(S->getDeclContext()) &&
cast<ObjCCategoryDecl>(S->getDeclContext())->IsClassExtension()));
return false;
}
static bool checkObjCDesignatedInitializerAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isObjCInterfaceDeclInitMethod(D)) {
S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedObjCInterfaceDeclInitMethod;
return false;
}
return true;
}
static bool checkObjCExceptionAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<ObjCInterfaceDecl>(D)) {
S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedObjectiveCInterface;
return false;
}
return true;
}
static bool checkObjCExplicitProtocolImplAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<ObjCProtocolDecl>(D)) {
S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedObjectiveCProtocol;
return false;
}
return true;
}
static bool checkObjCMethodFamilyAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<ObjCMethodDecl>(D)) {
S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedMethod;
return false;
}
return true;
}
static bool checkObjCPreciseLifetimeAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<VarDecl>(D)) {
S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedVariable;
return false;
}
return true;
}
static bool checkObjCRequiresPropertyDefsAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<ObjCInterfaceDecl>(D)) {
S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedObjectiveCInterface;
return false;
}
return true;
}
static bool checkObjCRequiresSuperAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<ObjCMethodDecl>(D)) {
S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedMethod;
return false;
}
return true;
}
static bool checkObjCReturnsInnerPointerAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<ObjCMethodDecl>(D) && !isa<ObjCPropertyDecl>(D)) {
S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedMethodOrProperty;
return false;
}
return true;
}
static bool checkObjCRootClassAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<ObjCInterfaceDecl>(D)) {
S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedObjectiveCInterface;
return false;
}
return true;
}
static bool checkObjCRuntimeNameAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<ObjCInterfaceDecl>(D) && !isa<ObjCProtocolDecl>(D)) {
S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedObjectiveCInterfaceOrProtocol;
return false;
}
return true;
}
static bool checkObjCRuntimeVisibleAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<ObjCInterfaceDecl>(D)) {
S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedObjectiveCInterface;
return false;
}
return true;
}
static bool checkOpenCLAccessAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<ParmVarDecl>(D) && !isa<TypedefNameDecl>(D)) {
S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedParameterOrTypedef;
return false;
}
return true;
}
static unsigned OpenCLAccessAttrSpellingMap(const AttributeList &Attr) {
enum Spelling {
Keyword_read_only = 0,
Keyword_write_only = 2,
Keyword_read_write = 4
};
unsigned Idx = Attr.getAttributeSpellingListIndex();
switch (Idx) {
default: llvm_unreachable("Unknown spelling list index");
case 0: return Keyword_read_only;
case 1: return Keyword_read_only;
case 2: return Keyword_write_only;
case 3: return Keyword_write_only;
case 4: return Keyword_read_write;
case 5: return Keyword_read_write;
}
}
static bool checkOpenCLKernelAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<FunctionDecl>(D)) {
S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedFunction;
return false;
}
return true;
}
static bool checkOpenCLNoSVMAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<VarDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedVariable;
return false;
}
return true;
}
static bool checkOpenCLLangOpts(Sema &S, const AttributeList &Attr) {
if (S.LangOpts.OpenCL)
return true;
S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
return false;
}
static bool checkOptimizeNoneAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<FunctionDecl>(D) && !isa<ObjCMethodDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedFunctionOrMethod;
return false;
}
return true;
}
static bool checkOverloadableAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<FunctionDecl>(D)) {
S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedFunction;
return false;
}
return true;
}
static bool checkOwnershipAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isHasFunctionProto(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedFunctionWithProtoType;
return false;
}
return true;
}
static unsigned OwnershipAttrSpellingMap(const AttributeList &Attr) {
enum Spelling {
GNU_ownership_holds = 0,
GNU_ownership_returns = 1,
GNU_ownership_takes = 2
};
unsigned Idx = Attr.getAttributeSpellingListIndex();
switch (Idx) {
default: llvm_unreachable("Unknown spelling list index");
case 0: return GNU_ownership_holds;
case 1: return GNU_ownership_returns;
case 2: return GNU_ownership_takes;
}
}
static bool checkParamTypestateAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<ParmVarDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedParameter;
return false;
}
return true;
}
static bool checkPassObjectSizeAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<ParmVarDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedParameter;
return false;
}
return true;
}
static bool checkPtGuardedByAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<FieldDecl>(D) && !isSharedVar(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedFieldOrGlobalVar;
return false;
}
return true;
}
static bool checkPtGuardedVarAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<FieldDecl>(D) && !isSharedVar(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedFieldOrGlobalVar;
return false;
}
return true;
}
static bool checkReleaseCapabilityAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<FunctionDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedFunction;
return false;
}
return true;
}
static unsigned ReleaseCapabilityAttrSpellingMap(const AttributeList &Attr) {
enum Spelling {
GNU_release_capability = 0,
CXX11_clang_release_capability = 1,
GNU_release_shared_capability = 2,
CXX11_clang_release_shared_capability = 3,
GNU_release_generic_capability = 4,
CXX11_clang_release_generic_capability = 5,
GNU_unlock_function = 6
};
unsigned Idx = Attr.getAttributeSpellingListIndex();
switch (Idx) {
default: llvm_unreachable("Unknown spelling list index");
case 0: return GNU_release_capability;
case 1: return CXX11_clang_release_capability;
case 2: return GNU_release_shared_capability;
case 3: return CXX11_clang_release_shared_capability;
case 4: return GNU_release_generic_capability;
case 5: return CXX11_clang_release_generic_capability;
case 6: return GNU_unlock_function;
}
}
static bool checkRenderScriptKernelAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<FunctionDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedFunction;
return false;
}
return true;
}
static bool checkRenderScriptLangOpts(Sema &S, const AttributeList &Attr) {
if (S.LangOpts.RenderScript)
return true;
S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
return false;
}
static bool checkReqdWorkGroupSizeAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<FunctionDecl>(D)) {
S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedFunction;
return false;
}
return true;
}
static bool checkRequireConstantInitAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isGlobalVar(D)) {
S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedStaticOrTLSVar;
return false;
}
return true;
}
static bool checkCPlusPlusLangOpts(Sema &S, const AttributeList &Attr) {
if (S.LangOpts.CPlusPlus)
return true;
S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
return false;
}
static bool checkRequiresCapabilityAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<FunctionDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedFunction;
return false;
}
return true;
}
static unsigned RequiresCapabilityAttrSpellingMap(const AttributeList &Attr) {
enum Spelling {
GNU_requires_capability = 0,
CXX11_clang_requires_capability = 1,
GNU_exclusive_locks_required = 2,
GNU_requires_shared_capability = 3,
CXX11_clang_requires_shared_capability = 4,
GNU_shared_locks_required = 5
};
unsigned Idx = Attr.getAttributeSpellingListIndex();
switch (Idx) {
default: llvm_unreachable("Unknown spelling list index");
case 0: return GNU_requires_capability;
case 1: return CXX11_clang_requires_capability;
case 2: return GNU_exclusive_locks_required;
case 3: return GNU_requires_shared_capability;
case 4: return CXX11_clang_requires_shared_capability;
case 5: return GNU_shared_locks_required;
}
}
static bool checkRestrictAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<FunctionDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedFunction;
return false;
}
return true;
}
static unsigned RestrictAttrSpellingMap(const AttributeList &Attr) {
enum Spelling {
Declspec_restrict = 0,
GNU_malloc = 1,
CXX11_gnu_malloc = 2
};
unsigned Idx = Attr.getAttributeSpellingListIndex();
switch (Idx) {
default: llvm_unreachable("Unknown spelling list index");
case 0: return Declspec_restrict;
case 1: return GNU_malloc;
case 2: return CXX11_gnu_malloc;
}
}
static bool checkReturnTypestateAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<FunctionDecl>(D) && !isa<ParmVarDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedFunctionMethodOrParameter;
return false;
}
return true;
}
static bool checkReturnsNonNullAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<ObjCMethodDecl>(D) && !isa<FunctionDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedFunctionOrMethod;
return false;
}
return true;
}
static bool checkReturnsTwiceAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<FunctionDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedFunction;
return false;
}
return true;
}
static bool checkScopedLockableAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<RecordDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << (S.getLangOpts().CPlusPlus ? ExpectedStructOrUnionOrClass : ExpectedStructOrUnion);
return false;
}
return true;
}
static bool checkSectionAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<FunctionDecl>(D) && !isGlobalVar(D) && !isa<ObjCMethodDecl>(D) && !isa<ObjCPropertyDecl>(D)) {
S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedFunctionGlobalVarMethodOrProperty;
return false;
}
return true;
}
static unsigned SectionAttrSpellingMap(const AttributeList &Attr) {
enum Spelling {
GNU_section = 0,
CXX11_gnu_section = 1,
Declspec_allocate = 2
};
unsigned Idx = Attr.getAttributeSpellingListIndex();
switch (Idx) {
default: llvm_unreachable("Unknown spelling list index");
case 0: return GNU_section;
case 1: return CXX11_gnu_section;
case 2: return Declspec_allocate;
}
}
static bool checkSetTypestateAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<CXXMethodDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedMethod;
return false;
}
return true;
}
static bool checkSharedTrylockFunctionAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<FunctionDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedFunction;
return false;
}
return true;
}
static bool checkSwiftContextAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<ParmVarDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedParameter;
return false;
}
return true;
}
static bool checkSwiftErrorResultAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<ParmVarDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedParameter;
return false;
}
return true;
}
static bool checkSwiftIndirectResultAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<ParmVarDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedParameter;
return false;
}
return true;
}
static bool isTLSVar(const Decl *D) {
if (const auto *S = dyn_cast<VarDecl>(D))
return S->getTLSKind() != 0;
return false;
}
static bool checkTLSModelAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isTLSVar(D)) {
S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedTLSVar;
return false;
}
return true;
}
static bool checkTargetAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<FunctionDecl>(D)) {
S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedFunction;
return false;
}
return true;
}
static bool checkTestTypestateAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<CXXMethodDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedMethod;
return false;
}
return true;
}
static bool checkThreadAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<VarDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedVariable;
return false;
}
return true;
}
static bool checkTryAcquireCapabilityAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<FunctionDecl>(D)) {
S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedFunction;
return false;
}
return true;
}
static unsigned TryAcquireCapabilityAttrSpellingMap(const AttributeList &Attr) {
enum Spelling {
GNU_try_acquire_capability = 0,
CXX11_clang_try_acquire_capability = 1,
GNU_try_acquire_shared_capability = 2,
CXX11_clang_try_acquire_shared_capability = 3
};
unsigned Idx = Attr.getAttributeSpellingListIndex();
switch (Idx) {
default: llvm_unreachable("Unknown spelling list index");
case 0: return GNU_try_acquire_capability;
case 1: return CXX11_clang_try_acquire_capability;
case 2: return GNU_try_acquire_shared_capability;
case 3: return CXX11_clang_try_acquire_shared_capability;
}
}
static bool checkUnusedAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<VarDecl>(D) && !isa<ObjCIvarDecl>(D) && !isa<TypeDecl>(D) && !isa<EnumDecl>(D) && !isa<EnumConstantDecl>(D) && !isa<LabelDecl>(D) && !isa<FieldDecl>(D) && !isa<ObjCMethodDecl>(D) && !isFunctionLike(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedForMaybeUnused;
return false;
}
return true;
}
static unsigned UnusedAttrSpellingMap(const AttributeList &Attr) {
enum Spelling {
CXX11_maybe_unused = 0,
GNU_unused = 1,
CXX11_gnu_unused = 2
};
unsigned Idx = Attr.getAttributeSpellingListIndex();
switch (Idx) {
default: llvm_unreachable("Unknown spelling list index");
case 0: return CXX11_maybe_unused;
case 1: return GNU_unused;
case 2: return CXX11_gnu_unused;
}
}
static bool checkMicrosoftExtBorlandLangOpts(Sema &S, const AttributeList &Attr) {
if (S.LangOpts.MicrosoftExt || S.LangOpts.Borland)
return true;
S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
return false;
}
static bool checkVecReturnAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<CXXRecordDecl>(D)) {
S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedClass;
return false;
}
return true;
}
static bool checkVecTypeHintAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<FunctionDecl>(D)) {
S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedFunction;
return false;
}
return true;
}
static bool checkWarnUnusedAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<RecordDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << (S.getLangOpts().CPlusPlus ? ExpectedStructOrUnionOrClass : ExpectedStructOrUnion);
return false;
}
return true;
}
static bool checkWarnUnusedResultAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<ObjCMethodDecl>(D) && !isa<EnumDecl>(D) && !isa<CXXRecordDecl>(D) && !isFunctionLike(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedFunctionMethodEnumOrClass;
return false;
}
return true;
}
static unsigned WarnUnusedResultAttrSpellingMap(const AttributeList &Attr) {
enum Spelling {
CXX11_nodiscard = 0,
CXX11_clang_warn_unused_result = 1,
GNU_warn_unused_result = 2,
CXX11_gnu_warn_unused_result = 3
};
unsigned Idx = Attr.getAttributeSpellingListIndex();
switch (Idx) {
default: llvm_unreachable("Unknown spelling list index");
case 0: return CXX11_nodiscard;
case 1: return CXX11_clang_warn_unused_result;
case 2: return GNU_warn_unused_result;
case 3: return CXX11_gnu_warn_unused_result;
}
}
static bool checkWeakAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D) && !isa<CXXRecordDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << (S.getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass : ExpectedVariableOrFunction);
return false;
}
return true;
}
static bool checkWeakRefAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D)) {
S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedVariableOrFunction;
return false;
}
return true;
}
static bool checkWorkGroupSizeHintAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<FunctionDecl>(D)) {
S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedFunction;
return false;
}
return true;
}
static bool isTargetx86(const TargetInfo &Target) {
const llvm::Triple &T = Target.getTriple();
return (T.getArch() == llvm::Triple::x86);
}
static bool checkXRayInstrumentAppertainsTo(Sema &S, const AttributeList &Attr, const Decl *D) {
if (!isa<CXXMethodDecl>(D) && !isa<ObjCMethodDecl>(D) && !isa<FunctionDecl>(D)) {
S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
<< Attr.getName() << ExpectedFunctionOrMethod;
return false;
}
return true;
}
static unsigned XRayInstrumentAttrSpellingMap(const AttributeList &Attr) {
enum Spelling {
GNU_xray_always_instrument = 0,
CXX11_clang_xray_always_instrument = 1,
GNU_xray_never_instrument = 2,
CXX11_clang_xray_never_instrument = 3
};
unsigned Idx = Attr.getAttributeSpellingListIndex();
switch (Idx) {
default: llvm_unreachable("Unknown spelling list index");
case 0: return GNU_xray_always_instrument;
case 1: return CXX11_clang_xray_always_instrument;
case 2: return GNU_xray_never_instrument;
case 3: return CXX11_clang_xray_never_instrument;
}
}
static const ParsedAttrInfo AttrInfoMap[AttributeList::UnknownAttribute + 1] = {
{ 1, 0, 0, 0, 0, 0, 0, checkAMDGPUNumSGPRAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_AMDGPUNumSGPR
{ 1, 0, 0, 0, 0, 0, 0, checkAMDGPUNumVGPRAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_AMDGPUNumVGPR
{ 0, 1, 1, 1, 0, 0, 0, defaultAppertainsTo, defaultDiagnoseLangOpts, isTargetarmthumbx86x86_64msp430mipsmipsel, defaultSpellingIndexToSemanticSpelling }, // AT_Interrupt
{ 0, 15, 0, 0, 0, 0, 1, checkAbiTagAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_AbiTag
{ 0, 15, 0, 0, 0, 0, 0, checkAcquireCapabilityAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, AcquireCapabilityAttrSpellingMap }, // AT_AcquireCapability
{ 0, 15, 0, 0, 0, 0, 0, checkAcquiredAfterAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_AcquiredAfter
{ 0, 15, 0, 0, 0, 0, 0, checkAcquiredBeforeAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_AcquiredBefore
{ 1, 0, 0, 0, 1, 0, 0, defaultAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_AddressSpace
{ 1, 0, 0, 0, 0, 0, 1, checkAliasAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_Alias
{ 1, 0, 0, 0, 0, 0, 0, checkAlignValueAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_AlignValue
{ 0, 1, 0, 0, 0, 0, 1, defaultAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, AlignedAttrSpellingMap }, // AT_Aligned
{ 0, 0, 0, 0, 0, 0, 1, checkAlwaysInlineAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, AlwaysInlineAttrSpellingMap }, // AT_AlwaysInline
{ 0, 0, 0, 0, 0, 0, 0, defaultAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_AnalyzerNoReturn
{ 1, 0, 0, 0, 0, 0, 0, defaultAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_Annotate
{ 0, 0, 0, 0, 0, 0, 0, checkArcWeakrefUnavailableAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_ArcWeakrefUnavailable
{ 4, 0, 1, 0, 0, 0, 0, defaultAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, ArgumentWithTypeTagAttrSpellingMap }, // AT_ArgumentWithTypeTag
{ 1, 0, 0, 0, 0, 0, 0, checkAssertCapabilityAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, AssertCapabilityAttrSpellingMap }, // AT_AssertCapability
{ 0, 15, 0, 0, 0, 0, 0, checkAssertExclusiveLockAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_AssertExclusiveLock
{ 0, 15, 0, 0, 0, 0, 0, checkAssertSharedLockAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_AssertSharedLock
{ 1, 1, 0, 0, 0, 0, 1, checkAssumeAlignedAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_AssumeAligned
{ 8, 0, 1, 0, 0, 0, 0, defaultAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_Availability
{ 1, 0, 0, 0, 0, 0, 0, defaultAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_Blocks
{ 0, 0, 0, 0, 0, 0, 1, defaultAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_CDecl
{ 0, 0, 0, 0, 0, 0, 0, checkCFAuditedTransferAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_CFAuditedTransfer
{ 0, 0, 0, 0, 0, 0, 0, checkCFConsumedAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_CFConsumed
{ 0, 0, 0, 0, 0, 0, 0, defaultAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_CFReturnsNotRetained
{ 0, 0, 0, 0, 0, 0, 0, defaultAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_CFReturnsRetained
{ 0, 0, 0, 0, 0, 0, 0, checkCFUnknownTransferAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_CFUnknownTransfer
{ 0, 0, 0, 0, 0, 0, 0, checkCUDAConstantAppertainsTo, checkCUDALangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_CUDAConstant
{ 0, 0, 0, 0, 0, 0, 0, checkCUDADeviceAppertainsTo, checkCUDALangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_CUDADevice
{ 0, 0, 0, 0, 0, 0, 0, checkCUDAGlobalAppertainsTo, checkCUDALangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_CUDAGlobal
{ 0, 0, 0, 0, 0, 0, 0, checkCUDAHostAppertainsTo, checkCUDALangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_CUDAHost
{ 0, 0, 0, 0, 0, 0, 0, checkCUDAInvalidTargetAppertainsTo, checkCUDALangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_CUDAInvalidTarget
{ 1, 1, 0, 0, 0, 0, 0, checkCUDALaunchBoundsAppertainsTo, checkCUDALangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_CUDALaunchBounds
{ 0, 0, 0, 0, 0, 0, 0, checkCUDASharedAppertainsTo, checkCUDALangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_CUDAShared
{ 0, 0, 0, 0, 0, 0, 0, checkCXX11NoReturnAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_CXX11NoReturn
{ 0, 15, 0, 0, 0, 0, 0, checkCallableWhenAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_CallableWhen
{ 1, 0, 0, 0, 0, 0, 0, checkCapabilityAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, CapabilityAttrSpellingMap }, // AT_Capability
{ 0, 0, 0, 0, 0, 0, 0, checkCarriesDependencyAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_CarriesDependency
{ 1, 0, 0, 0, 0, 0, 1, checkCleanupAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_Cleanup
{ 0, 0, 0, 0, 0, 0, 1, checkColdAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_Cold
{ 0, 0, 0, 0, 0, 0, 1, checkCommonAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_Common
{ 0, 0, 0, 0, 0, 0, 1, defaultAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_Const
{ 0, 1, 0, 0, 0, 0, 1, checkConstructorAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_Constructor
{ 1, 0, 0, 0, 0, 0, 0, checkConsumableAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_Consumable
{ 0, 0, 0, 0, 0, 0, 0, checkConsumableAutoCastAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_ConsumableAutoCast
{ 0, 0, 0, 0, 0, 0, 0, checkConsumableSetOnReadAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_ConsumableSetOnRead
{ 0, 0, 0, 1, 0, 0, 1, checkDLLExportAppertainsTo, defaultDiagnoseLangOpts, isTargetx86x86_64armthumbWin32, defaultSpellingIndexToSemanticSpelling }, // AT_DLLExport
{ 0, 0, 0, 1, 0, 0, 1, checkDLLImportAppertainsTo, defaultDiagnoseLangOpts, isTargetx86x86_64armthumbWin32, defaultSpellingIndexToSemanticSpelling }, // AT_DLLImport
{ 0, 2, 0, 0, 0, 0, 1, defaultAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_Deprecated
{ 0, 1, 0, 0, 0, 0, 1, checkDestructorAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_Destructor
{ 0, 0, 0, 0, 0, 0, 0, checkDisableTailCallsAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_DisableTailCalls
{ 0, 0, 0, 1, 0, 0, 0, checkEmptyBasesAppertainsTo, defaultDiagnoseLangOpts, isTargetx86x86_64armthumbMicrosoft, defaultSpellingIndexToSemanticSpelling }, // AT_EmptyBases
{ 2, 0, 0, 0, 0, 0, 0, checkEnableIfAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_EnableIf
{ 1, 15, 0, 0, 0, 0, 0, checkExclusiveTrylockFunctionAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_ExclusiveTrylockFunction
{ 1, 0, 0, 0, 0, 0, 0, checkExtVectorTypeAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_ExtVectorType
{ 0, 0, 0, 0, 0, 1, 0, defaultAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_FallThrough
{ 0, 0, 0, 0, 0, 0, 1, defaultAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_FastCall
{ 0, 0, 0, 0, 0, 0, 0, checkFlagEnumAppertainsTo, checkNotCPlusPlusLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_FlagEnum
{ 0, 0, 0, 0, 0, 0, 1, checkFlattenAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_Flatten
{ 3, 0, 0, 0, 0, 0, 1, checkFormatAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_Format
{ 1, 0, 0, 0, 0, 0, 1, checkFormatArgAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_FormatArg
{ 0, 0, 0, 0, 0, 0, 1, checkGNUInlineAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_GNUInline
{ 1, 0, 0, 0, 0, 0, 0, checkGuardedByAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_GuardedBy
{ 0, 0, 0, 0, 0, 0, 0, checkGuardedVarAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_GuardedVar
{ 0, 0, 0, 0, 0, 0, 1, checkHotAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_Hot
{ 0, 0, 0, 0, 0, 0, 0, checkIBActionAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_IBAction
{ 0, 0, 0, 0, 0, 0, 0, defaultAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_IBOutlet
{ 0, 1, 0, 0, 0, 0, 0, defaultAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_IBOutletCollection
{ 1, 0, 0, 0, 0, 0, 1, checkIFuncAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_IFunc
{ 1, 0, 0, 0, 0, 0, 0, checkInitPriorityAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_InitPriority
{ 0, 0, 0, 0, 0, 0, 0, defaultAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_IntelOclBicc
{ 0, 0, 0, 0, 0, 0, 0, checkInternalLinkageAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_InternalLinkage
{ 0, 0, 0, 0, 0, 0, 0, checkLTOVisibilityPublicAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_LTOVisibilityPublic
{ 1, 0, 0, 1, 0, 0, 0, checkLayoutVersionAppertainsTo, defaultDiagnoseLangOpts, isTargetx86x86_64armthumbMicrosoft, defaultSpellingIndexToSemanticSpelling }, // AT_LayoutVersion
{ 1, 0, 0, 0, 0, 0, 0, checkLockReturnedAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_LockReturned
{ 0, 0, 0, 0, 0, 0, 0, checkLockableAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_Lockable
{ 0, 15, 0, 0, 0, 0, 0, checkLocksExcludedAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_LocksExcluded
{ 3, 0, 0, 0, 0, 0, 0, defaultAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, LoopHintAttrSpellingMap }, // AT_LoopHint
{ 0, 0, 0, 0, 0, 0, 1, defaultAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_MSABI
{ 0, 1, 0, 0, 0, 0, 0, defaultAppertainsTo, checkMicrosoftExtLangOpts, defaultTargetRequirements, MSInheritanceAttrSpellingMap }, // AT_MSInheritance
{ 0, 0, 0, 1, 0, 0, 0, checkMSNoVTableAppertainsTo, defaultDiagnoseLangOpts, isTargetx86x86_64armthumbMicrosoft, defaultSpellingIndexToSemanticSpelling }, // AT_MSNoVTable
{ 0, 0, 0, 0, 0, 0, 1, checkMSStructAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_MSStruct
{ 0, 0, 0, 0, 0, 0, 1, defaultAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_MayAlias
{ 0, 0, 0, 0, 0, 0, 0, checkMinSizeAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_MinSize
{ 0, 0, 0, 1, 0, 0, 1, checkMips16AppertainsTo, defaultDiagnoseLangOpts, isTargetmipsmipsel, defaultSpellingIndexToSemanticSpelling }, // AT_Mips16
{ 1, 0, 0, 0, 0, 0, 1, checkModeAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_Mode
{ 0, 0, 0, 0, 0, 0, 0, checkNSConsumedAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_NSConsumed
{ 0, 0, 0, 0, 0, 0, 0, checkNSConsumesSelfAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_NSConsumesSelf
{ 0, 0, 0, 0, 0, 0, 0, defaultAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_NSReturnsAutoreleased
{ 0, 0, 0, 0, 0, 0, 0, defaultAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_NSReturnsNotRetained
{ 0, 0, 0, 0, 0, 0, 0, defaultAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_NSReturnsRetained
{ 0, 0, 0, 0, 0, 0, 1, checkNakedAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_Naked
{ 1, 0, 0, 0, 1, 0, 0, defaultAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_NeonPolyVectorType
{ 1, 0, 0, 0, 1, 0, 0, defaultAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_NeonVectorType
{ 0, 0, 0, 0, 0, 0, 0, checkNoAliasAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_NoAlias
{ 0, 0, 0, 0, 0, 0, 1, checkNoCommonAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_NoCommon
{ 0, 0, 0, 0, 0, 0, 1, checkNoDebugAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_NoDebug
{ 0, 0, 0, 0, 0, 0, 0, checkNoDuplicateAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_NoDuplicate
{ 0, 0, 0, 0, 0, 0, 1, checkNoInlineAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_NoInline
{ 0, 0, 0, 0, 0, 0, 1, checkNoInstrumentFunctionAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_NoInstrumentFunction
{ 0, 0, 0, 1, 0, 0, 1, checkNoMips16AppertainsTo, defaultDiagnoseLangOpts, isTargetmipsmipsel, defaultSpellingIndexToSemanticSpelling }, // AT_NoMips16
{ 0, 0, 0, 0, 0, 0, 1, defaultAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_NoReturn
{ 0, 15, 0, 0, 0, 0, 0, checkNoSanitizeAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_NoSanitize
{ 0, 0, 0, 0, 0, 0, 1, checkNoSanitizeSpecificAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_NoSanitizeSpecific
{ 0, 0, 0, 0, 0, 0, 1, checkNoSplitStackAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_NoSplitStack
{ 0, 0, 0, 0, 0, 0, 0, checkNoThreadSafetyAnalysisAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_NoThreadSafetyAnalysis
{ 0, 0, 0, 0, 0, 0, 1, defaultAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_NoThrow
{ 0, 15, 0, 0, 0, 0, 1, checkNonNullAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_NonNull
{ 0, 0, 0, 0, 0, 0, 0, checkNotTailCalledAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_NotTailCalled
{ 0, 0, 0, 0, 0, 0, 0, checkObjCBoxableAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_ObjCBoxable
{ 1, 0, 0, 0, 0, 0, 0, checkObjCBridgeAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_ObjCBridge
{ 1, 0, 0, 0, 0, 0, 0, checkObjCBridgeMutableAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_ObjCBridgeMutable
{ 1, 2, 1, 0, 0, 0, 0, checkObjCBridgeRelatedAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_ObjCBridgeRelated
{ 0, 0, 0, 0, 0, 0, 0, checkObjCDesignatedInitializerAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_ObjCDesignatedInitializer
{ 0, 0, 0, 0, 0, 0, 0, checkObjCExceptionAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_ObjCException
{ 0, 0, 0, 0, 0, 0, 0, checkObjCExplicitProtocolImplAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_ObjCExplicitProtocolImpl
{ 1, 0, 0, 0, 1, 0, 0, defaultAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_ObjCGC
{ 0, 0, 0, 0, 0, 0, 0, defaultAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_ObjCIndependentClass
{ 0, 0, 0, 0, 1, 0, 0, defaultAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_ObjCKindOf
{ 1, 0, 0, 0, 0, 0, 0, checkObjCMethodFamilyAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_ObjCMethodFamily
{ 0, 0, 0, 0, 0, 0, 0, defaultAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_ObjCNSObject
{ 1, 0, 0, 0, 0, 0, 0, defaultAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_ObjCOwnership
{ 0, 0, 0, 0, 0, 0, 0, checkObjCPreciseLifetimeAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_ObjCPreciseLifetime
{ 0, 0, 0, 0, 0, 0, 0, checkObjCRequiresPropertyDefsAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_ObjCRequiresPropertyDefs
{ 0, 0, 0, 0, 0, 0, 0, checkObjCRequiresSuperAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_ObjCRequiresSuper
{ 0, 0, 0, 0, 0, 0, 0, checkObjCReturnsInnerPointerAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_ObjCReturnsInnerPointer
{ 0, 0, 0, 0, 0, 0, 0, checkObjCRootClassAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_ObjCRootClass
{ 1, 0, 0, 0, 0, 0, 0, checkObjCRuntimeNameAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_ObjCRuntimeName
{ 0, 0, 0, 0, 0, 0, 0, checkObjCRuntimeVisibleAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_ObjCRuntimeVisible
{ 0, 0, 0, 0, 0, 0, 0, checkOpenCLAccessAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, OpenCLAccessAttrSpellingMap }, // AT_OpenCLAccess
{ 0, 0, 0, 0, 1, 0, 0, defaultAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_OpenCLConstantAddressSpace
{ 0, 0, 0, 0, 1, 0, 0, defaultAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_OpenCLGenericAddressSpace
{ 0, 0, 0, 0, 1, 0, 0, defaultAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_OpenCLGlobalAddressSpace
{ 0, 0, 0, 0, 0, 0, 0, checkOpenCLKernelAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_OpenCLKernel
{ 0, 0, 0, 0, 1, 0, 0, defaultAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_OpenCLLocalAddressSpace
{ 0, 0, 0, 0, 0, 0, 0, checkOpenCLNoSVMAppertainsTo, checkOpenCLLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_OpenCLNoSVM
{ 0, 0, 0, 0, 1, 0, 0, defaultAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_OpenCLPrivateAddressSpace
{ 1, 0, 0, 0, 0, 0, 0, defaultAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_OpenCLUnrollHint
{ 0, 0, 0, 0, 0, 0, 0, checkOptimizeNoneAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_OptimizeNone
{ 0, 0, 0, 0, 0, 0, 0, checkOverloadableAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_Overloadable
{ 1, 15, 0, 0, 0, 0, 0, checkOwnershipAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, OwnershipAttrSpellingMap }, // AT_Ownership
{ 0, 0, 0, 0, 0, 0, 1, defaultAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_Packed
{ 1, 0, 0, 0, 0, 0, 0, checkParamTypestateAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_ParamTypestate
{ 0, 0, 0, 0, 0, 0, 0, defaultAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_Pascal
{ 1, 0, 0, 0, 0, 0, 0, checkPassObjectSizeAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_PassObjectSize
{ 1, 0, 0, 0, 0, 0, 1, defaultAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_Pcs
{ 0, 0, 0, 0, 0, 0, 0, defaultAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_PreserveAll
{ 0, 0, 0, 0, 0, 0, 0, defaultAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_PreserveMost
{ 1, 0, 0, 0, 0, 0, 0, checkPtGuardedByAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_PtGuardedBy
{ 0, 0, 0, 0, 0, 0, 0, checkPtGuardedVarAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_PtGuardedVar
{ 0, 0, 0, 0, 1, 0, 0, defaultAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_Ptr32
{ 0, 0, 0, 0, 1, 0, 0, defaultAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_Ptr64
{ 0, 0, 0, 0, 0, 0, 1, defaultAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_Pure
{ 1, 0, 0, 0, 1, 0, 1, defaultAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_Regparm
{ 0, 15, 0, 0, 0, 0, 0, checkReleaseCapabilityAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, ReleaseCapabilityAttrSpellingMap }, // AT_ReleaseCapability
{ 0, 0, 0, 0, 0, 0, 0, checkRenderScriptKernelAppertainsTo, checkRenderScriptLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_RenderScriptKernel
{ 3, 0, 0, 0, 0, 0, 0, checkReqdWorkGroupSizeAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_ReqdWorkGroupSize
{ 0, 0, 0, 0, 0, 0, 0, checkRequireConstantInitAppertainsTo, checkCPlusPlusLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_RequireConstantInit
{ 0, 15, 0, 0, 0, 0, 0, checkRequiresCapabilityAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, RequiresCapabilityAttrSpellingMap }, // AT_RequiresCapability
{ 0, 0, 0, 0, 0, 0, 1, checkRestrictAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, RestrictAttrSpellingMap }, // AT_Restrict
{ 1, 0, 0, 0, 0, 0, 0, checkReturnTypestateAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_ReturnTypestate
{ 0, 0, 0, 0, 0, 0, 1, checkReturnsNonNullAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_ReturnsNonNull
{ 0, 0, 0, 0, 0, 0, 1, checkReturnsTwiceAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_ReturnsTwice
{ 0, 0, 0, 0, 1, 0, 0, defaultAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_SPtr
{ 0, 0, 0, 0, 0, 0, 0, checkScopedLockableAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_ScopedLockable
{ 1, 0, 0, 0, 0, 0, 1, checkSectionAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, SectionAttrSpellingMap }, // AT_Section
{ 0, 0, 0, 0, 0, 0, 0, defaultAppertainsTo, checkMicrosoftExtLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_SelectAny
{ 0, 2, 0, 0, 0, 0, 1, defaultAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_Sentinel
{ 1, 0, 0, 0, 0, 0, 0, checkSetTypestateAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_SetTypestate
{ 1, 15, 0, 0, 0, 0, 0, checkSharedTrylockFunctionAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_SharedTrylockFunction
{ 0, 0, 0, 0, 0, 0, 1, defaultAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_StdCall
{ 0, 0, 0, 0, 0, 0, 1, defaultAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_SwiftCall
{ 0, 0, 0, 0, 0, 0, 1, checkSwiftContextAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_SwiftContext
{ 0, 0, 0, 0, 0, 0, 1, checkSwiftErrorResultAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_SwiftErrorResult
{ 0, 0, 0, 0, 0, 0, 1, checkSwiftIndirectResultAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_SwiftIndirectResult
{ 0, 0, 0, 0, 0, 0, 1, defaultAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_SysVABI
{ 1, 0, 0, 0, 0, 0, 1, checkTLSModelAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_TLSModel
{ 1, 0, 0, 0, 0, 0, 1, checkTargetAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_Target
{ 1, 0, 0, 0, 0, 0, 0, checkTestTypestateAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_TestTypestate
{ 0, 0, 0, 0, 0, 0, 1, defaultAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_ThisCall
{ 0, 0, 0, 0, 0, 0, 0, checkThreadAppertainsTo, checkMicrosoftExtLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_Thread
{ 0, 0, 0, 0, 0, 0, 1, defaultAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_TransparentUnion
{ 1, 15, 0, 0, 0, 0, 0, checkTryAcquireCapabilityAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, TryAcquireCapabilityAttrSpellingMap }, // AT_TryAcquireCapability
{ 0, 0, 0, 0, 1, 0, 0, defaultAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_TypeNonNull
{ 0, 0, 0, 0, 1, 0, 0, defaultAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_TypeNullUnspecified
{ 0, 0, 0, 0, 1, 0, 0, defaultAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_TypeNullable
{ 4, 0, 1, 0, 0, 0, 0, defaultAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_TypeTagForDatatype
{ 1, 0, 0, 0, 0, 0, 0, defaultAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_TypeVisibility
{ 0, 0, 0, 0, 1, 0, 0, defaultAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_UPtr
{ 0, 2, 0, 0, 0, 0, 0, defaultAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_Unavailable
{ 0, 0, 0, 0, 0, 0, 1, checkUnusedAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, UnusedAttrSpellingMap }, // AT_Unused
{ 0, 0, 0, 0, 0, 0, 1, defaultAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_Used
{ 1, 0, 0, 0, 0, 0, 0, defaultAppertainsTo, checkMicrosoftExtBorlandLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_Uuid
{ 0, 0, 0, 0, 0, 0, 0, checkVecReturnAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_VecReturn
{ 1, 0, 0, 0, 0, 0, 0, checkVecTypeHintAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_VecTypeHint
{ 0, 0, 0, 0, 0, 0, 0, defaultAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_VectorCall
{ 1, 0, 0, 0, 1, 0, 1, defaultAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_VectorSize
{ 1, 0, 0, 0, 0, 0, 1, defaultAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_Visibility
{ 0, 0, 0, 0, 0, 0, 0, checkWarnUnusedAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_WarnUnused
{ 0, 0, 0, 0, 0, 0, 1, checkWarnUnusedResultAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, WarnUnusedResultAttrSpellingMap }, // AT_WarnUnusedResult
{ 0, 0, 0, 0, 0, 0, 1, checkWeakAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_Weak
{ 0, 0, 0, 0, 0, 0, 0, defaultAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_WeakImport
{ 0, 1, 0, 0, 0, 0, 1, checkWeakRefAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_WeakRef
{ 3, 0, 0, 0, 0, 0, 0, checkWorkGroupSizeHintAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, defaultSpellingIndexToSemanticSpelling }, // AT_WorkGroupSizeHint
{ 0, 0, 0, 1, 0, 0, 0, defaultAppertainsTo, defaultDiagnoseLangOpts, isTargetx86, defaultSpellingIndexToSemanticSpelling }, // AT_X86ForceAlignArgPointer
{ 0, 0, 0, 0, 0, 0, 0, checkXRayInstrumentAppertainsTo, defaultDiagnoseLangOpts, defaultTargetRequirements, XRayInstrumentAttrSpellingMap } // AT_XRayInstrument
};
| [
"[email protected]"
]
| |
a8e34e8f865eb9a377cc2b7cb80f4658589b56ee | 453b89ab46797a2a8a42923b0a93e8c71f06f48a | /Lectures/finalprac.cpp | 852f743040b43aeb2f7d485979fad65f17eafcd0 | []
| no_license | abgordon/CS2270 | e3707b5f1444e05ea7ebf90d784f61dc7fb0c482 | 0fb96485dbbe17723771d13483d1142be2dff0ec | refs/heads/master | 2021-01-02T23:08:06.662724 | 2014-03-12T16:36:34 | 2014-03-12T16:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 902 | cpp | #include <iostream>
using namespace std;
void funRecurse(int funParam)
{
if (funParam<35)
{
cout<< "Are you also"<<endl;
return;
}
funRecurse(funParam/10);
cout << "Sick ofthis"<<endl;
funRecurse(funParam/30);
cout<<"Summer Class Too?"<<endl;
}
template <typename Item>
void myfunction(Item& x, Item& y)
{
x = x * 23;
y = y * 13;
}
void moreorless(int* &p)
{
p = NULL;
}
int main()
{
funRecurse(300);
const double*c;
double d = 6969.6966969;
c=&d;
cout << c << endl;
cout << *c << endl;
// *c = 0.0;
// cout << *c <<endl;
// double f = 500.696996;
// c=&f;
// cout << c << endl;
// cout <<d<<endl;
// cout <<f<<endl;
// myfunction(d,f);
// cout <<d<<endl;
// cout <<f<<endl;
int* x;
int y = 69;
x=&y;
cout << "x = " << x << endl;
cout <<"y = " << y << endl;
moreorless(x);
cout <<"y = " << y << endl;
cout << "x = " << x << endl;
}
| [
"[email protected]"
]
| |
c9e273f6a01c4695a03a578fa3de3cd32999ebb6 | 8acc36b20467cee20e48d9a163d90c65bc1ad98a | /third-party/paxos/src/deptran/classic/coordinator.cc | 12a5820c3873a1d513826e13d7010a2e04271946 | [
"MIT"
]
| permissive | stonysystems/rolis | 65fcfdb1c3aea2ce63a525ae5b7a3faa3ac41008 | 02ae2d91ed31d85ca0ac4464641cf9eddd2612bd | refs/heads/master | 2023-04-18T16:15:32.077322 | 2022-04-17T14:12:31 | 2022-04-17T14:12:31 | 466,564,131 | 19 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 13,543 | cc |
/**
* What shoud we do to change this to asynchronous?
* 1. Fisrt we need to have a queue to hold all transaction requests.
* 2. pop next request, send start request for each piece until there is no
*available left.
* in the callback, send the next piece of start request.
* if responses to all start requests are collected.
* send the finish request
* in callback, remove it from queue.
*
*/
#include "coordinator.h"
#include "../frame.h"
#include "../benchmark_control_rpc.h"
namespace janus {
CoordinatorClassic::CoordinatorClassic(uint32_t coo_id,
int benchmark,
ClientControlServiceImpl* ccsi,
uint32_t thread_id)
: Coordinator(coo_id,
benchmark,
ccsi,
thread_id) {
verify(commo_ == nullptr);
}
Communicator* CoordinatorClassic::commo() {
if (commo_ == nullptr) {
commo_ = new Communicator;
}
verify(commo_ != nullptr);
return commo_;
}
void CoordinatorClassic::ForwardTxnRequest(TxRequest& req) {
auto comm = commo();
comm->SendForwardTxnRequest(
req,
this,
std::bind(&CoordinatorClassic::ForwardTxRequestAck,
this,
std::placeholders::_1
));
}
void CoordinatorClassic::ForwardTxRequestAck(const TxReply& txn_reply) {
Log_info("%s: %d", __FUNCTION__, txn_reply.res_);
committed_ = (txn_reply.res_ == REJECT) ? false : true;
aborted_ = !committed_;
phase_ = Phase::COMMIT;
GotoNextPhase();
}
void CoordinatorClassic::DoTxAsync(TxRequest& req) {
std::lock_guard<std::recursive_mutex> lock(this->mtx_);
TxData* cmd = frame_->CreateTxnCommand(req, txn_reg_);
verify(txn_reg_ != nullptr);
cmd->root_id_ = this->next_txn_id();
cmd->id_ = cmd->root_id_;
ongoing_tx_id_ = cmd->id_;
Log_debug("assigning tx id: %" PRIx64, ongoing_tx_id_);
cmd->timestamp_ = GenerateTimestamp();
cmd_ = cmd;
n_retry_ = 0;
Reset(); // In case of reuse.
Log_debug("do one request txn_id: %d", cmd_->id_);
auto config = Config::GetConfig();
bool not_forwarding = forward_status_ != PROCESS_FORWARD_REQUEST;
if (ccsi_ && not_forwarding) {
ccsi_->txn_start_one(thread_id_, cmd->type_);
}
if (config->forwarding_enabled_ && forward_status_ == FORWARD_TO_LEADER) {
Log_info("forward to leader: %d; cooid: %d",
forward_status_,
this->coo_id_);
ForwardTxnRequest(req);
} else {
Log_debug("start txn!!! : %d", forward_status_);
Coroutine::CreateRun([this]() { GotoNextPhase(); });
}
}
void CoordinatorClassic::GotoNextPhase() {
int n_phase = 4;
int current_phase = phase_ % n_phase;
switch (phase_++ % n_phase) {
case Phase::INIT_END:
DispatchAsync();
verify(phase_ % n_phase == Phase::DISPATCH);
break;
case Phase::DISPATCH:
verify(phase_ % n_phase == Phase::PREPARE);
verify(!committed_);
if (aborted_) {
phase_++;
Commit();
} else {
Prepare();
}
break;
case Phase::PREPARE:
verify(phase_ % n_phase == Phase::COMMIT);
Commit();
break;
case Phase::COMMIT:
verify(phase_ % n_phase == Phase::INIT_END);
if (committed_)
End();
else if (aborted_) {
Restart();
} else
verify(0);
break;
default:
verify(0);
}
}
void CoordinatorClassic::Reset() {
Coordinator::Reset();
for (int i = 0; i < site_prepare_.size(); i++) {
site_prepare_[i] = 0;
}
n_dispatch_ = 0;
n_dispatch_ack_ = 0;
n_prepare_req_ = 0;
n_prepare_ack_ = 0;
n_finish_req_ = 0;
n_finish_ack_ = 0;
dispatch_acks_.clear();
committed_ = false;
aborted_ = false;
}
void CoordinatorClassic::Restart() {
std::lock_guard<std::recursive_mutex> lock(this->mtx_);
verify(aborted_);
n_retry_++;
cmd_->root_id_ = this->next_txn_id();
cmd_->id_ = cmd_->root_id_;
ongoing_tx_id_ = cmd_->root_id_;
Log_debug("assigning tx_id: %" PRIx64, ongoing_tx_id_);
TxData* txn = (TxData*) cmd_;
double last_latency = txn->last_attempt_latency();
if (ccsi_)
ccsi_->txn_retry_one(this->thread_id_, txn->type_, last_latency);
auto& max_retry = Config::GetConfig()->max_retry_;
if (n_retry_ > max_retry && max_retry >= 0) {
if (ccsi_)
ccsi_->txn_give_up_one(this->thread_id_, txn->type_);
End();
} else {
// Log_info("retry count %d, max_retry: %d, this coord: %llx", n_retry_, max_retry, this);
Reset();
txn->Reset();
GotoNextPhase();
}
}
void CoordinatorClassic::DispatchAsync() {
std::lock_guard<std::recursive_mutex> lock(mtx_);
auto txn = (TxData*) cmd_;
int cnt = 0;
auto n_pd = Config::GetConfig()->n_parallel_dispatch_;
n_pd = 1;
auto cmds_by_par = txn->GetReadyPiecesData(n_pd);
Log_debug("Dispatch for tx_id: %" PRIx64, txn->root_id_);
for (auto& pair: cmds_by_par) {
const parid_t& par_id = pair.first;
auto& cmds = pair.second;
n_dispatch_ += cmds.size();
cnt += cmds.size();
auto sp_vec_piece = std::make_shared<vector<shared_ptr<TxPieceData>>>();
for (auto c: cmds) {
c->id_ = next_pie_id();
dispatch_acks_[c->inn_id_] = false;
sp_vec_piece->push_back(c);
}
commo()->BroadcastDispatch(sp_vec_piece,
this,
std::bind(&CoordinatorClassic::DispatchAck,
this,
phase_,
std::placeholders::_1,
std::placeholders::_2));
}
Log_debug("Dispatch cnt: %d for tx_id: %" PRIx64, cnt, txn->root_id_);
}
bool CoordinatorClassic::AllDispatchAcked() {
bool ret1 = std::all_of(dispatch_acks_.begin(),
dispatch_acks_.end(),
[](std::pair<innid_t, bool> pair) {
return pair.second;
});
if (ret1)
verify(n_dispatch_ack_ == n_dispatch_);
return ret1;
}
void CoordinatorClassic::DispatchAck(phase_t phase,
int res,
TxnOutput& outputs) {
std::lock_guard<std::recursive_mutex> lock(this->mtx_);
if (phase != phase_) return;
TxData* txn = (TxData*) cmd_;
if (res == REJECT) {
Log_debug("got REJECT reply for cmd_id: %llx NOT COMMITING",
txn->root_id_);
aborted_ = true;
txn->commit_.store(false);
}
n_dispatch_ack_ += outputs.size();
if (aborted_) {
if (n_dispatch_ack_ == n_dispatch_) {
// wait until all ongoing dispatch to finish before aborting.
Log_debug("received all start acks (at least one is REJECT);"
"tx_id: %"
PRIx64, txn->root_id_);
GotoNextPhase();
return;
}
}
for (auto& pair : outputs) {
const innid_t& inn_id = pair.first;
verify(dispatch_acks_.at(inn_id) == false);
dispatch_acks_[inn_id] = true;
Log_debug("get start ack %ld/%ld for cmd_id: %lx, inn_id: %d",
n_dispatch_ack_, n_dispatch_, cmd_->id_, inn_id);
txn->Merge(pair.first, pair.second);
}
if (txn->HasMoreUnsentPiece()) {
Log_debug("command has more sub-cmd, cmd_id: %llx,"
" n_started_: %d, n_pieces: %d",
txn->id_, txn->n_pieces_dispatched_, txn->GetNPieceAll());
DispatchAsync();
} else if (AllDispatchAcked()) {
Log_debug("receive all start acks, txn_id: %llx; START PREPARE",
txn->id_);
GotoNextPhase();
}
}
/** caller should be thread_safe */
void CoordinatorClassic::Prepare() {
TxData* cmd = (TxData*) cmd_;
auto mode = Config::GetConfig()->tx_proto_;
verify(mode == MODE_OCC || mode == MODE_2PL);
std::vector<i32> sids;
for (auto& site : cmd->partition_ids_) {
sids.push_back(site);
}
for (auto& partition_id : cmd->partition_ids_) {
Log_debug("send prepare tid: %ld; partition_id %d",
cmd_->id_,
partition_id);
commo()->SendPrepare(partition_id,
cmd_->id_,
sids,
std::bind(&CoordinatorClassic::PrepareAck,
this,
phase_,
std::placeholders::_1));
verify(site_prepare_[partition_id] == 0);
site_prepare_[partition_id]++;
verify(site_prepare_[partition_id] == 1);
}
}
void CoordinatorClassic::PrepareAck(phase_t phase, int res) {
std::lock_guard<std::recursive_mutex> lock(this->mtx_);
if (phase != phase_) return;
TxData* cmd = (TxData*) cmd_;
n_prepare_ack_++;
verify(res == SUCCESS || res == REJECT);
if (res == REJECT) {
cmd->commit_.store(false);
aborted_ = true;
// Log_fatal("2PL prepare failed due to error %d", e);
}
Log_debug("tid %llx; prepare result %d", (int64_t) cmd_->root_id_, res);
if (n_prepare_ack_ == cmd->partition_ids_.size()) {
Log_debug("2PL prepare finished for %ld", cmd->root_id_);
if (!aborted_) {
cmd->commit_.store(true);
committed_ = true;
}
GotoNextPhase();
} else {
// Do nothing.
}
}
void CoordinatorClassic::Commit() {
std::lock_guard<std::recursive_mutex> lock(this->mtx_);
// ___TestPhaseThree(cmd_->id_);
auto mode = Config::GetConfig()->tx_proto_;
verify(mode == MODE_OCC || mode == MODE_2PL);
Log_debug("send out finish request, cmd_id: %"
PRIx64
", %d",
tx_data().id_, n_finish_req_);
verify(tx_data().commit_.load() == committed_);
if (committed_) {
tx_data().reply_.res_ = SUCCESS;
for (auto& rp : tx_data().partition_ids_) {
n_finish_req_++;
Log_debug("send commit for txn_id %"
PRIx64
" to %d", tx_data().id_, rp);
commo()->SendCommit(rp,
tx_data().id_,
std::bind(&CoordinatorClassic::CommitAck,
this,
phase_));
site_commit_[rp]++;
}
} else if (aborted_) {
tx_data().reply_.res_ = REJECT;
for (auto& rp : tx_data().partition_ids_) {
n_finish_req_++;
Log_debug("send abort for txn_id %"
PRIx64
" to %d", tx_data().id_, rp);
commo()->SendAbort(rp,
cmd_->id_,
std::bind(&CoordinatorClassic::CommitAck,
this,
phase_));
site_abort_[rp]++;
}
} else {
verify(0);
}
}
void CoordinatorClassic::CommitAck(phase_t phase) {
std::lock_guard<std::recursive_mutex> lock(this->mtx_);
// TODO fix bug: when receiving a reply, the coordinator already frees.
if (phase != phase_) return;
TxData* cmd = (TxData*) cmd_;
n_finish_ack_++;
Log_debug("finish cmd_id_: %ld; n_finish_ack_: %ld; n_finish_req_: %ld",
cmd_->id_, n_finish_ack_, n_finish_req_);
verify(cmd->GetPartitionIds().size() == n_finish_req_);
if (n_finish_ack_ == cmd->GetPartitionIds().size()) {
if (cmd->reply_.res_ == REJECT) {
aborted_ = true;
} else {
committed_ = true;
}
GotoNextPhase();
}
Log_debug("callback: %s, retry: %s",
committed_ ? "True" : "False",
aborted_ ? "True" : "False");
}
void CoordinatorClassic::End() {
TxData* tx_data = (TxData*) cmd_;
TxReply& tx_reply_buf = tx_data->get_reply();
double last_latency = tx_data->last_attempt_latency();
if (committed_) {
tx_data->reply_.res_ = SUCCESS;
this->Report(tx_reply_buf, last_latency
#ifdef TXN_STAT
, txn
#endif // ifdef TXN_STAT
);
} else if (aborted_) {
tx_data->reply_.res_ = REJECT;
} else {
verify(0);
}
tx_reply_buf.tx_id_ = ongoing_tx_id_;
Log_debug("call reply for tx_id: %"
PRIx64, ongoing_tx_id_);
tx_data->callback_(tx_reply_buf);
ongoing_tx_id_ = 0;
delete tx_data;
}
void CoordinatorClassic::Report(TxReply& txn_reply,
double last_latency
#ifdef TXN_STAT
, TxnChopper *ch
#endif // ifdef TXN_STAT
) {
bool not_forwarding = forward_status_ != PROCESS_FORWARD_REQUEST;
if (ccsi_ && not_forwarding) {
if (txn_reply.res_ == SUCCESS) {
#ifdef TXN_STAT
txn_stats_[ch->tx_type_].one(ch->proxies_.size(), ch->p_types_);
#endif // ifdef TXN_STAT
ccsi_->txn_success_one(thread_id_,
txn_reply.txn_type_,
txn_reply.start_time_,
txn_reply.time_,
last_latency,
txn_reply.n_try_);
} else
ccsi_->txn_reject_one(thread_id_,
txn_reply.txn_type_,
txn_reply.start_time_,
txn_reply.time_,
last_latency,
txn_reply.n_try_);
}
}
void CoordinatorClassic::___TestPhaseThree(txnid_t txn_id) {
// auto it = ___phase_three_tids_.find(txn_id);
// verify(it == ___phase_three_tids_.end());
// ___phase_three_tids_.insert(txn_id);
}
void CoordinatorClassic::___TestPhaseOne(txnid_t txn_id) {
auto it = ___phase_one_tids_.find(txn_id);
verify(it == ___phase_one_tids_.end());
___phase_one_tids_.insert(txn_id);
}
} // namespace janus
| [
"[email protected]"
]
| |
ba6ca19120053c0aa0851b78d093c9c479916dab | fb26fec51f1967e06751577d6fff3214fa654bee | /include/single_mphf.hpp | bf38400d2eb77514810921f3e047ba09267391ed | [
"MIT"
]
| permissive | cxz/pthash | 43daec6448491190759ae672d54d03393283a8dd | dd5f304d5f251239b968501016cc17df67fb0762 | refs/heads/master | 2023-04-09T10:40:23.014963 | 2021-04-22T08:57:33 | 2021-04-22T08:57:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,224 | hpp | #pragma once
#include "utils/bucketers.hpp"
#include "builders/util.hpp"
#include "builders/internal_memory_builder_single_mphf.hpp"
#include "builders/external_memory_builder_single_mphf.hpp"
namespace pthash {
template <typename Hasher, typename Encoder>
struct single_mphf {
typedef Encoder encoder_type;
template <typename Iterator>
build_timings build_in_internal_memory(Iterator keys, uint64_t n,
build_configuration const& config) {
internal_memory_builder_single_mphf<Hasher> builder;
auto timings = builder.build_from_keys(keys, n, config);
timings.encoding_seconds = build(builder, config);
return timings;
}
template <typename Iterator>
build_timings build_in_external_memory(Iterator keys, uint64_t n,
build_configuration const& config) {
external_memory_builder_single_mphf<Hasher> builder;
auto timings = builder.build_from_keys(keys, n, config);
timings.encoding_seconds = build(builder, config);
return timings;
}
template <typename Builder>
double build(Builder const& builder, build_configuration const&) {
auto start = clock_type::now();
m_seed = builder.seed();
m_num_keys = builder.num_keys();
m_table_size = builder.table_size();
m_M = fastmod::computeM_u64(m_table_size);
m_bucketer = builder.bucketer();
m_pilots.encode(builder.pilots());
m_free_slots.encode(builder.free_slots());
auto stop = clock_type::now();
return seconds(stop - start);
}
template <typename T>
uint64_t operator()(T const& key) const {
auto hash = Hasher::hash(key, m_seed);
return position(hash);
}
uint64_t position(typename Hasher::hash_type hash) const {
uint64_t bucket = m_bucketer.bucket(hash.first());
uint64_t pilot = m_pilots.access(bucket);
uint64_t hashed_pilot = default_hash64(pilot, m_seed);
uint64_t p = fastmod::fastmod_u64(hash.second() ^ hashed_pilot, m_M, m_table_size);
if (PTH_LIKELY(p < num_keys())) return p;
return m_free_slots.access(p - num_keys());
}
size_t num_bits_for_pilots() const {
return 8 * (sizeof(m_seed) + sizeof(m_num_keys) + sizeof(m_table_size) + sizeof(m_M)) +
m_bucketer.num_bits() + m_pilots.num_bits();
}
size_t num_bits_for_mapper() const {
return m_free_slots.num_bits();
}
size_t num_bits() const {
return num_bits_for_pilots() + num_bits_for_mapper();
}
inline uint64_t num_keys() const {
return m_num_keys;
}
template <typename Visitor>
void visit(Visitor& visitor) {
visitor.visit(m_seed);
visitor.visit(m_num_keys);
visitor.visit(m_table_size);
visitor.visit(m_M);
visitor.visit(m_bucketer);
visitor.visit(m_pilots);
visitor.visit(m_free_slots);
}
private:
uint64_t m_seed;
uint64_t m_num_keys;
uint64_t m_table_size;
__uint128_t m_M;
skew_bucketer m_bucketer;
Encoder m_pilots;
ef_sequence m_free_slots;
};
} // namespace pthash | [
"[email protected]"
]
| |
b691ad6bee3b4738cd54d63169cc2ed4e9fcff0d | 9fac7237fb36b4139a742d373f5b49f15052790c | /chap4/c4_9.cpp | 51b858cb6d610fc3980f07d5f2ee1b88909dcdb5 | []
| no_license | mryoshio/coding_interview | 68dd324bdd89ac3a5fc29e1db7da904dfeb99cfd | 7038eec4a0d266b41b759b2066a73f62adf63e52 | refs/heads/master | 2020-04-05T14:39:41.079499 | 2016-11-30T05:50:11 | 2016-11-30T05:50:11 | 16,435,508 | 0 | 0 | null | 2016-11-30T05:50:11 | 2014-02-01T14:38:47 | C++ | UTF-8 | C++ | false | false | 981 | cpp | #include <iostream>
#include <queue>
#include <stack>
#include "node.h"
using namespace std;
void checkPath(Node* n, int t) {
stack<int> s;
while (n != nullptr && t > 0) {
s.push(n->data);
t -= n->data;
n = n->parent;
}
if (t == 0) {
cout << "path: " << s.top();
s.pop();
while (!s.empty()) {
cout << " -> " << s.top();
s.pop();
}
cout << endl;
}
}
void solve(Node* n, int t) {
queue<Node*> q;
q.push(n);
while (!q.empty()) {
Node* start = q.front();
if (start->leftChild != nullptr) q.push(start->leftChild);
if (start->rightChild != nullptr) q.push(start->rightChild);
checkPath(start, t);
q.pop();
}
}
int main() {
srand((unsigned int)time(NULL));
int maxVal = 20;
int d = 3;
int target = maxVal + rand() % maxVal;
Node* tree = makeBalancedBT(new Node(rand() % maxVal), maxVal, d);
dumpTree(tree, 0);
cout << "--- target: " << target << endl;
solve(tree, target);
}
| [
"[email protected]"
]
| |
76a86f0d25ade14e7c11b950d47fd532faf3b081 | dd2fa7da3ee1d1f976a7315b7cf924dc401000f6 | /app_telnetloop1.cpp | 3de259320537013175c4151feddd7f0a95894688 | []
| no_license | jterweeme/avruino | d596a31b06db67b77ad7dc9ebc212fa4b018b601 | 0d175e82f625922515589f7f4ff144352a9e3d3f | refs/heads/master | 2022-11-26T16:41:44.310743 | 2022-11-23T16:07:09 | 2022-11-23T16:07:09 | 110,882,116 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,703 | cpp | #include "enc28j60tcp.h"
#include "enc28j60udp.h"
#include "stream.h"
#include "dhcp.h"
#include "misc.h"
#include "board.h"
static Enc28J60Network nw;
static Enc28J60IP eth(&nw);
ostream *gout;
static inline char convertCase(char c)
{
if (my_isupper(c))
return c + 32;
if (my_islower(c))
return c - 32;
return c;
}
int main()
{
*p_tccr0b = cs02; // | CS00;
*p_timsk0 |= 1<<toie0;
zei();
DefaultUart s;
UartStream cout(&s);
gout = &cout;
cout << "Initialize Ethernet\r\n";
cout.flush();
uint8_t mac[6] = {0,1,2,3,4,5};
eth.init(mac);
cout << "Starting DHCP\r\n";
cout.flush();
UIPUDP udp(ð);
DhcpClass dhcp(&udp);
dhcp.beginWithDHCP(mac);
eth.configure(dhcp.localIp(), dhcp.dnsServer(), dhcp.gateway(), dhcp.subnetMask2());
eth.addresses(cout);
cout << "\r\n";
UIPServer server = UIPServer(ð, 23);
server.begin();
cout << "Telnet server started\r\n";
while (true)
{
UIPClient client = server.available();
if (client)
{
cout << "Client connected\r\n";
while (client.connected())
{
if (client.available())
{
char c = client.read();
cout.put(convertCase(c));
server.write(convertCase(c));
}
}
for (volatile uint16_t i = 0; i < 0x4fff; i++); // delay
client.stop();
cout << "Client disconnected\r\n";
}
}
return 0;
}
extern "C" void TIMER0_OVF __attribute__ ((signal, used, externally_visible));
void TIMER0_OVF
{
eth.tick2();
}
| [
"[email protected]"
]
| |
cf3e4f7379a76e89d0e59d77d3c4f3d957ed86c2 | 4aff5a49d635ecfab5cac986b1ddc1809189e8f8 | /LeetCode/Plus One/plus one.cpp | 988c36a20a7811afd1b7115b9166b3644597d7bc | []
| no_license | shreyrai99/CP-DSA-Questions | 1221f595391643f5967a77efeb790352536ab9ff | 5a5bfdaee6bf0253661259cae7780b8859108dbd | refs/heads/main | 2023-09-04T06:38:59.114238 | 2021-10-22T09:46:59 | 2021-10-22T09:46:59 | 413,551,990 | 1 | 0 | null | 2021-10-04T19:10:04 | 2021-10-04T19:10:04 | null | UTF-8 | C++ | false | false | 1,596 | cpp | class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
// The idea to solve this problem is to just iterating the given vector from last and adding carry to the ith element.
// As asked in the question, we have to increment the given number by 1. Thus, initially the Carry is 1.
/*
Some examples -
9 9 9 9
1
__________
1 0 0 0 0
9 9 8
1
________
9 9 9
*/
int c = 1;
// Now iterating through the number vector from Right and adding carry. (As we used to do in elementary classes)
for(int i = digits.size()-1;i>=0;i--)
{
// The ith element i.e., the ith digit is stored here in d.
int d = digits[i];
// Now, updating the ith digit value by adding carry to it and taking modulo by 10.
digits[i] = (d + c) % 10;
// We also need to update carry value if there is some.
c = (d+c)/10;
}
// If the carry is non zero then we have to increase the size of the given vector and have to put carry in the beginning.
if(c != 0)
{
digits.emplace(digits.begin(),c);
}
// Returning the Plus-oned vector.
return digits;
}
};
| [
"[email protected]"
]
| |
742c2a578d3bc785a2716df01f8708f7af467c83 | 4979915833a11a0306b66a25a91fadd009e7d863 | /zircon/system/ulib/ftl-mtd/ftl-volume-wrapper.cc | 4830b1a5a4d31f1a23ee2f694af5814faa9a6794 | [
"BSD-2-Clause",
"BSD-3-Clause",
"MIT"
]
| permissive | dreamboy9/fuchsia | 1f39918fb8fe71d785b43b90e0b3128d440bd33f | 4ec0c406a28f193fe6e7376ee7696cca0532d4ba | refs/heads/master | 2023-05-08T02:11:06.045588 | 2021-06-03T01:59:17 | 2021-06-03T01:59:17 | 373,352,924 | 0 | 0 | NOASSERTION | 2021-06-03T01:59:18 | 2021-06-03T01:58:57 | null | UTF-8 | C++ | false | false | 2,386 | cc | // Copyright 2019 The Fuchsia 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 <lib/ftl-mtd/ftl-volume-wrapper.h>
namespace ftl_mtd {
zx_status_t FtlVolumeWrapper::Init(std::unique_ptr<ftl::NdmDriver> driver) {
if (volume_->Init(std::move(driver)) != nullptr) {
return ZX_ERR_IO;
}
return ZX_OK;
}
bool FtlVolumeWrapper::OnVolumeAdded(uint32_t page_size, uint32_t num_pages) {
page_size_ = page_size;
num_pages_ = num_pages;
return true;
}
ssize_t FtlVolumeWrapper::Read(void* buffer, size_t count) {
if (page_ >= num_pages_) {
return 0;
}
if (count % page_size_ != 0) {
return ZX_ERR_INVALID_ARGS;
}
uint32_t page_count = static_cast<uint32_t>(count / page_size_);
zx_status_t status = volume_->Read(page_, page_count, buffer);
if (status != ZX_OK) {
return status;
}
page_ += page_count;
return count;
}
ssize_t FtlVolumeWrapper::Write(const void* buffer, size_t count) {
if (page_ >= num_pages_) {
return 0;
}
if (count % page_size_ != 0) {
return ZX_ERR_INVALID_ARGS;
}
uint32_t page_count = static_cast<uint32_t>(count / page_size_);
zx_status_t status = volume_->Write(page_, page_count, buffer);
if (status != ZX_OK) {
return status;
}
page_ += page_count;
return count;
}
ssize_t FtlVolumeWrapper::Seek(off_t offset, int whence) {
if (offset % page_size_ != 0) {
return ZX_ERR_INVALID_ARGS;
}
off_t page_delta = static_cast<off_t>(offset / page_size_);
off_t page;
if (whence == SEEK_SET) {
page = page_delta;
} else if (whence == SEEK_END) {
page = static_cast<off_t>(num_pages_) - page_delta;
} else if (whence == SEEK_CUR) {
page = static_cast<off_t>(page_) + page_delta;
} else {
return ZX_ERR_INVALID_ARGS;
}
uint32_t page_u32 = static_cast<uint32_t>(page);
if (page != page_u32) {
return ZX_ERR_OUT_OF_RANGE;
}
page_ = page_u32;
return Tell();
}
ssize_t FtlVolumeWrapper::Size() { return page_size_ * num_pages_; }
ssize_t FtlVolumeWrapper::Tell() { return page_size_ * page_; }
zx_status_t FtlVolumeWrapper::Truncate(size_t size) { return ZX_ERR_NOT_SUPPORTED; }
zx_status_t FtlVolumeWrapper::Sync() { return volume_->Flush(); }
zx_status_t FtlVolumeWrapper::Format() { return volume_->Format(); }
} // namespace ftl_mtd
| [
"[email protected]"
]
| |
002a2ae17d1e97a65b33a4b13b430e5230145657 | 1b73c418ede5b941aac33e986e251ebe9683af6a | /competitive/august_2020_long/skmp3.cpp | 6d45e5ce4b26bf09f0d55407adb35dad7ea34306 | []
| no_license | gauravengine/CPP_Freak | 492e7478c5e3bcb08e641b160c69e247b21f5503 | 0f98c2cd943d062578cc30839524d1814af0efa3 | refs/heads/main | 2023-08-02T04:10:32.720437 | 2021-09-22T09:21:04 | 2021-09-22T09:21:04 | 313,554,738 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,247 | cpp | // it worked dunno how ;)
#include<bits/stdc++.h>
using namespace std;
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
int t;
cin>>t;
while(t--){
string s;
string p;
string res="";
cin>>s>>p;
unordered_map <char,int> freq;
string temp = p;
for( unsigned int i=0;i<s.length();i++){
freq[s[i]] ++;
}
for( unsigned int i=0;i<p.length();i++){
freq[p[i]] --;
}
bool flag1= false;
string res1 = temp.append(freq[p[0]] , p[0]); // end me append kardia
string res2 ="" ; // beg me append p[0]
//cout<<"res1 "<<res1<<endl;
for(int i=0;i<freq[p[0]];i++){
res2= res2+ p[0];
}
freq[p[0]]= 0;
res2.append(p);
//cout<<"res2 "<<res2<<endl;
for(unsigned int i=0;i<s.length();i++){
if(res1[i] < res2[i] ){
flag1 =true;
break;
}
if(res2[i] < res1[i] ){
break;
}
}
for(int i=97;i<123;i++){
char c= static_cast<char>(i);
while(freq[c] > 0 && c < p[0] ){
res= res + c;
freq[c] --;
}
}
if(flag1) res.append(res1);
else res.append(res2);
for(int i=97;i<123;i++){
char c= static_cast<char>(i);
while(freq[c]>0){
res= res +c;
freq[c]--;
}
}
cout<<res<<"\n";
}
return 0;
} | [
"[email protected]"
]
| |
7c18391aff705e4b9f6b3fec1f4054700182297e | 385cb811d346a4d7a285fc087a50aaced1482851 | /codeforces/245/H/main.cpp | b2366c2679043e0290046ab839aa422863a40aaf | []
| no_license | NoureldinYosri/competitive-programming | aa19f0479420d8d1b10605536e916f0f568acaec | 7739344404bdf4709c69a97f61dc3c0b9deb603c | refs/heads/master | 2022-11-22T23:38:12.853482 | 2022-11-10T20:32:28 | 2022-11-10T20:32:28 | 40,174,513 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,774 | cpp | #include <bits/stdc++.h>
#define loop(i,n) for(int i = 0;i < (n);i++)
#define range(i,a,b) for(int i = (a);i <= (b);i++)
#define all(A) A.begin(),A.end()
#define PI acos(-1)
#define pb push_back
#define mp make_pair
#define sz(A) ((int)A.size())
#define vi vector<int>
#define vl vector<long long>
#define vd vector<double>
#define vp vector<pair<int,int> >
#define ll long long
#define pi pair<int,int>
#define point pair<double,double>
#define pl pair<ll,ll>
#define popcnt(x) __builtin_popcount(x)
#define LSOne(x) ((x) & (-(x)))
#define xx first
#define yy second
#define PQ priority_queue
#define print(A,t) cerr << #A << ": "; copy(all(A),ostream_iterator<t>(cerr," " )); cerr << endl
#define prp(p) cerr << "(" << (p).first << " ," << (p).second << ")";
#define prArr(A,n,t) cerr << #A << ": "; copy(A,A + n,ostream_iterator<t>(cerr," " )); cerr << endl
#define PRESTDIO() cin.tie(0),cerr.tie(0),ios_base::sync_with_stdio(0)
using namespace std;
const int MAX = 5010;
char line[MAX];
int dp[MAX][MAX][2];
void solve(int s,int e){
if(s == e){
dp[s][e][0] = dp[s][e][1] = 1;
return;
}
if(e == s + 1){
solve(s+1,e);
solve(s,e-1);
dp[s][e][0] = 0;
dp[s][e][1] = 2;
if(line[s] == line[e]){
dp[s][e][0] = 1;
dp[s][e][1] = 3;
}
return;
}
if(dp[s][e][0] != -1) return;
solve(s+1,e);
solve(s,e-1);
solve(s+1,e-1);
dp[s][e][0] = 0;
dp[s][e][1] = dp[s+1][e][1] + dp[s][e-1][1] - dp[s + 1][e - 1][1];
if(line[s] == line[e] && dp[s + 1][e - 1][0] ){
dp[s][e][0] = 1;
dp[s][e][1] ++;
}
}
int main(){
memset(dp,-1,sizeof dp);
scanf("%s",line);
solve(0,int(strlen(line))-1);
int n; scanf("%d",&n);
loop(i,n){
int l,r; scanf("%d %d",&l,&r); l--,r--;
printf("%d\n",dp[l][r][1]);
// cerr << dp[l][r][1] << endl;
}
return 0;
}
| [
"[email protected]"
]
| |
38da0ad74080f8ea2beb90e0d2f16a183902ed62 | 7e0ec0e32282307dd5bf051602cc6c2ea268452c | /src/rads/chomp/include/capd/multiEngHom/chomInterface.h | 504cd64d75c9ae60e780b2c02fedc50b1044db9e | []
| no_license | caosuomo/rads | 03a31936715da2a9131a73ae80304680c5c3db7e | 71cab0d6f0711cfab67e8277e1e025b0fc2d8346 | refs/heads/master | 2021-01-20T10:18:58.222894 | 2018-05-24T02:18:58 | 2018-05-24T02:18:58 | 1,039,029 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 9,016 | h | /// @addtogroup multiEngHom
/// @{
/////////////////////////////////////////////////////////////////////////////
/// @file chomInterface.h
///
/// @author Natalia Zaremba, Marian Mrozek
/////////////////////////////////////////////////////////////////////////////
// Copyright (C) The CAPD Group 2005-2006
//
// This file constitutes a part of the CAPD library,
// distributed under the terms of the GNU General Public License.
// Consult http://capd.wsb-nlu.edu.pl/ for details.
// ********** Interface to the chom package by B. Kalies ********** //
/***
Conversion from EuclBitSetT used in this
package to bitcodes used in Kalies' programs
***/
#include <limits>
#include <climits>
#include <list>
#include <cmath>
#include <sstream>
#include <exception>
#include "capd/auxil/CRef.h"
#include "capd/homologicalAlgebra/HomologySignature.h"
#include "capd/multiEngHom/powerTwoCeiling.h"
#include "capd/bitSet/BitmapT.h"
#include "capd/bitSet/BitSetT.h"
#include "capd/bitSet/EuclBitSetT.h"
#include "capd/bitSet/CubSetT.h"
#include "capd/bitSet/CubCellSetT.h"
#include "capd/chom/chom_lu.hpp"
#include "capd/chom/list.hpp"
#include "capd/chom/bitcodes.hpp"
#include "capd/chom/cell.hpp"
#include "capd/chom/edge.hpp"
#include "capd/chom/vertex.hpp"
#include "capd/chom/ncell.hpp"
#include "capd/chom/block.hpp"
#include "capd/chom/complex.hpp"
#include "capd/chom/dim.hpp"
/*************** converting EuclBitSetT to a string file in the format of Kalies package ****/
template <typename P_CubSet>
void writeBitcodeCubSet(P_CubSet const& set,ostringstream& setString){
int dim=set.embDim();
std::vector<int> minCoord(dim); // min coordinates of the enclosing box
std::vector<int> maxCoord(dim); // max coordinates of the enclosing box
// find minCoord and maxCoord
for(int i=0;i<dim;++i){
maxCoord[i]=0;
minCoord[i]=INT_MAX;
}
for(typename P_CubSet::PointCoordIterator it=set.begin();it<set.end();++it){
for(int d=0;d<dim;++d){
if(it[d]<=minCoord[d]) minCoord[d]=it[d];
if(it[d]+1>=maxCoord[d]) maxCoord[d]=it[d]+1;
}
}
int boxSizeAux=0; // maximal length of the enclosing box sides
for(int i=0;i<dim;++i){
if (maxCoord[i]-minCoord[i]>boxSizeAux) boxSizeAux=(maxCoord[i]-minCoord[i]);
}
int depth=1; // depth needed to store all coordinates
int boxSize=1; // minimal power of 2 > boxSizeAux
while(boxSize<boxSizeAux){
boxSize*=2;
++depth;
}
//pomocnicza lista z lizcbami repr pol punktow- do ewentualnego sortowania
vector<string> bitcodes;
setString << dim << endl;
setString << dim*depth << endl;
setString << set.cardinality() << endl;
// for every point in the bitmap
for(typename P_CubSet::PointCoordIterator it=set.begin();it<set.end();++it){
ostringstream bitcodeStream; // this will contain the bitcode representation of the point
std::vector<int> relCoord(dim); // we need coordinates relative to minCoord
for(int d=0;d<dim;++d){
relCoord[d]=it[d]-minCoord[d];
}
// mask is used to pick up bits from the coordinates, starting from the top bit, i.e. from the lowest depth
for(int mask = (int(1) << (depth-1));
mask >=1;
mask /= 2 ){
// write the group of d bits for fixed depth
for(int d=0;d<dim;++d){
bitcodeStream << " " << ( (relCoord[d] & mask) != 0);
}
}
// bitcode of the point is ready, push it to the vector
bitcodes.push_back(bitcodeStream.str());
}
// bitcodes must be sorted
sort(bitcodes.begin(),bitcodes.end());
// write all bitcodes
for(int i=0;i<(int)bitcodes.size();++i){
setString << bitcodes[i] << endl;
}
}//writeBitcodeCubSet
extern int top_leaf;
int PrepRead(istringstream& in){
int dim;
in >> dim;
if(dim>MAX_CHOM_DIM) throw std::runtime_error("homologyViaChom: cubset dimension inconsistent with MAX_CHOM_DIM from chom package!");
// if (dim!=DIM){
// throw std::string("chom: Dimension of the cubset is different from the compiled dimension");
// }
in >> cube_bits;
in >> top_leaf;
return dim;
}
block* Read(complex* c, istringstream& in){
int bit;
block* b=new block(cube_bits,c);
for (char j=0; j<cube_bits; ++j){
in >> bit;
BC(b)(cube_bits-j-1,bit);
}
b->CreateCells(c);
return(b);
}
// Adaptation via istringstream files
// This adaptation is faster and can treat larger files
template <typename P_CubSet>
CRef<HomologySignature<int> > homologyViaChomPackageStreamed(CRef<P_CubSet> A_cubSetCR){
ostringstream sOut;
try{
writeBitcodeCubSet(A_cubSetCR(),sOut);
}catch(std::bad_alloc){
throw std::runtime_error("No memory to prepare data for chom package\n");
}
istringstream in(sOut.str());
cube_bits=0;
top_leaf=0;
GEN_TOL=0;
chomDIM=PrepRead(in);;
for(int i=0; i<chomDIM+1; ++i) gen_flag[i]=0;
ofstream* gout=NULL;
block* nb=new block;
complex c(nb);
block* b;
for (int i=0; i<top_leaf; ++i){
b=Read(&c,in);
c.InsertCube(b);
}
c.FinalCube();
std::vector<int> betti(chomDIM + 1);
c.Homology(gout, &betti[0]);
return CRef<HomologySignature<int> >(new HomologySignature<int> (betti));
}
template <typename P_CubSet>
CRef<HomologySignature<int> > homologyViaChomPackageStreamedCel(CRef<CubCellSetT<typename P_CubSet::BaseClass> > A_cubCellSetCR){
CRef<P_CubSet> cubSetCR(new P_CubSet(A_cubCellSetCR()));
A_cubCellSetCR().~CubCellSetT<typename P_CubSet::BaseClass>();
return homologyViaChomPackageStreamed<P_CubSet>(cubSetCR);
}
extern int SUBDIVISIONS;
// Adaptation via Marcio's bitmaps
// This one actually is better than the above only in the 3 dim version with shaving via lookup tables given below
template <typename P_CubSet>
CRef<HomologySignature<int> > homologyViaChomPackage(CRef<P_CubSet> A_cubSetCR){
const typename P_CubSet::BaseClass& euclSet=A_cubSetCR().getBaseObject();
int dim=euclSet.embDim();
// if(dim!=DIM) throw std::runtime_error("homologyViaChom: cubset dimension inconsistent with DIM from chom package!");
if(dim>MAX_CHOM_DIM) throw std::runtime_error("homologyViaChom: cubset dimension inconsistent with MAX_CHOM_DIM from chom package!");
chomDIM=dim;
int maxSize=1;
for(int i=0;i<dim;++i){
if(euclSet.getPaddedWidth(i)>maxSize) maxSize=euclSet.getPaddedWidth(i);
}
maxSize=powerTwoCeiling(maxSize);
typename P_CubSet::BaseClass internal(maxSize,true); // true means clear
typename P_CubSet::BaseClass::PointCoordIterator it(A_cubSetCR());
for(it=A_cubSetCR().begin();it<A_cubSetCR().end();++it){
typename P_CubSet::BaseClass::Pixel c(it.coords());
internal.addPixel(c);
}
char* buf=const_cast<char*>(reinterpret_cast<const char*>(internal.getBaseObject().getBaseObject().getBitmap()));
std::vector<int> betti(dim + 1);
SUBDIVISIONS=baseTwoLog(maxSize);
ulong* maxSizes=new ulong[chomDIM];
for(int i=0;i<dim;++i){
maxSizes[i]=maxSize;
}
compute_homology(buf, maxSizes, &betti[0]); /* Compute Homology */
delete maxSizes;
return CRef<HomologySignature<int> >(new HomologySignature<int> (betti));
}
template <typename P_CubSet>
CRef<HomologySignature<int> > homologyViaChomPackageCel(CRef<CubCellSetT<typename P_CubSet::BaseClass> > A_cubCellSetCR){
CRef<P_CubSet> cubSetCR(new P_CubSet(A_cubCellSetCR()) );
return homologyViaChomPackage<P_CubSet>(cubSetCR);
}
// Adaptation via Marcio's bitmaps with shaving
template <typename P_CubSet>
CRef<HomologySignature<int> > homologyViaChomPackageLT(CRef<P_CubSet> A_cubSetCR){
const typename P_CubSet::BaseClass& euclSet=A_cubSetCR().getBaseObject();
int dim=euclSet.embDim();
if(dim!=3) throw std::runtime_error("homologyViaChomLT: adaptation only for dimension 3!");
chomDIM=dim;
if(dim>MAX_CHOM_DIM) throw std::runtime_error("homologyViaChom: cubset dimension inconsistent with MAX_CHOM_DIM from chom package!");
int maxSize=1;
for(int i=0;i<dim;++i){
if(euclSet.getPaddedWidth(i)>maxSize) maxSize=euclSet.getPaddedWidth(i);
}
maxSize=powerTwoCeiling(maxSize);
typename P_CubSet::BaseClass internal(maxSize,true); // true means clear
typename P_CubSet::BaseClass::PointCoordIterator it(A_cubSetCR());
for(it=A_cubSetCR().begin();it<A_cubSetCR().end();++it){
typename P_CubSet::BaseClass::Pixel c(it.coords());
internal.addPixel(c);
}
char* buf=const_cast<char*>(reinterpret_cast<const char*>(internal.getBaseObject().getBaseObject().getBitmap()));
std::vector<int> betti(dim + 1);
reduce(buf, maxSize, maxSize, maxSize); /* Reduce cubical complex */
SUBDIVISIONS=baseTwoLog(maxSize);
compute_homology(buf, maxSize, maxSize, maxSize, &betti[0]); /* Compute Homology */
return CRef<HomologySignature<int> >(new HomologySignature<int> (betti));
}
template <typename P_CubSet>
CRef<HomologySignature<int> > homologyViaChomPackageLTCel(CRef<CubCellSetT<typename P_CubSet::BaseClass> > A_cubCellSetCR){
CRef<P_CubSet> cubSetCR(new P_CubSet(A_cubCellSetCR()) );
return homologyViaChomPackageLT<P_CubSet>(cubSetCR);
}
/// @}
| [
"[email protected]"
]
| |
00c2f1dda0af8c9862a90830117941fac5900b20 | fa60dc561e12ba3582386a86e13f71a4aa4bddd6 | /plugins(http)/storesvc/store_basic_info.cc | 210d39f88015fffed25ac9fe256c23fa176ad4f1 | []
| no_license | smartdata-x/abhegsvc | 20a2f49e0ef4ada547bcacd5ed3d8085df4b890a | 350a2148fbd963c1ff68d39873bdbf1a1661e453 | refs/heads/master | 2020-12-03T02:21:55.837263 | 2015-06-08T10:20:03 | 2015-06-08T10:20:03 | 29,679,233 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 985 | cc | /*
* user_basic_info.cc
*
* Created on: 2014年12月4日
* Author: kerry
*/
#include "store_basic_info.h"
namespace storesvc_logic{
GameStrategy::GameStrategy(){
data_ = new Data();
}
GameStrategy::GameStrategy(const GameStrategy& strategy)
:data_(strategy.data_){
if(data_!=NULL){
data_->AddRef();
}
}
GameStrategy& GameStrategy::operator =(const GameStrategy& strategy){
if(strategy.data_!=NULL){
strategy.data_->AddRef();
}
if(data_!=NULL){
data_->Release();
}
data_ = strategy.data_;
return (*this);
}
base_logic::DictionaryValue* GameStrategy::Release(){
scoped_ptr<base_logic::DictionaryValue> dict(new base_logic::DictionaryValue());
if(data_->id_!=0)
dict->SetBigInteger(L"id",data_->id_);
if(!data_->name_.empty())
dict->SetString(L"name",data_->name_);
if(!data_->details_.empty())
dict->SetString(L"details",data_->details_);
if(!data_->address_.empty())
dict->SetString(L"address",data_->address_);
return dict.release();
}
}
| [
"[email protected]"
]
| |
1ce7768bd57a337109e0cef2fe938218f06cb102 | cbee89864e03f3bd4e86308d386e6d157c07a7a7 | /enma_pe/pe_preview_icon.cpp | 159e3aeee2d9d9e038e58745c4863914b2c6acee | [
"MIT",
"BSD-3-Clause"
]
| permissive | jnastarot/enma_pe | c21c7b99dcf8d0717bc0363a2ea4f78151afe8df | ed5e0d12e6c564b8ab27f06efe12127424d42016 | refs/heads/master | 2022-08-17T06:35:13.209869 | 2022-07-31T21:27:55 | 2022-07-31T21:27:55 | 125,741,395 | 76 | 27 | BSD-3-Clause | 2022-01-07T19:48:17 | 2018-03-18T15:50:00 | C++ | UTF-8 | C++ | false | false | 2,225 | cpp | #include "stdafx.h"
using namespace enma;
using namespace pe_resource_internal;
using namespace hl;
pe_image_preview_icon::pe_image_preview_icon(pe_resource_directory& resources)
: _resources(resources) {
parse_resources();
}
bool pe_image_preview_icon::parse_resources() {
auto resources_entry = hl::pe_image_resources_hl(_resources).get_directory(hl::kResourceIconGroup);
if (!resources_entry || resources_entry->is_includes_data() ||
resources_entry->get_resource_directory().get_entry_list().size() == 0) {
return false;
}
pe_resource_directory_entry* group_lvl2 = 0;
for (auto& entry : resources_entry->get_resource_directory().get_entry_list()) {
if (!group_lvl2) {
group_lvl2 = &entry;
}
else if (entry.get_id() < group_lvl2->get_id()) {
group_lvl2 = &entry;
}
}
if (!group_lvl2 || group_lvl2->is_includes_data() ||
group_lvl2->get_resource_directory().get_entry_list().size() == 0) {
return false;
}
for (auto& entry : group_lvl2->get_resource_directory().get_entry_list()) {
_available_languages.push_back({ entry.get_id(), &entry });
}
return true;
}
bool pe_image_preview_icon::get_default_icon_group(pe_image_icon_group& icon, uint16_t& language_id) {
for (auto& entry : _available_languages) {
if (entry.first == 0x1000) {
auto& data = entry.second->get_data_entry().get_data();
language_id = entry.first;
return icon.parse(data.data(), data.size());
}
}
if (_available_languages.size()) {
auto& data = _available_languages.front().second->get_data_entry().get_data();
language_id = _available_languages.front().first;
return icon.parse(data.data(), data.size());
}
return false;
}
bool pe_image_preview_icon::get_icon_group_by_language(uint16_t language_id, pe_image_icon_group& icon) {
for (auto& entry : _available_languages) {
if (entry.first == language_id) {
auto& data = entry.second->get_data_entry().get_data();
return icon.parse(data.data(), data.size());
}
}
return false;
} | [
"[email protected]"
]
| |
cec1e849045d349cf0bbb994b8baa8c87db498bc | 73ee941896043f9b3e2ab40028d24ddd202f695f | /external/chromium_org/chrome/browser/extensions/api/notifications/notifications_api.cc | 257eb1ab5b6ef8f74d6e91e5281a5c7be6b9b461 | [
"BSD-3-Clause"
]
| permissive | CyFI-Lab-Public/RetroScope | d441ea28b33aceeb9888c330a54b033cd7d48b05 | 276b5b03d63f49235db74f2c501057abb9e79d89 | refs/heads/master | 2022-04-08T23:11:44.482107 | 2016-09-22T20:15:43 | 2016-09-22T20:15:43 | 58,890,600 | 5 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 21,322 | cc | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/api/notifications/notifications_api.h"
#include "base/callback.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "base/time/time.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/extensions/event_names.h"
#include "chrome/browser/extensions/event_router.h"
#include "chrome/browser/extensions/extension_system.h"
#include "chrome/browser/notifications/desktop_notification_service.h"
#include "chrome/browser/notifications/desktop_notification_service_factory.h"
#include "chrome/browser/notifications/notification.h"
#include "chrome/browser/notifications/notification_ui_manager.h"
#include "chrome/common/chrome_version_info.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/extensions/features/feature.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/gfx/image/image.h"
#include "ui/gfx/image/image_skia.h"
#include "ui/gfx/image/image_skia_rep.h"
#include "ui/message_center/message_center_style.h"
#include "ui/message_center/message_center_util.h"
#include "ui/message_center/notifier_settings.h"
#include "url/gurl.h"
namespace extensions {
namespace {
const char kResultKey[] = "result";
const char kMissingRequiredPropertiesForCreateNotification[] =
"Some of the required properties are missing: type, iconUrl, title and "
"message.";
const char kUnexpectedProgressValueForNonProgressType[] =
"The progress value should not be specified for non-progress notification";
const char kInvalidProgressValue[] =
"The progress value should range from 0 to 100";
// Converts an object with width, height, and data in RGBA format into an
// gfx::Image (in ARGB format).
bool NotificationBitmapToGfxImage(
api::notifications::NotificationBitmap* notification_bitmap,
gfx::Image* return_image) {
if (!notification_bitmap)
return false;
// Ensure a sane set of dimensions.
const int max_width = message_center::kNotificationPreferredImageSize;
const int max_height =
message_center::kNotificationPreferredImageRatio * max_width;
const int BYTES_PER_PIXEL = 4;
const int width = notification_bitmap->width;
const int height = notification_bitmap->height;
if (width < 0 || height < 0 || width > max_width || height > max_height)
return false;
// Ensure we have rgba data.
std::string* rgba_data = notification_bitmap->data.get();
if (!rgba_data)
return false;
const size_t rgba_data_length = rgba_data->length();
const size_t rgba_area = width * height;
if (rgba_data_length != rgba_area * BYTES_PER_PIXEL)
return false;
// Now configure the bitmap with the sanitized dimensions.
SkBitmap bitmap;
bitmap.setConfig(SkBitmap::kARGB_8888_Config, width, height);
// Allocate the actual backing store.
if (!bitmap.allocPixels())
return false;
// Ensure that our bitmap and our data now refer to the same number of pixels.
if (rgba_data_length != bitmap.getSafeSize())
return false;
uint32_t* pixels = bitmap.getAddr32(0, 0);
const char* c_rgba_data = rgba_data->data();
for (size_t t = 0; t < rgba_area; ++t) {
// |c_rgba_data| is RGBA, pixels is ARGB.
size_t rgba_index = t * BYTES_PER_PIXEL;
pixels[t] = SkPreMultiplyColor(
((c_rgba_data[rgba_index + 3] & 0xFF) << 24) |
((c_rgba_data[rgba_index + 0] & 0xFF) << 16) |
((c_rgba_data[rgba_index + 1] & 0xFF) << 8) |
((c_rgba_data[rgba_index + 2] & 0xFF) << 0));
}
// TODO(dewittj): Handle HiDPI images.
ui::ScaleFactor scale_factor(ui::SCALE_FACTOR_100P);
gfx::ImageSkia skia(gfx::ImageSkiaRep(bitmap, scale_factor));
*return_image = gfx::Image(skia);
return true;
}
// Given an extension id and another id, returns an id that is unique
// relative to other extensions.
std::string CreateScopedIdentifier(const std::string& extension_id,
const std::string& id) {
return extension_id + "-" + id;
}
// Removes the unique internal identifier to send the ID as the
// extension expects it.
std::string StripScopeFromIdentifier(const std::string& extension_id,
const std::string& id) {
size_t index_of_separator = extension_id.length() + 1;
DCHECK_LT(index_of_separator, id.length());
return id.substr(index_of_separator);
}
class NotificationsApiDelegate : public NotificationDelegate {
public:
NotificationsApiDelegate(ApiFunction* api_function,
Profile* profile,
const std::string& extension_id,
const std::string& id)
: api_function_(api_function),
profile_(profile),
extension_id_(extension_id),
id_(id),
scoped_id_(CreateScopedIdentifier(extension_id, id)),
process_id_(-1) {
DCHECK(api_function_.get());
if (api_function_->render_view_host())
process_id_ = api_function->render_view_host()->GetProcess()->GetID();
}
virtual void Display() OVERRIDE { }
virtual void Error() OVERRIDE {
scoped_ptr<base::ListValue> args(CreateBaseEventArgs());
SendEvent(event_names::kOnNotificationError, args.Pass());
}
virtual void Close(bool by_user) OVERRIDE {
scoped_ptr<base::ListValue> args(CreateBaseEventArgs());
args->Append(Value::CreateBooleanValue(by_user));
SendEvent(event_names::kOnNotificationClosed, args.Pass());
}
virtual void Click() OVERRIDE {
scoped_ptr<base::ListValue> args(CreateBaseEventArgs());
SendEvent(event_names::kOnNotificationClicked, args.Pass());
}
virtual bool HasClickedListener() OVERRIDE {
return ExtensionSystem::Get(profile_)->event_router()->HasEventListener(
event_names::kOnNotificationClicked);
}
virtual void ButtonClick(int index) OVERRIDE {
scoped_ptr<base::ListValue> args(CreateBaseEventArgs());
args->Append(Value::CreateIntegerValue(index));
SendEvent(event_names::kOnNotificationButtonClicked, args.Pass());
}
virtual std::string id() const OVERRIDE {
return scoped_id_;
}
virtual int process_id() const OVERRIDE {
return process_id_;
}
virtual content::RenderViewHost* GetRenderViewHost() const OVERRIDE {
// We're holding a reference to api_function_, so we know it'll be valid
// until ReleaseRVH is called, and api_function_ (as a
// UIThreadExtensionFunction) will zero out its copy of render_view_host
// when the RVH goes away.
if (!api_function_.get())
return NULL;
return api_function_->render_view_host();
}
virtual void ReleaseRenderViewHost() OVERRIDE {
api_function_ = NULL;
}
private:
virtual ~NotificationsApiDelegate() {}
void SendEvent(const std::string& name, scoped_ptr<base::ListValue> args) {
scoped_ptr<Event> event(new Event(name, args.Pass()));
ExtensionSystem::Get(profile_)->event_router()->DispatchEventToExtension(
extension_id_, event.Pass());
}
scoped_ptr<base::ListValue> CreateBaseEventArgs() {
scoped_ptr<base::ListValue> args(new base::ListValue());
args->Append(Value::CreateStringValue(id_));
return args.Pass();
}
scoped_refptr<ApiFunction> api_function_;
Profile* profile_;
const std::string extension_id_;
const std::string id_;
const std::string scoped_id_;
int process_id_;
DISALLOW_COPY_AND_ASSIGN(NotificationsApiDelegate);
};
} // namespace
bool NotificationsApiFunction::IsNotificationsApiAvailable() {
// We need to check this explicitly rather than letting
// _permission_features.json enforce it, because we're sharing the
// chrome.notifications permissions namespace with WebKit notifications.
return GetExtension()->is_platform_app() || GetExtension()->is_extension();
}
NotificationsApiFunction::NotificationsApiFunction() {
}
NotificationsApiFunction::~NotificationsApiFunction() {
}
bool NotificationsApiFunction::CreateNotification(
const std::string& id,
api::notifications::NotificationOptions* options) {
// First, make sure the required fields exist: type, title, message, icon.
// These fields are defined as optional in IDL such that they can be used as
// optional for notification updates. But for notification creations, they
// should be present.
if (options->type == api::notifications::TEMPLATE_TYPE_NONE ||
!options->icon_url || !options->title || !options->message) {
SetError(kMissingRequiredPropertiesForCreateNotification);
return false;
}
// Extract required fields: type, title, message, and icon.
message_center::NotificationType type =
MapApiTemplateTypeToType(options->type);
const string16 title(UTF8ToUTF16(*options->title));
const string16 message(UTF8ToUTF16(*options->message));
gfx::Image icon;
// TODO(dewittj): Return error if this fails.
NotificationBitmapToGfxImage(options->icon_bitmap.get(), &icon);
// Then, handle any optional data that's been provided.
message_center::RichNotificationData optional_fields;
if (message_center::IsRichNotificationEnabled()) {
if (options->priority.get())
optional_fields.priority = *options->priority;
if (options->event_time.get())
optional_fields.timestamp = base::Time::FromJsTime(*options->event_time);
if (options->buttons.get()) {
// Currently we allow up to 2 buttons.
size_t number_of_buttons = options->buttons->size();
number_of_buttons = number_of_buttons > 2 ? 2 : number_of_buttons;
for (size_t i = 0; i < number_of_buttons; i++) {
message_center::ButtonInfo info(
UTF8ToUTF16((*options->buttons)[i]->title));
NotificationBitmapToGfxImage((*options->buttons)[i]->icon_bitmap.get(),
&info.icon);
optional_fields.buttons.push_back(info);
}
}
if (options->expanded_message.get()) {
optional_fields.expanded_message =
UTF8ToUTF16(*options->expanded_message);
}
bool has_image = NotificationBitmapToGfxImage(options->image_bitmap.get(),
&optional_fields.image);
// We should have an image if and only if the type is an image type.
if (has_image != (type == message_center::NOTIFICATION_TYPE_IMAGE))
return false;
// We should have list items if and only if the type is a multiple type.
bool has_list_items = options->items.get() && options->items->size() > 0;
if (has_list_items != (type == message_center::NOTIFICATION_TYPE_MULTIPLE))
return false;
if (options->progress.get() != NULL) {
// We should have progress if and only if the type is a progress type.
if (type != message_center::NOTIFICATION_TYPE_PROGRESS) {
SetError(kUnexpectedProgressValueForNonProgressType);
return false;
}
optional_fields.progress = *options->progress;
// Progress value should range from 0 to 100.
if (optional_fields.progress < 0 || optional_fields.progress > 100) {
SetError(kInvalidProgressValue);
return false;
}
}
if (has_list_items) {
using api::notifications::NotificationItem;
std::vector<linked_ptr<NotificationItem> >::iterator i;
for (i = options->items->begin(); i != options->items->end(); ++i) {
message_center::NotificationItem item(UTF8ToUTF16(i->get()->title),
UTF8ToUTF16(i->get()->message));
optional_fields.items.push_back(item);
}
}
}
NotificationsApiDelegate* api_delegate(new NotificationsApiDelegate(
this,
profile(),
extension_->id(),
id)); // ownership is passed to Notification
Notification notification(type,
extension_->url(),
title,
message,
icon,
WebKit::WebTextDirectionDefault,
UTF8ToUTF16(extension_->name()),
UTF8ToUTF16(api_delegate->id()),
optional_fields,
api_delegate);
g_browser_process->notification_ui_manager()->Add(notification, profile());
return true;
}
bool NotificationsApiFunction::UpdateNotification(
const std::string& id,
api::notifications::NotificationOptions* options,
Notification* notification) {
// Update optional fields if provided.
if (options->type != api::notifications::TEMPLATE_TYPE_NONE)
notification->set_type(MapApiTemplateTypeToType(options->type));
if (options->title)
notification->set_title(UTF8ToUTF16(*options->title));
if (options->message)
notification->set_message(UTF8ToUTF16(*options->message));
// TODO(dewittj): Return error if this fails.
if (options->icon_bitmap) {
gfx::Image icon;
NotificationBitmapToGfxImage(options->icon_bitmap.get(), &icon);
notification->set_icon(icon);
}
message_center::RichNotificationData optional_fields;
if (message_center::IsRichNotificationEnabled()) {
if (options->priority)
notification->set_priority(*options->priority);
if (options->event_time)
notification->set_timestamp(base::Time::FromJsTime(*options->event_time));
if (options->buttons) {
// Currently we allow up to 2 buttons.
size_t number_of_buttons = options->buttons->size();
number_of_buttons = number_of_buttons > 2 ? 2 : number_of_buttons;
for (size_t i = 0; i < number_of_buttons; i++) {
message_center::ButtonInfo info(
UTF8ToUTF16((*options->buttons)[i]->title));
NotificationBitmapToGfxImage((*options->buttons)[i]->icon_bitmap.get(),
&info.icon);
optional_fields.buttons.push_back(info);
}
}
if (options->expanded_message) {
notification->set_expanded_message(
UTF8ToUTF16(*options->expanded_message));
}
gfx::Image image;
if (NotificationBitmapToGfxImage(options->image_bitmap.get(), &image)) {
// We should have an image if and only if the type is an image type.
if (notification->type() != message_center::NOTIFICATION_TYPE_IMAGE)
return false;
notification->set_image(image);
}
if (options->progress) {
// We should have progress if and only if the type is a progress type.
if (notification->type() != message_center::NOTIFICATION_TYPE_PROGRESS) {
SetError(kUnexpectedProgressValueForNonProgressType);
return false;
}
int progress = *options->progress;
// Progress value should range from 0 to 100.
if (progress < 0 || progress > 100) {
SetError(kInvalidProgressValue);
return false;
}
notification->set_progress(progress);
}
if (options->items.get() && options->items->size() > 0) {
// We should have list items if and only if the type is a multiple type.
if (notification->type() != message_center::NOTIFICATION_TYPE_MULTIPLE)
return false;
std::vector< message_center::NotificationItem> items;
using api::notifications::NotificationItem;
std::vector<linked_ptr<NotificationItem> >::iterator i;
for (i = options->items->begin(); i != options->items->end(); ++i) {
message_center::NotificationItem item(UTF8ToUTF16(i->get()->title),
UTF8ToUTF16(i->get()->message));
items.push_back(item);
}
notification->set_items(items);
}
}
g_browser_process->notification_ui_manager()->Update(
*notification, profile());
return true;
}
bool NotificationsApiFunction::IsNotificationsApiEnabled() {
DesktopNotificationService* service =
DesktopNotificationServiceFactory::GetForProfile(profile());
return service->IsNotifierEnabled(message_center::NotifierId(
message_center::NotifierId::APPLICATION, extension_->id()));
}
bool NotificationsApiFunction::RunImpl() {
if (IsNotificationsApiAvailable() && IsNotificationsApiEnabled()) {
return RunNotificationsApi();
} else {
SendResponse(false);
return true;
}
}
message_center::NotificationType
NotificationsApiFunction::MapApiTemplateTypeToType(
api::notifications::TemplateType type) {
switch (type) {
case api::notifications::TEMPLATE_TYPE_NONE:
case api::notifications::TEMPLATE_TYPE_BASIC:
return message_center::NOTIFICATION_TYPE_BASE_FORMAT;
case api::notifications::TEMPLATE_TYPE_IMAGE:
return message_center::NOTIFICATION_TYPE_IMAGE;
case api::notifications::TEMPLATE_TYPE_LIST:
return message_center::NOTIFICATION_TYPE_MULTIPLE;
case api::notifications::TEMPLATE_TYPE_PROGRESS:
return message_center::NOTIFICATION_TYPE_PROGRESS;
default:
// Gracefully handle newer application code that is running on an older
// runtime that doesn't recognize the requested template.
return message_center::NOTIFICATION_TYPE_BASE_FORMAT;
}
}
const char kNotificationPrefix[] = "extensions.api.";
static uint64 next_id_ = 0;
NotificationsCreateFunction::NotificationsCreateFunction() {
}
NotificationsCreateFunction::~NotificationsCreateFunction() {
}
bool NotificationsCreateFunction::RunNotificationsApi() {
params_ = api::notifications::Create::Params::Create(*args_);
EXTENSION_FUNCTION_VALIDATE(params_.get());
// If the caller provided a notificationId, use that. Otherwise, generate
// one. Note that there's nothing stopping an app developer from passing in
// arbitrary "extension.api.999" notificationIds that will collide with
// future generated IDs. It doesn't seem necessary to try to prevent this; if
// developers want to hurt themselves, we'll let them.
const std::string extension_id(extension_->id());
std::string notification_id;
if (!params_->notification_id.empty())
notification_id = params_->notification_id;
else
notification_id = kNotificationPrefix + base::Uint64ToString(next_id_++);
SetResult(Value::CreateStringValue(notification_id));
// TODO(dewittj): Add more human-readable error strings if this fails.
if (!CreateNotification(notification_id, ¶ms_->options))
return false;
SendResponse(true);
return true;
}
NotificationsUpdateFunction::NotificationsUpdateFunction() {
}
NotificationsUpdateFunction::~NotificationsUpdateFunction() {
}
bool NotificationsUpdateFunction::RunNotificationsApi() {
params_ = api::notifications::Update::Params::Create(*args_);
EXTENSION_FUNCTION_VALIDATE(params_.get());
// We are in update. If the ID doesn't exist, succeed but call the callback
// with "false".
const Notification* matched_notification =
g_browser_process->notification_ui_manager()->FindById(
CreateScopedIdentifier(extension_->id(), params_->notification_id));
if (!matched_notification) {
SetResult(Value::CreateBooleanValue(false));
SendResponse(true);
return true;
}
// If we have trouble updating the notification (could be improper use of API
// or some other reason), mark the function as failed, calling the callback
// with false.
// TODO(dewittj): Add more human-readable error strings if this fails.
Notification notification = *matched_notification;
bool could_update_notification = UpdateNotification(
params_->notification_id, ¶ms_->options, ¬ification);
SetResult(Value::CreateBooleanValue(could_update_notification));
if (!could_update_notification)
return false;
// No trouble, created the notification, send true to the callback and
// succeed.
SendResponse(true);
return true;
}
NotificationsClearFunction::NotificationsClearFunction() {
}
NotificationsClearFunction::~NotificationsClearFunction() {
}
bool NotificationsClearFunction::RunNotificationsApi() {
params_ = api::notifications::Clear::Params::Create(*args_);
EXTENSION_FUNCTION_VALIDATE(params_.get());
bool cancel_result = g_browser_process->notification_ui_manager()->CancelById(
CreateScopedIdentifier(extension_->id(), params_->notification_id));
SetResult(Value::CreateBooleanValue(cancel_result));
SendResponse(true);
return true;
}
NotificationsGetAllFunction::NotificationsGetAllFunction() {}
NotificationsGetAllFunction::~NotificationsGetAllFunction() {}
bool NotificationsGetAllFunction::RunNotificationsApi() {
NotificationUIManager* notification_ui_manager =
g_browser_process->notification_ui_manager();
std::set<std::string> notification_ids =
notification_ui_manager->GetAllIdsByProfileAndSourceOrigin(
profile_, extension_->url());
scoped_ptr<base::DictionaryValue> result(new base::DictionaryValue());
for (std::set<std::string>::iterator iter = notification_ids.begin();
iter != notification_ids.end(); iter++) {
result->SetBooleanWithoutPathExpansion(
StripScopeFromIdentifier(extension_->id(), *iter), true);
}
SetResult(result.release());
SendResponse(true);
return true;
}
} // namespace extensions
| [
"[email protected]"
]
| |
c3b3554404dc1749cbb5f08b7cf8f2a834bbaef1 | b7f3edb5b7c62174bed808079c3b21fb9ea51d52 | /device/gamepad/hid_writer_win.cc | aab23c321c2be829c22810ee28c69a9fe8308df7 | [
"BSD-3-Clause"
]
| permissive | otcshare/chromium-src | 26a7372773b53b236784c51677c566dc0ad839e4 | 64bee65c921db7e78e25d08f1e98da2668b57be5 | refs/heads/webml | 2023-03-21T03:20:15.377034 | 2020-11-16T01:40:14 | 2020-11-16T01:40:14 | 209,262,645 | 18 | 21 | BSD-3-Clause | 2023-03-23T06:20:07 | 2019-09-18T08:52:07 | null | UTF-8 | C++ | false | false | 2,450 | 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 "device/gamepad/hid_writer_win.h"
#include <Unknwn.h>
#include <WinDef.h>
#include <stdint.h>
#include <windows.h>
namespace device {
HidWriterWin::HidWriterWin(HANDLE device) {
UINT size;
UINT result =
::GetRawInputDeviceInfo(device, RIDI_DEVICENAME, nullptr, &size);
if (result == 0U) {
std::unique_ptr<wchar_t[]> name_buffer(new wchar_t[size]);
result = ::GetRawInputDeviceInfo(device, RIDI_DEVICENAME, name_buffer.get(),
&size);
if (result == size) {
// Open the device handle for asynchronous I/O.
hid_handle_.Set(
::CreateFile(name_buffer.get(), GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
OPEN_EXISTING, FILE_FLAG_OVERLAPPED, nullptr));
}
}
}
HidWriterWin::~HidWriterWin() = default;
size_t HidWriterWin::WriteOutputReport(base::span<const uint8_t> report) {
DCHECK_GE(report.size_bytes(), 1U);
if (!hid_handle_.IsValid())
return 0;
base::win::ScopedHandle event_handle(
::CreateEvent(nullptr, false, false, L""));
OVERLAPPED overlapped = {0};
overlapped.hEvent = event_handle.Get();
// Set up an asynchronous write.
DWORD bytes_written = 0;
BOOL write_success =
::WriteFile(hid_handle_.Get(), report.data(), report.size_bytes(),
&bytes_written, &overlapped);
if (!write_success) {
DWORD error = ::GetLastError();
if (error == ERROR_IO_PENDING) {
// Wait for the write to complete. This causes WriteOutputReport to behave
// synchronously.
DWORD wait_object = ::WaitForSingleObject(overlapped.hEvent, 100);
if (wait_object == WAIT_OBJECT_0) {
::GetOverlappedResult(hid_handle_.Get(), &overlapped, &bytes_written,
true);
} else {
// Wait failed, or the timeout was exceeded before the write completed.
// Cancel the write request.
if (::CancelIo(hid_handle_.Get())) {
HANDLE handles[2];
handles[0] = hid_handle_.Get();
handles[1] = overlapped.hEvent;
::WaitForMultipleObjects(2, handles, false, INFINITE);
}
}
}
}
return write_success ? bytes_written : 0;
}
} // namespace device
| [
"[email protected]"
]
| |
1e34ab84db699bca011cae5cd994cc8306247015 | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/rsync/gumtree/rsync_patch_hunk_290.cpp | 8f4d70d3672fbccfd6c1ffc054b3263a5095534b | []
| 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 | 344 | cpp | }
if (set_perms(fname,file,NULL,0) && verbose)
fprintf(FINFO,"%s/\n",fname);
return;
}
-#if SUPPORT_LINKS
if (preserve_links && S_ISLNK(file->mode)) {
+#if SUPPORT_LINKS
char lnk[MAXPATHLEN];
int l;
if (statret == 0) {
l = readlink(fname,lnk,MAXPATHLEN-1);
if (l > 0) {
lnk[l] = 0;
| [
"[email protected]"
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.