text
string
size
int64
token_count
int64
#pragma once #include "stdafx.h" // MountainCar MDP - see Gridworld.hpp for comments regarding the general structure of these environment/MDP objects class MountainCar { public: MountainCar(); int getStateDim() const; int getNumActions() const; double update(const int & action, std::mt19937_64 & generator); std::vector<double> getState(std::mt19937_64 & generator); bool inTerminalState() const; void newEpisode(std::mt19937_64 & generator); private: const double minX = -1.2; const double maxX = 0.5; const double minXDot = -0.07; const double maxXDot = 0.07; std::vector<double> state; // [2] - x and xDot };
651
246
#include "FWCore/PluginManager/interface/ModuleDef.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/Framework/interface/ModuleFactory.h" #include "FWCore/Framework/interface/ESProducer.h" // Producers //#include "PixelTrackProducerWithZPos.h" //DEFINE_FWK_MODULE(PixelTrackProducerWithZPos); #include "PixelVertexProducerMedian.h" DEFINE_FWK_MODULE(PixelVertexProducerMedian); #include "PixelVertexProducerClusters.h" DEFINE_FWK_MODULE(PixelVertexProducerClusters); #include "TrackListCombiner.h" DEFINE_FWK_MODULE(TrackListCombiner); // Generator #include "RecoPixelVertexing/PixelTriplets/interface/HitTripletGeneratorFromPairAndLayers.h" #include "RecoPixelVertexing/PixelTriplets/interface/HitTripletGeneratorFromPairAndLayersFactory.h" #include "RecoPixelVertexing/PixelLowPtUtilities/interface/PixelTripletLowPtGenerator.h" DEFINE_EDM_PLUGIN(HitTripletGeneratorFromPairAndLayersFactory, PixelTripletLowPtGenerator, "PixelTripletLowPtGenerator"); // Seed //#include "RecoPixelVertexing/PixelLowPtUtilities/interface/SeedProducer.h" //DEFINE_FWK_MODULE(SeedProducer); // TrajectoryFilter #include "FWCore/Utilities/interface/typelookup.h" #include "FWCore/ParameterSet/interface/ValidatedPluginMacros.h" #include "TrackingTools/TrajectoryFiltering/interface/TrajectoryFilterFactory.h" #include "RecoPixelVertexing/PixelLowPtUtilities/interface/ClusterShapeTrajectoryFilter.h" DEFINE_EDM_VALIDATED_PLUGIN(TrajectoryFilterFactory, ClusterShapeTrajectoryFilter, "ClusterShapeTrajectoryFilter"); // the seed comparitor to remove seeds on incompatible angle/cluster compatibility #include "RecoPixelVertexing/PixelLowPtUtilities/interface/LowPtClusterShapeSeedComparitor.h" #include "RecoTracker/TkSeedingLayers/interface/SeedComparitorFactory.h" DEFINE_EDM_PLUGIN(SeedComparitorFactory, LowPtClusterShapeSeedComparitor, "LowPtClusterShapeSeedComparitor"); #include "RecoPixelVertexing/PixelLowPtUtilities/interface/StripSubClusterShapeTrajectoryFilter.h" DEFINE_EDM_VALIDATED_PLUGIN(TrajectoryFilterFactory, StripSubClusterShapeTrajectoryFilter, "StripSubClusterShapeTrajectoryFilter"); DEFINE_EDM_PLUGIN(SeedComparitorFactory, StripSubClusterShapeSeedFilter, "StripSubClusterShapeSeedFilter");
2,320
808
// license:BSD-3-Clause // copyright-holders:smf #include "emu.h" #include "atapicdr.h" #define SCSI_SENSE_ASC_MEDIUM_NOT_PRESENT 0x3a #define SCSI_SENSE_ASC_NOT_READY_TO_READY_TRANSITION 0x28 #define T10MMC_GET_EVENT_STATUS_NOTIFICATION 0x4a // device type definition DEFINE_DEVICE_TYPE(ATAPI_CDROM, atapi_cdrom_device, "cdrom", "ATAPI CD-ROM") DEFINE_DEVICE_TYPE(ATAPI_FIXED_CDROM, atapi_fixed_cdrom_device, "cdrom_fixed", "ATAPI fixed CD-ROM") atapi_cdrom_device::atapi_cdrom_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock) : atapi_cdrom_device(mconfig, ATAPI_CDROM, tag, owner, clock) { } atapi_cdrom_device::atapi_cdrom_device(const machine_config &mconfig, device_type type, const char *tag, device_t *owner, uint32_t clock) : atapi_hle_device(mconfig, type, tag, owner, clock) { } atapi_fixed_cdrom_device::atapi_fixed_cdrom_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock) : atapi_cdrom_device(mconfig, ATAPI_FIXED_CDROM, tag, owner, clock) { } //------------------------------------------------- // device_add_mconfig - add device configuration //------------------------------------------------- MACHINE_CONFIG_START(atapi_cdrom_device::device_add_mconfig) MCFG_CDROM_ADD("image") MCFG_CDROM_INTERFACE("cdrom") MCFG_SOUND_ADD("cdda", CDDA, 0) MACHINE_CONFIG_END void atapi_cdrom_device::device_start() { m_image = subdevice<cdrom_image_device>("image"); m_cdda = subdevice<cdda_device>("cdda"); memset(m_identify_buffer, 0, sizeof(m_identify_buffer)); m_identify_buffer[ 0 ] = 0x8500; // ATAPI device, cmd set 5 compliant, DRQ within 3 ms of PACKET command m_identify_buffer[ 23 ] = ('1' << 8) | '.'; m_identify_buffer[ 24 ] = ('0' << 8) | ' '; m_identify_buffer[ 25 ] = (' ' << 8) | ' '; m_identify_buffer[ 26 ] = (' ' << 8) | ' '; m_identify_buffer[ 27 ] = ('M' << 8) | 'A'; m_identify_buffer[ 28 ] = ('M' << 8) | 'E'; m_identify_buffer[ 29 ] = (' ' << 8) | ' '; m_identify_buffer[ 30 ] = (' ' << 8) | ' '; m_identify_buffer[ 31 ] = ('V' << 8) | 'i'; m_identify_buffer[ 32 ] = ('r' << 8) | 't'; m_identify_buffer[ 33 ] = ('u' << 8) | 'a'; m_identify_buffer[ 34 ] = ('l' << 8) | ' '; m_identify_buffer[ 35 ] = ('C' << 8) | 'D'; m_identify_buffer[ 36 ] = ('R' << 8) | 'O'; m_identify_buffer[ 37 ] = ('M' << 8) | ' '; m_identify_buffer[ 38 ] = (' ' << 8) | ' '; m_identify_buffer[ 39 ] = (' ' << 8) | ' '; m_identify_buffer[ 40 ] = (' ' << 8) | ' '; m_identify_buffer[ 41 ] = (' ' << 8) | ' '; m_identify_buffer[ 42 ] = (' ' << 8) | ' '; m_identify_buffer[ 43 ] = (' ' << 8) | ' '; m_identify_buffer[ 44 ] = (' ' << 8) | ' '; m_identify_buffer[ 45 ] = (' ' << 8) | ' '; m_identify_buffer[ 46 ] = (' ' << 8) | ' '; m_identify_buffer[ 49 ] = 0x0600; // Word 49=Capabilities, IORDY may be disabled (bit_10), LBA Supported mandatory (bit_9) atapi_hle_device::device_start(); } void atapi_cdrom_device::device_reset() { atapi_hle_device::device_reset(); m_media_change = true; } void atapi_fixed_cdrom_device::device_reset() { atapi_hle_device::device_reset(); m_cdrom = m_image->get_cdrom_file(); m_media_change = false; } void atapi_cdrom_device::process_buffer() { if(m_cdrom != m_image->get_cdrom_file()) { m_media_change = true; SetDevice(m_image->get_cdrom_file()); } atapi_hle_device::process_buffer(); } void atapi_cdrom_device::perform_diagnostic() { m_error = IDE_ERROR_DIAGNOSTIC_PASSED; } void atapi_cdrom_device::identify_packet_device() { } void atapi_cdrom_device::ExecCommand() { switch(command[0]) { case T10SBC_CMD_READ_CAPACITY: case T10SBC_CMD_READ_10: case T10MMC_CMD_READ_SUB_CHANNEL: case T10MMC_CMD_READ_TOC_PMA_ATIP: case T10MMC_CMD_PLAY_AUDIO_10: case T10MMC_CMD_PLAY_AUDIO_TRACK_INDEX: case T10MMC_CMD_PAUSE_RESUME: case T10MMC_CMD_PLAY_AUDIO_12: case T10SBC_CMD_READ_12: if(!m_cdrom) { m_phase = SCSI_PHASE_STATUS; m_sense_key = SCSI_SENSE_KEY_MEDIUM_ERROR; m_sense_asc = SCSI_SENSE_ASC_MEDIUM_NOT_PRESENT; m_status_code = SCSI_STATUS_CODE_CHECK_CONDITION; m_transfer_length = 0; return; } default: if(m_media_change) { m_phase = SCSI_PHASE_STATUS; m_sense_key = SCSI_SENSE_KEY_UNIT_ATTENTION; m_sense_asc = SCSI_SENSE_ASC_NOT_READY_TO_READY_TRANSITION; m_status_code = SCSI_STATUS_CODE_CHECK_CONDITION; m_transfer_length = 0; return; } break; case T10SPC_CMD_INQUIRY: break; case T10SPC_CMD_REQUEST_SENSE: m_media_change = false; break; } t10mmc::ExecCommand(); }
4,571
2,180
//$Id$ //------------------------------------------------------------------------------ // CompareFilesDialog //------------------------------------------------------------------------------ // GMAT: General Mission Analysis Tool // // Copyright (c) 2002 - 2020 United States Government as represented by the // Administrator of the National Aeronautics and Space Administration. // All Other 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. // // Author: Linda Jun // Created: 2005/12/22 // /** * Shows dialog where various run script folder option can be selected. */ //------------------------------------------------------------------------------ #include "CompareFilesDialog.hpp" #include "GmatStaticBoxSizer.hpp" #include "FileManager.hpp" #include "MessageInterface.hpp" #include <wx/dir.h> #include <wx/filename.h> //#define DEBUG_COMPARE_FILES_DIALOG 1 //------------------------------------------------------------------------------ // event tables and other macros for wxWindows //------------------------------------------------------------------------------ BEGIN_EVENT_TABLE(CompareFilesDialog, GmatDialog) EVT_BUTTON(ID_BUTTON_OK, GmatDialog::OnOK) EVT_BUTTON(ID_BUTTON_CANCEL, GmatDialog::OnCancel) EVT_BUTTON(ID_BUTTON, CompareFilesDialog::OnButtonClick) EVT_CHECKBOX(ID_CHECKBOX, CompareFilesDialog::OnCheckBoxChange) EVT_COMBOBOX(ID_COMBOBOX, CompareFilesDialog::OnComboBoxChange) EVT_TEXT_ENTER(ID_TEXTCTRL, CompareFilesDialog::OnTextEnterPress) EVT_RADIOBOX(ID_RADIOBOX, CompareFilesDialog::OnRadioButtonClick) END_EVENT_TABLE() //------------------------------------------------------------------------------ // CompareFilesDialog(wxWindow *parent) //------------------------------------------------------------------------------ CompareFilesDialog::CompareFilesDialog(wxWindow *parent) : GmatDialog(parent, -1, wxString(_T("CompareFilesDialog"))) { mCompareFiles = false; mSkipBlankLinesForTextCompare = false; mSaveCompareResults = false; mHasDir1 = false; mHasDir2 = false; mHasDir3 = false; mNumFilesToCompare = 0; mNumDirsToCompare = 1; mTolerance = 1.0e-6; mCompareOption = 1; mBaseDirectory = ""; mBaseString = ""; // we can have up to 3 directories to compare mCompareStrings.Add(""); mCompareStrings.Add(""); mCompareStrings.Add(""); mCompareDirs.Add(""); mCompareDirs.Add(""); mCompareDirs.Add(""); Create(); ShowData(); } //------------------------------------------------------------------------------ // ~CompareFilesDialog() //------------------------------------------------------------------------------ CompareFilesDialog::~CompareFilesDialog() { } //------------------------------------------------------------------------------ // virtual void Create() //------------------------------------------------------------------------------ void CompareFilesDialog::Create() { #if DEBUG_COMPARE_FILES_DIALOG MessageInterface::ShowMessage("CompareFilesDialog::Create() entered.\n"); #endif int bsize = 2; wxArrayString options; options.Add("Compare lines as text"); options.Add("Compare lines numerically (skips strings and blank lines)"); options.Add("Compare data columns numerically"); //------------------------------------------------------ // compare type //------------------------------------------------------ mCompareOptionRadioBox = new wxRadioBox(this, ID_RADIOBOX, wxT("Compare Option"), wxDefaultPosition, wxDefaultSize, options, 1, wxRA_SPECIFY_COLS); //------------------------------------------------------ // compare directory //------------------------------------------------------ mBaseDirTextCtrl = new wxTextCtrl(this, ID_TEXTCTRL, wxT(""), wxDefaultPosition, wxSize(400,-1), 0); mBaseDirButton = new wxButton(this, ID_BUTTON, wxT("Browse"), wxDefaultPosition, wxDefaultSize, 0); wxStaticText *baseStringLabel = new wxStaticText(this, ID_TEXT, wxT("Compare Files Contain:"), wxDefaultPosition, wxDefaultSize, 0); mBaseStrTextCtrl = new wxTextCtrl(this, ID_TEXTCTRL, mBaseString, wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER); wxStaticText *numFilesBaseDirLabel = new wxStaticText(this, ID_TEXT, wxT("Number of Files:"), wxDefaultPosition, wxDefaultSize, 0); mNumFilesInBaseDirTextCtrl = new wxTextCtrl(this, ID_TEXTCTRL, wxT("0"), wxDefaultPosition, wxDefaultSize, 0); mBaseUpdateButton = new wxButton(this, ID_BUTTON, wxT("Update"), wxDefaultPosition, wxDefaultSize, 0); wxFlexGridSizer *baseDirGridSizer = new wxFlexGridSizer(2, 0, 0); baseDirGridSizer->Add(mBaseDirTextCtrl, 0, wxALIGN_RIGHT|wxALL|wxGROW, bsize); baseDirGridSizer->Add(mBaseDirButton, 0, wxALIGN_CENTER|wxALL, bsize); wxFlexGridSizer *baseFileGridSizer = new wxFlexGridSizer(3, 0, 0); baseFileGridSizer->Add(baseStringLabel, 0, wxALIGN_LEFT|wxALL, bsize); baseFileGridSizer->Add(mBaseStrTextCtrl, 0, wxALIGN_RIGHT|wxALL|wxGROW, bsize); baseFileGridSizer->Add(20, 20, 0, wxALIGN_RIGHT|wxALL|wxGROW, bsize); baseFileGridSizer->Add(numFilesBaseDirLabel, 0, wxALIGN_LEFT|wxALL, bsize); baseFileGridSizer->Add(mNumFilesInBaseDirTextCtrl, 0, wxALIGN_RIGHT|wxALL|wxGROW, bsize); baseFileGridSizer->Add(mBaseUpdateButton, 0, wxALIGN_LEFT|wxALL, bsize); GmatStaticBoxSizer *baseDirSizer = new GmatStaticBoxSizer(wxVERTICAL, this, "Base Directory"); baseDirSizer->Add(baseDirGridSizer, 0, wxALIGN_RIGHT|wxALL|wxGROW, bsize); baseDirSizer->Add(baseFileGridSizer, 0, wxALIGN_RIGHT|wxALL|wxGROW, bsize); //------------------------------------------------------ // compare file names //------------------------------------------------------ wxString dirArray[] = {"Directory1", "Directory2", "Directory3"}; mCompareDirsComboBox = new wxComboBox(this, ID_COMBOBOX, wxT("Compare Directories"), wxDefaultPosition, wxDefaultSize, 3, dirArray, wxCB_READONLY); mCompareDirTextCtrl = new wxTextCtrl(this, ID_TEXTCTRL, wxT(""), wxDefaultPosition, wxSize(400,-1), 0); mCompareDirButton = new wxButton(this, ID_BUTTON, wxT("Browse"), wxDefaultPosition, wxDefaultSize, 0); wxStaticText *compareStringLabel = new wxStaticText(this, ID_TEXT, wxT("Compare Files Contain:"), wxDefaultPosition, wxDefaultSize, 0); mCompareStrTextCtrl = new wxTextCtrl(this, ID_TEXTCTRL, mCompareStrings[0], wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER); wxStaticText *numFilesInCompareDirLabel = new wxStaticText(this, ID_TEXT, wxT("Number of Files:"), wxDefaultPosition, wxDefaultSize, 0); mNumFilesInCompareDirTextCtrl = new wxTextCtrl(this, ID_TEXTCTRL, wxT("0"), wxDefaultPosition, wxDefaultSize, 0); mCompareUpdateButton = new wxButton(this, ID_BUTTON, wxT("Update"), wxDefaultPosition, wxDefaultSize, 0); //---------- sizer wxFlexGridSizer *compareDirGridSizer = new wxFlexGridSizer(2, 0, 0); compareDirGridSizer->Add(mCompareDirsComboBox, 0, wxALIGN_LEFT|wxALL, bsize); compareDirGridSizer->Add(20, 20, 0, wxALIGN_LEFT|wxALL, bsize); compareDirGridSizer->Add(mCompareDirTextCtrl, 0, wxALIGN_LEFT|wxALL, bsize); compareDirGridSizer->Add(mCompareDirButton, 0, wxALIGN_LEFT|wxALL, bsize); wxFlexGridSizer *compareFileGridSizer = new wxFlexGridSizer(3, 0, 0); compareFileGridSizer->Add(compareStringLabel, 0, wxALIGN_LEFT|wxALL, bsize); compareFileGridSizer->Add(mCompareStrTextCtrl, 0, wxALIGN_RIGHT|wxALL|wxGROW, bsize); compareFileGridSizer->Add(20, 20, 0, wxALIGN_RIGHT|wxALL|wxGROW, bsize); compareFileGridSizer->Add(numFilesInCompareDirLabel, 0, wxALIGN_RIGHT|wxALL|wxGROW, bsize); compareFileGridSizer->Add(mNumFilesInCompareDirTextCtrl, 0, wxALIGN_RIGHT|wxALL|wxGROW, bsize); compareFileGridSizer->Add(mCompareUpdateButton, 0, wxALIGN_LEFT|wxALL, bsize); GmatStaticBoxSizer *compareDirsSizer = new GmatStaticBoxSizer(wxVERTICAL, this, "Compare Directories"); compareDirsSizer->Add(compareDirGridSizer, 0, wxALIGN_LEFT|wxALL|wxGROW, bsize); compareDirsSizer->Add(compareFileGridSizer, 0, wxALIGN_LEFT|wxALL|wxGROW, bsize); //------------------------------------------------------ // compare results //------------------------------------------------------ wxStaticText *numDirsToCompareLabel = new wxStaticText(this, ID_TEXT, wxT("Number of Directories to Compare:"), wxDefaultPosition, wxDefaultSize, 0); mNumDirsToCompareTextCtrl = new wxTextCtrl(this, ID_TEXTCTRL, wxT("0"), wxDefaultPosition, wxDefaultSize, 0); wxStaticText *numFilesToCompareLabel = new wxStaticText(this, ID_TEXT, wxT("Number of Files to Compare:"), wxDefaultPosition, wxDefaultSize, 0); mNumFilesToCompareTextCtrl = new wxTextCtrl(this, ID_TEXTCTRL, wxT("0"), wxDefaultPosition, wxDefaultSize, 0); wxStaticText *toleranceLabel = new wxStaticText(this, ID_TEXT, wxT("Tolerance to be Used in Flagging:"), wxDefaultPosition, wxDefaultSize, 0); mToleranceTextCtrl = new wxTextCtrl(this, ID_TEXTCTRL, ToWxString(mTolerance), wxDefaultPosition, wxDefaultSize, 0); //---------- sizer wxFlexGridSizer *numFilesGridSizer = new wxFlexGridSizer(2, 0, 0); numFilesGridSizer->Add(numDirsToCompareLabel, 0, wxALIGN_LEFT|wxALL, bsize); numFilesGridSizer->Add(mNumDirsToCompareTextCtrl, 0, wxALIGN_RIGHT|wxALL|wxGROW, bsize); numFilesGridSizer->Add(numFilesToCompareLabel, 0, wxALIGN_LEFT|wxALL, bsize); numFilesGridSizer->Add(mNumFilesToCompareTextCtrl, 0, wxALIGN_RIGHT|wxALL|wxGROW, bsize); numFilesGridSizer->Add(toleranceLabel, 0, wxALIGN_LEFT|wxALL, bsize); numFilesGridSizer->Add(mToleranceTextCtrl, 0, wxALIGN_RIGHT|wxALL|wxGROW, bsize); // Inner parentheses were added below to turn off warnings // need to verify intent was not "if (!(mCompareOption == 1)" // the concern is that since mCompareOption isn't Bool the # of possible // options is unknown. As written, this is true only if mCompareOption is 0, // because if mCompareOption !=0 then !nCompareOption == 0. //if (!(mCompareOption) == 1) //warnings persisted even with parentheses around mCompareOption, so rewrote // using "!=" if (mCompareOption != 1) { numFilesGridSizer->Hide(toleranceLabel); numFilesGridSizer->Hide(mToleranceTextCtrl); } mSkipBlankLinesCheckBox = new wxCheckBox(this, ID_CHECKBOX, wxT("Skip Blank Lines for Text Compare"), wxDefaultPosition, wxDefaultSize, 0); mSaveResultCheckBox = new wxCheckBox(this, ID_CHECKBOX, wxT("Save Compare Results to File"), wxDefaultPosition, wxDefaultSize, 0); wxStaticText *saveFileLabel = new wxStaticText(this, ID_TEXT, wxT("File Name to Save:"), wxDefaultPosition, wxDefaultSize, 0); mSaveFileTextCtrl = new wxTextCtrl(this, ID_TEXTCTRL, wxT(""), wxDefaultPosition, wxSize(400,-1), 0); mSaveBrowseButton = new wxButton(this, ID_BUTTON, wxT("Browse"), wxDefaultPosition, wxDefaultSize, 0); //---------- sizer wxFlexGridSizer *saveGridSizer = new wxFlexGridSizer(2, 0, 0); saveGridSizer->Add(mSaveFileTextCtrl, 0, wxALIGN_LEFT|wxALL, bsize); saveGridSizer->Add(mSaveBrowseButton, 0, wxALIGN_CENTRE|wxALL, bsize); GmatStaticBoxSizer *compareSizer = new GmatStaticBoxSizer(wxVERTICAL, this, "Compare"); compareSizer->Add(numFilesGridSizer, 0, wxALIGN_LEFT|wxALL, bsize); compareSizer->Add(mSkipBlankLinesCheckBox, 0, wxALIGN_LEFT|wxALL, bsize); compareSizer->Add(mSaveResultCheckBox, 0, wxALIGN_LEFT|wxALL, bsize); compareSizer->Add(20, 5, 0, wxALIGN_LEFT|wxALL, bsize); compareSizer->Add(saveFileLabel, 0, wxALIGN_LEFT|wxALL, bsize); compareSizer->Add(saveGridSizer, 0, wxALIGN_LEFT|wxALL, bsize); //------------------------------------------------------ // add to page sizer //------------------------------------------------------ wxBoxSizer *pageBoxSizer = new wxBoxSizer(wxVERTICAL); pageBoxSizer->Add(mCompareOptionRadioBox, 0, wxALIGN_CENTRE|wxALL|wxGROW, bsize); pageBoxSizer->Add(baseDirSizer, 0, wxALIGN_CENTRE|wxALL|wxGROW, bsize); pageBoxSizer->Add(compareDirsSizer, 0, wxALIGN_CENTRE|wxALL|wxGROW, bsize); pageBoxSizer->Add(compareSizer, 0, wxALIGN_CENTRE|wxALL|wxGROW, bsize); theMiddleSizer->Add(pageBoxSizer, 0, wxALIGN_CENTRE|wxALL, bsize); } //------------------------------------------------------------------------------ // virtual void LoadData() //------------------------------------------------------------------------------ void CompareFilesDialog::LoadData() { #ifdef DEBUG_COMPARE_FILES_DIALOG MessageInterface::ShowMessage ("CompareFilesDialog::LoadData() entered, mNumFilesToCompare = %d\n", mNumFilesToCompare); #endif wxString str; str.Printf("%d", mNumFilesToCompare); mNumFilesToCompareTextCtrl->SetValue(str); str.Printf("%d", mNumDirsToCompare); mNumDirsToCompareTextCtrl->SetValue(str); str.Printf("%g", mTolerance); mToleranceTextCtrl->SetValue(str); FileManager *fm = FileManager::Instance(); mBaseDirectory = fm->GetFullPathname(FileManager::OUTPUT_PATH).c_str(); mCompareDirs[0] = fm->GetFullPathname(FileManager::OUTPUT_PATH).c_str(); mCompareDirs[1] = fm->GetFullPathname(FileManager::OUTPUT_PATH).c_str(); mCompareDirs[2] = fm->GetFullPathname(FileManager::OUTPUT_PATH).c_str(); mCompareDirsComboBox->SetSelection(0); mSaveFileName = mBaseDirectory + "CompareNumericResults.out"; mBaseDirTextCtrl->SetValue(mBaseDirectory); mCompareDirTextCtrl->SetValue(mCompareDirs[0]); mSaveFileTextCtrl->SetValue(mSaveFileName); // update file info in directory 1 and 2 UpdateFileInfo(0, true); UpdateFileInfo(1, false); mSaveResultCheckBox->Enable(); mSaveFileTextCtrl->Disable(); mSaveBrowseButton->Disable(); theOkButton->Enable(); #ifdef DEBUG_COMPARE_FILES_DIALOG MessageInterface::ShowMessage ("CompareFilesDialog::LoadData() leaving, mNumFilesToCompare = %d\n", mNumFilesToCompare); #endif } //------------------------------------------------------------------------------ // virtual void SaveData() //------------------------------------------------------------------------------ void CompareFilesDialog::SaveData() { long longNum; canClose = true; if (!mNumFilesToCompareTextCtrl->GetValue().ToLong(&longNum)) { wxMessageBox("Invalid number of scripts to run entered."); canClose = false; return; } mNumFilesToCompare = longNum; if (!mNumDirsToCompareTextCtrl->GetValue().ToLong(&longNum)) { wxMessageBox("Invalid number of scripts to run entered."); canClose = false; return; } mNumDirsToCompare = longNum; if (!mToleranceTextCtrl->GetValue().ToDouble(&mTolerance)) { wxMessageBox("Invalid tolerance entered."); canClose = false; return; } mSaveFileName = mSaveFileTextCtrl->GetValue(); mCompareFiles = true; if (mNumFilesToCompare <= 0) { wxMessageBox("There are no specific report files to compare.\n" "Please check file names to compare.", "GMAT Warning"); canClose = false; mCompareFiles = false; } mSkipBlankLinesForTextCompare = mSkipBlankLinesCheckBox->GetValue(); mSaveCompareResults = mSaveResultCheckBox->GetValue(); #if DEBUG_COMPARE_FILES_DIALOG MessageInterface::ShowMessage ("CompareFilesDialog::SaveData() mNumFilesToCompare=%d, " "mCompareFiles=%d, mTolerance=%e\n mBaseDirectory=%s, mCompareDirs[0]=%s, " "mBaseString=%s, mCompareStrings[0]=%s\n", mNumFilesToCompare, mCompareFiles, mTolerance, mBaseDirectory.WX_TO_C_STRING, mCompareDirs[0].WX_TO_C_STRING, mBaseString.WX_TO_C_STRING, mCompareStrings[0].WX_TO_C_STRING); #endif } //------------------------------------------------------------------------------ // virtual void ResetData() //------------------------------------------------------------------------------ void CompareFilesDialog::ResetData() { canClose = true; mCompareFiles = false; } //------------------------------------------------------------------------------ // void OnButtonClick(wxCommandEvent& event) //------------------------------------------------------------------------------ void CompareFilesDialog::OnButtonClick(wxCommandEvent& event) { if (event.GetEventObject() == mBaseDirButton) { wxDirDialog dialog(this, "Select a base directory", mBaseDirectory); if (dialog.ShowModal() == wxID_OK) { mBaseDirectory = dialog.GetPath(); mBaseDirTextCtrl->SetValue(mBaseDirectory); mSaveFileName = mBaseDirectory + "/CompareNumericResults.out"; mSaveFileTextCtrl->SetValue(mSaveFileName); //mSaveFileTextCtrl->SetValue(mBaseDirectory + "/CompareNumericResults.out"); UpdateFileInfo(0, true); #if DEBUG_COMPARE_FILES_DIALOG MessageInterface::ShowMessage ("CompareFilesDialog::OnButtonClick() mBaseDirectory=%s\n", mBaseDirectory.WX_TO_C_STRING); #endif } } else if (event.GetEventObject() == mCompareDirButton) { int dirIndex = mCompareDirsComboBox->GetSelection(); wxDirDialog dialog(this, "Select a compare dierctory", mCompareDirs[dirIndex]); if (dialog.ShowModal() == wxID_OK) { if (dirIndex == 0) mHasDir1 = true; else if (dirIndex == 1) mHasDir2 = true; else if (dirIndex == 2) mHasDir3 = true; mCompareDirs[dirIndex] = dialog.GetPath(); mCompareDirTextCtrl->SetValue(mCompareDirs[dirIndex]); UpdateFileInfo(dirIndex, false); // update number of directories to compare int numDirs = 0; if (mHasDir1) numDirs++; if (mHasDir2) numDirs++; if (mHasDir3) numDirs++; mNumDirsToCompare = numDirs; wxString str; str.Printf("%d", mNumDirsToCompare); mNumDirsToCompareTextCtrl->SetValue(str); #if DEBUG_COMPARE_FILES_DIALOG MessageInterface::ShowMessage ("CompareFilesDialog::OnButtonClick() mCompareDirs[%d]=%s\n", dirIndex, mCompareDirs[dirIndex].WX_TO_C_STRING); #endif } } else if (event.GetEventObject() == mBaseUpdateButton) { // update file info in base directory mBaseDirectory = mBaseDirTextCtrl->GetValue(); mBaseString = mBaseStrTextCtrl->GetValue(); mSaveFileName = mBaseDirectory + "/CompareNumericResults.out"; mSaveFileTextCtrl->SetValue(mSaveFileName); UpdateFileInfo(0, true); } else if (event.GetEventObject() == mCompareUpdateButton) { int dirIndex = mCompareDirsComboBox->GetSelection(); // update file info in compare directory mCompareDirs[dirIndex] = mCompareDirTextCtrl->GetValue(); mCompareStrings[dirIndex] = mCompareStrTextCtrl->GetValue(); UpdateFileInfo(dirIndex, false); } else if (event.GetEventObject() == mSaveBrowseButton) { wxString filename = wxFileSelector("Choose a file to save", mBaseDirectory, "", "txt", "Report files (*.report)|*.report|Text files (*.txt)|*.txt", wxFD_SAVE); //wxSAVE); if (!filename.empty()) { mSaveFileTextCtrl->SetValue(filename); #if DEBUG_COMPARE_FILES_DIALOG MessageInterface::ShowMessage ("CompareFilesDialog::OnButtonClick() savefile=%s\n", filename.WX_TO_C_STRING); #endif } } } //------------------------------------------------------------------------------ // void OnRadioButtonClick(wxCommandEvent& event) //------------------------------------------------------------------------------ void CompareFilesDialog::OnRadioButtonClick(wxCommandEvent& event) { mCompareOption = mCompareOptionRadioBox->GetSelection() + 1; } //------------------------------------------------------------------------------ // void OnCheckBoxChange(wxCommandEvent& event) //------------------------------------------------------------------------------ void CompareFilesDialog::OnCheckBoxChange(wxCommandEvent& event) { if (mSaveResultCheckBox->IsChecked()) { mSaveFileTextCtrl->Enable(); mSaveBrowseButton->Enable(); } else { mSaveFileTextCtrl->Disable(); mSaveBrowseButton->Disable(); } } // void OnComboBoxChange(wxCommandEvent& event) //------------------------------------------------------------------------------ void CompareFilesDialog::OnComboBoxChange(wxCommandEvent& event) { if (event.GetEventObject() == mCompareDirsComboBox) { int currDir = mCompareDirsComboBox->GetSelection(); mCompareDirTextCtrl->SetValue(mCompareDirs[currDir]); } } //------------------------------------------------------------------------------ // void OnTextEnterPress(wxCommandEvent& event) //------------------------------------------------------------------------------ void CompareFilesDialog::OnTextEnterPress(wxCommandEvent& event) { MessageInterface::ShowMessage("==> CompareFilesDialog::OnTextEnterPress() entered\n"); wxObject *eventObj = event.GetEventObject(); int dirIndex = mCompareDirsComboBox->GetSelection(); if (eventObj == mBaseDirTextCtrl) { mBaseDirectory = mBaseDirTextCtrl->GetValue(); mSaveFileName = mBaseDirectory + "/CompareNumericResults.out"; mSaveFileTextCtrl->SetValue(mSaveFileName); UpdateFileInfo(0, true); } else if (eventObj == mCompareDirTextCtrl) { mCompareDirs[dirIndex] = mCompareDirTextCtrl->GetValue(); UpdateFileInfo(0, false); } else if (eventObj == mBaseStrTextCtrl) { mBaseString = mBaseStrTextCtrl->GetValue(); UpdateFileInfo(0, true); } else if (eventObj == mCompareStrTextCtrl) { mCompareStrings[dirIndex] = mCompareStrTextCtrl->GetValue(); UpdateFileInfo(dirIndex, false); } } //------------------------------------------------------------------------------ // void UpdateFileInfo(Integer dir) //------------------------------------------------------------------------------ void CompareFilesDialog::UpdateFileInfo(Integer dir, bool isBaseDir) { #ifdef DEBUG_COMPARE_FILES_DIALOG MessageInterface::ShowMessage ("CompareFilesDialog::UpdateFileInfo() entered, dir = %d, isBaseDir = %d\n", dir, isBaseDir); #endif if (isBaseDir) { mFileNamesInBaseDir = GetFilenamesContain(mBaseDirectory, mBaseString); mNumFilesInBaseDir = mFileNamesInBaseDir.GetCount(); mNumFilesInBaseDirTextCtrl->SetValue(""); *mNumFilesInBaseDirTextCtrl << mNumFilesInBaseDir; } else { mFileNamesInCompareDir = GetFilenamesContain(mCompareDirs[dir], mCompareStrings[dir]); mNumFilesInCompareDir = mFileNamesInCompareDir.GetCount(); mNumFilesInCompareDirTextCtrl->SetValue(""); *mNumFilesInCompareDirTextCtrl << mNumFilesInCompareDir; } // number of files to compare mNumFilesToCompareTextCtrl->SetValue(""); if (mNumFilesInBaseDir == 0 || mNumFilesInCompareDir == 0) *mNumFilesToCompareTextCtrl << 0; else *mNumFilesToCompareTextCtrl << mNumFilesInBaseDir; mNumFilesToCompare = mNumFilesInBaseDir; #ifdef DEBUG_COMPARE_FILES_DIALOG MessageInterface::ShowMessage ("CompareFilesDialog::UpdateFileInfo() leaving, mNumFilesInBaseDir = %d, " "mNumFilesToCompare = %d\n", mNumFilesInBaseDir, mNumFilesToCompare); #endif } //------------------------------------------------------------------------------ // wxArrayString GetFilenamesContain(const wxString &dirname, // const wxString &str) //------------------------------------------------------------------------------ wxArrayString CompareFilesDialog::GetFilenamesContain(const wxString &dirname, const wxString &str) { #ifdef DEBUG_COMPARE_FILES_DIALOG MessageInterface::ShowMessage ("CompareFilesDialog::GetFilenamesContain() entered, dirname = '%s', str = '%s'\n", dirname.WX_TO_C_STRING, str.WX_TO_C_STRING); #endif wxDir dir(dirname); wxString filename; wxString filepath; wxArrayString fileNames; bool cont = dir.GetFirst(&filename); while (cont) { if (filename.Contains(".report") || filename.Contains(".txt") || filename.Contains(".data") || filename.Contains(".script") || filename.Contains(".eph") || filename.Contains(".oem") || filename.Contains(".e") || filename.Contains(".truth")) { // If not backup files // Add files ending 't' for report, txt, and script // 'a' for data, 'h' for eph and truth, 'm' for .oem, 'e' for .e if (filename.Last() == 't' || filename.Last() == 'a' || filename.Last() == 'h' || filename.Last() == 'm' || filename.Last() == 'e') { if (filename.Contains(str)) { filepath = dirname + "/" + filename; fileNames.Add(filepath); } } } cont = dir.GetNext(&filename); } #ifdef DEBUG_COMPARE_FILES_DIALOG MessageInterface::ShowMessage ("CompareFilesDialog::GetFilenamesContain() returning %d files\n", fileNames.size()); #endif return fileNames; }
26,843
8,432
#include <set> #include <vector> #include "dg/ReachingDefinitions/ReachingDefinitions.h" #include "dg/BBlocksBuilder.h" namespace dg { namespace dda { void ReadWriteGraph::buildBBlocks(bool dce) { assert(getRoot() && "No root node"); DBG(dda, "Building basic blocks"); BBlocksBuilder<RWBBlock> builder; _bblocks = std::move(builder.buildAndGetBlocks(getRoot())); assert(getRoot()->getBBlock() && "Root node has no BBlock"); // should we eliminate dead code? // The dead code are the nodes that have no basic block assigned // (follows from the DFS nature of the block builder algorithm) if (!dce) return; for (auto& nd : _nodes) { if (nd->getBBlock() == nullptr) { nd->isolate(); nd.reset(); } } } void ReadWriteGraph::removeUselessNodes() { } } // namespace dda } // namespace dg
883
293
#include "features.hpp" #include <SDL2/SDL_scancode.h> #include <vector> int score; ImVec2 cursorPos; float deltaTime; bool alive = true; bool paused = false; float birdHeight; class Bird { public: void draw(ImDrawList* drawList) { drawList->AddRectFilled(ImVec2{cursorPos.x+60, cursorPos.y+(400-height)}, ImVec2{cursorPos.x+70, cursorPos.y+(400-height)+10}, ImColor(255, 255, 255, 255)); if (alive) { if (!paused) { height += velocity*deltaTime; // add velocity birdHeight = height; velocity -= 250.f*deltaTime; // gravity if (height < 50) { alive = false; } } } else { height = 300; score = 0; drawList->AddText(ImVec2{ImVec2{cursorPos.x+10, cursorPos.y+10}}, ImColor(255, 255, 255, 255), "You died, press up arrow to respawn"); } } void handleInput() { if (ImGui::IsKeyPressed(SDL_SCANCODE_UP, false) && !paused) { velocity = 140.f; alive = true; } else if (ImGui::IsKeyPressed(SDL_SCANCODE_DOWN, false) && alive) { paused = !paused; } } float velocity = 0; float height = 300; }; class Pipe { public: Pipe(float startX) { x = startX; xOriginal = startX; gapTop = (rand() % 200) + 130; gapBottom = gapTop - 65; } void draw(ImDrawList* drawList) { drawList->AddRectFilled(ImVec2{cursorPos.x+x, cursorPos.y}, ImVec2{cursorPos.x+x+40, cursorPos.y+(400-gapTop)}, ImColor(0, 65, 0, 255)); drawList->AddRectFilled(ImVec2{cursorPos.x+x, cursorPos.y+400}, ImVec2{cursorPos.x+x+40, cursorPos.y+(400-gapBottom)}, ImColor(0, 65, 0, 255)); if (alive) { if (!paused) { x -= 90.f * deltaTime; if (x < -200) { x = 400; gapTop = (rand() % 200) + 130; gapBottom = gapTop - 65; hasBirdPassed = false; } if ((x < 70) && (x > 20)) { if ((birdHeight > gapTop) || (birdHeight < gapBottom)) { alive = false; } if (!hasBirdPassed) { score++; hasBirdPassed = true; } } } } else { x = xOriginal; gapTop = (rand() % 200) + 130; gapBottom = gapTop - 65; hasBirdPassed = false; } } bool hasBirdPassed = false; float gapTop = 300, gapBottom = 235; float x; float xOriginal; }; void Features::FlappyBird::draw() { if (CONFIGBOOL("Misc>Misc>Misc>Flappy Birb")) { ImGui::Begin("Flappy Birb", nullptr, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | (Menu::open ? 0 : ImGuiWindowFlags_NoMouseInputs)); ImGui::Text("Flappy Birb (Score %i)", score); ImGui::Separator(); ImDrawList* drawList = ImGui::GetWindowDrawList(); deltaTime = ImGui::GetIO().DeltaTime; cursorPos = ImGui::GetCursorScreenPos(); drawList->AddRectFilled(ImVec2{cursorPos.x, cursorPos.y}, ImVec2{cursorPos.x+400, cursorPos.y+400}, ImColor(0, 0, 0, 255)); drawList->AddRectFilled(ImVec2{cursorPos.x, cursorPos.y+360}, ImVec2{cursorPos.x+400, cursorPos.y+400}, ImColor(0, 80, 0, 255)); static Bird bird; bird.handleInput(); bird.draw(drawList); static Pipe pipe(400); pipe.draw(drawList); static Pipe pipe2(550); pipe2.draw(drawList); static Pipe pipe3(700); pipe3.draw(drawList); if (paused) { drawList->AddText(ImVec2{ImVec2{cursorPos.x+10, cursorPos.y+10}}, ImColor(255, 255, 255, 255), "Paused"); } ImGui::End(); } }
3,957
1,443
/* Atanua Real-Time Logic Simulator Copyright (c) 2008-2014 Jari Komppa This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "atanua.h" #include "16segchip.h" #include "slidingaverage.h" SixteenSegChip::SixteenSegChip(int aColor, int aInverse) { mAvg = new SlidingAverage[17]; mInverse = aInverse; mColor = aColor & 0xffffff; set(0, 0, 3.5, 4, NULL); mPin.push_back(&mInputPin[0]); mPin.push_back(&mInputPin[1]); mPin.push_back(&mInputPin[2]); mPin.push_back(&mInputPin[3]); mPin.push_back(&mInputPin[4]); mPin.push_back(&mInputPin[5]); mPin.push_back(&mInputPin[6]); mPin.push_back(&mInputPin[7]); mPin.push_back(&mInputPin[8]); mPin.push_back(&mInputPin[9]); mPin.push_back(&mInputPin[10]); mPin.push_back(&mInputPin[11]); mPin.push_back(&mInputPin[12]); mPin.push_back(&mInputPin[13]); mPin.push_back(&mInputPin[14]); mPin.push_back(&mInputPin[15]); mPin.push_back(&mInputPin[16]); int i; for (i = 0; i < 17; i++) mInputPin[i].mReadOnly = 1; float ypos = 0.1; float step = 0.42; mInputPin[0].set(0.03,ypos,this,"Pin 1: A1"); ypos += step; mInputPin[1].set(0.03,ypos,this,"Pin 2: A2"); ypos += step; mInputPin[2].set(0.03,ypos,this,"Pin 3: J"); ypos += step; mInputPin[3].set(0.03,ypos,this,"Pin 4: H"); ypos += step; mInputPin[4].set(0.03,ypos,this,"Pin 5: F"); ypos += step; mInputPin[5].set(0.03,ypos,this,"Pin 6: E"); ypos += step; mInputPin[6].set(0.03,ypos,this,"Pin 7: N"); ypos += step; mInputPin[7].set(0.03,ypos,this,"Pin 8: D1"); ypos += step; mInputPin[8].set(0.03,ypos,this,"Pin 9: D2"); ypos += step; ypos -= step; ypos -= step; mInputPin[9].set(2.95,ypos,this,"Pin 11: K"); ypos -= step; mInputPin[10].set(2.95,ypos,this,"Pin 12: B"); ypos -= step; mInputPin[11].set(2.95,ypos,this,"Pin 13: G2"); ypos -= step; mInputPin[12].set(2.95,ypos,this,"Pin 14: G1"); ypos -= step; mInputPin[13].set(2.95,ypos,this,"Pin 15: C"); ypos -= step; mInputPin[14].set(2.95,ypos,this,"Pin 16: L"); ypos -= step; mInputPin[15].set(2.95,ypos,this,"Pin 17: M"); ypos -= step; mInputPin[16].set(2.95,ypos,this,"Pin 18: DP"); ypos -= step; mTexture[0] = load_texture("data/16seg_base.png"); mTexture[1] = load_texture("data/16seg_a1.png"); mTexture[2] = load_texture("data/16seg_a2.png"); mTexture[3] = load_texture("data/16seg_j.png"); mTexture[4] = load_texture("data/16seg_h.png"); mTexture[5] = load_texture("data/16seg_f.png"); mTexture[6] = load_texture("data/16seg_e.png"); mTexture[7] = load_texture("data/16seg_n.png"); mTexture[8] = load_texture("data/16seg_d1.png"); mTexture[9] = load_texture("data/16seg_d2.png"); mTexture[10] = load_texture("data/16seg_k.png"); mTexture[11] = load_texture("data/16seg_b.png"); mTexture[12] = load_texture("data/16seg_g1.png"); mTexture[13] = load_texture("data/16seg_g2.png"); mTexture[14] = load_texture("data/16seg_c.png"); mTexture[15] = load_texture("data/16seg_l.png"); mTexture[16] = load_texture("data/16seg_m.png"); mTexture[17] = load_texture("data/16seg_dp.png"); } SixteenSegChip::~SixteenSegChip() { delete[] mAvg; } void SixteenSegChip::render(int aChipId) { drawtexturedrect(mTexture[0], mX-0.25, mY, mW+0.5, mH, 0xffffffff); glBlendFunc(GL_ONE,GL_SRC_ALPHA); int i; for (i = 0; i < 17; i++) { float val = mAvg[i].getAverage(); if (val > 0) { if (val > 0.1) val = 1.0; else val *= 10; int col = ((int)(((mColor >> 0) & 0xff) * val) << 0) | ((int)(((mColor >> 8) & 0xff) * val) << 8) | ((int)(((mColor >> 16) & 0xff) * val) << 16); drawtexturedrect(mTexture[i+1], mX-0.25, mY, mW+0.5, mH, 0xff000000 | col); } } glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA); } void SixteenSegChip::update(float aTick) { int i; for (i = 0; i < 17; i++) { mAvg[i].setValue(mInputPin[i].mNet && ((mInputPin[i].mNet->mState == NETSTATE_HIGH) ^ (!!mInverse))); } mDirty = 1; }
4,729
2,236
#include<iostream> #include<stdlib.h> using namespace std; // 单链表的操作 typedef struct LinkNode{ int data; struct LinkNode *next; }LinkNode; // headermake void creat(LinkNode *L){ LinkNode *node; for(int i = 0;i < 10;i++){ node = (LinkNode *)malloc(sizeof(LinkNode)); node->data = rand()%13; node->next = L->next; L->next = node; } // return L; } void PrintOut(LinkNode *L){ int time = 1; while(L->next != NULL){ if(time > 20) return; cout<<L->next->data<<" "; L = L->next; time ++; } cout<<endl; } //第一个为标准,前面比他小,后面比他大。practice 5 void sortA(LinkNode *L){ int time = 1; LinkNode *s = L->next; LinkNode *p = s->next; LinkNode *pre; cout<<s->data<<endl; s->next = NULL; LinkNode *qre = s; while(p != NULL){ if(time > 30) return; time++; if(p->data < s->data){ pre = p->next; p->next = L->next; L->next = p; p = pre; }else if(p->data > s->data){ pre = p->next; p->next = s->next; s->next = p; p = pre; } } } //practice 6 caculate the last site element int func_6(LinkNode *L,int k){ LinkNode *p,*q; p = L->next; q = L->next; while(k > 1&&q->next != NULL){ q = q->next; k--; } if(q->next == NULL){ cout<<0<<endl; return 0; } while(q->next != NULL){ q = q->next; p = p->next; } cout<<p->data<<endl; return 1; } // reversed way 1 void func_7(LinkNode *L){ LinkNode *p = L->next; LinkNode *q; L->next = NULL; while(p != NULL){ q = p->next; p->next = L->next; L->next = p; p = q; } } // reversede way 2 void func_8(LinkNode *L){ LinkNode *p,*q,*r; p = L->next; q = p->next; p->next = NULL; while(q->next != NULL){ r = q->next; q->next = p; p = q; q = r; } q->next = p; L->next = q; } int main(){ LinkNode *L; L = (LinkNode *)malloc(sizeof(LinkNode)); L->next = NULL; creat(L); PrintOut(L); //practice 5 //sortA(L); //PrintOut(L); //pracetice 6 //func_6(L,4); //reversed without other space //func_7(L); func_8(L); PrintOut(L); return 0; }
2,392
963
#include "aoc21/helpers.h" #include <array> #include <algorithm> #include <list> #include <map> #include <set> #include <vector> namespace { constexpr int RoomCount = 4; constexpr int RoomDepth = 2; constexpr int HallwaySize = 4 + (RoomCount * 2) - 1; using Hallway = std::array<char, HallwaySize>; using Room = std::string; using Rooms = std::array<Room, RoomCount>; using CharIntMap = std::map<char, int>; CharIntMap EnergyCost = { {'A', 1 }, { 'B', 10 }, { 'C', 100 }, { 'D', 1000 } }; CharIntMap RoomAssignments = { { 'A', 0 }, { 'B', 1 }, { 'C', 2 }, { 'D', 3 } }; const auto IsFish = [](const char f) { return f >= 'A' && f <= 'D'; }; #if !defined (NDEBUG) const auto IsRoom = [](const int room) { return room >= 0 && room < RoomCount; }; #endif const auto TargetRoom = [](const char f) { assert(IsFish(f)); return f - 'A'; }; class MapState { public: int energy; int roomDepth; Hallway hallway; Rooms rooms; std::vector<int>doorways; MapState(int depth) : energy(0) , roomDepth(depth) { for (auto& c : hallway) { c = '.'; } } MapState() : MapState(RoomDepth) { } void insertFish(const std::vector<std::string> fish) { int i = 0; for (auto& r : rooms) { std::string new_r(&r[0], 1); new_r += fish[i++]; new_r += (r.substr(1)); r = new_r; } roomDepth = rooms[0].size(); } std::string hash() const { std::string s; for (const auto&c : hallway) { s.append(&c, 1); } for (const auto& r : rooms) { s.append(",", 1); s.append(r); } return s; } bool isDesiredRoom(char fish, int room) const { assert(IsFish(fish)); assert(IsRoom(room)); return RoomAssignments[fish] == room; } bool isRoomFinal(int room) const { assert(IsRoom(room)); if (rooms[room].size() < static_cast<size_t>(roomDepth)) { return false; } for (const auto& f : rooms[room]) { if (!isDesiredRoom(f, room)) { return false; } } return true; } bool final() const { for (int i = 0; i < RoomCount; i++) { if (!isRoomFinal(i)) { return false; } } return true; } bool isDoorway(const int p) const { return std::find(doorways.begin(), doorways.end(), p) != doorways.end(); } int getRoom(const int p) const { for (size_t i = 0; i < doorways.size(); i++) { if (doorways[i] == p) { return i; } } return -1; } MapState move(int from, int to) { MapState next(*this); auto fish = next.hallway[from]; int steps = 0; const int from_room = getRoom(from); const int to_room = getRoom(to); if (from_room != -1) { fish = next.rooms[from_room].front(); // remove the first element from the room next.rooms[from_room].erase(0, 1); // steps to get out of room steps += (next.roomDepth - next.rooms[from_room].size()); } else { next.hallway[from] = '.'; } // steps between spaces steps += ::abs(to - from); if (to_room != -1) { // steps to emplace in the room steps += (next.roomDepth - next.rooms[to_room].size()); next.rooms[to_room] = fish + next.rooms[to_room]; } else { next.hallway[to] = fish; } next.energy += steps * EnergyCost[fish]; return next; } bool isHallwayClear(const int from, const int to) const { assert(std::min(from, to) == from); assert(std::max(from, to) == to); for (int k = from; k < to; k++) { if (isDoorway(k)) { // nothing can be directly above a room continue; } // if a hallway spot is occupied, no bueno if (hallway[k] != '.') { return false; } } return true; } bool isTargetRoomClear(const int to) const { assert(IsRoom(to)); if (rooms[to].size() == static_cast<size_t>(roomDepth)) { // room is full return false; } for (const auto& c : rooms[to]) { // room has non-correct occupant if (!isDesiredRoom(c, to)) { return false; } } return true; } bool canMoveToHall(const int from, const int to) const { assert(IsRoom(from)); assert(to >= 0 && to < HallwaySize); const int door_from = doorways[from]; const int i = std::min(door_from, to); const int j = std::max(door_from, to); if (isDoorway(to)) { return false; } return isHallwayClear(i, j); } bool canMoveToRoom(const int from, const int to) const { assert(IsRoom(from)); assert(IsRoom(to)); const int door_from = doorways[from]; const int door_to = doorways[to]; const int i = std::min(door_from, door_to); const int j = std::max(door_from, door_to); return isTargetRoomClear(to) && isHallwayClear(i, j); } bool canMoveFromHall(const int from, const int to) const { assert(from >= 0 && from < HallwaySize); assert(IsRoom(to)); const int door_to = doorways[to]; const int i = std::min(from, door_to); const int j = std::max(from, door_to); return isTargetRoomClear(to) && isHallwayClear(i + 1, j); } bool valid() const { int fish = 0; for (const auto& r : rooms) { fish += r.size(); if (r.size() > static_cast<size_t>(roomDepth)) { return false; } } for (const auto& c : hallway) { fish += IsFish(c); } return fish == roomDepth * RoomCount; } friend std::ostream& operator<<(std::ostream& os, const MapState& m) { os << aoc::cls; os << "#"; for (size_t i = 0; i < m.hallway.size(); i++) { os << "#"; } os << "#"; os << std::endl; os << "#"; for (const auto& c : m.hallway) { os << c; } os << "#"; os << std::endl; os << "#"; for (size_t i = 0; i < m.hallway.size(); i++) { if (m.isDoorway(i)) { os << '.'; } else { os << "#"; } } os << "#"; return os; } }; struct HeapComparator { bool operator()(const MapState& lhs, const MapState& rhs) { return lhs.energy > rhs.energy; } }; using StateList = std::vector<MapState>; const auto HeapPop = [](auto& heap) { auto s = heap.front(); std::pop_heap(heap.begin(), heap.end(), HeapComparator()); heap.pop_back(); return s; }; const auto HeapPush = [](auto& heap, auto& s) { heap.emplace_back(s); std::push_heap(heap.begin(), heap.end(), HeapComparator()); }; int solve(MapState map) { aoc::AutoTimer __t; // Maintain a heap of states StateList sq; sq.push_back(map); std::make_heap(sq.begin(), sq.end(), HeapComparator()); // Maintain a list of visited states, so we can quickly eliminate them from our A* int result = INT_MAX; std::set<std::string> seen; while (result == INT_MAX && !sq.empty()) { auto s = HeapPop(sq); const auto r = seen.emplace(s.hash()); if (!r.second) { continue; } if (s.final()) { result = s.energy; break; } for (int i = 0; i < RoomCount; i++) { if (!s.isRoomFinal(i)) { const auto fish = s.rooms[i].front(); if (!IsFish(fish)) { continue; } const auto t = TargetRoom(fish); if (s.canMoveToRoom(i, t)) { const auto next = s.move(s.doorways[i], s.doorways[t]); assert(next.valid()); HeapPush(sq, next); } } for (int j = 0; j < HallwaySize; j++) { const auto fish = s.rooms[i].front(); if (!IsFish(fish)) { continue; } const auto tf = s.hallway[j]; if (IsFish(tf)) { continue; } if (s.canMoveToHall(i, j)) { const auto next = s.move(s.doorways[i], j); assert(next.valid()); HeapPush(sq, next); } } } for (int j = 0; j < HallwaySize; j++) { const char fish = s.hallway[j]; if (!IsFish(fish)) { continue; } const auto t = TargetRoom(fish); if (s.canMoveFromHall(j, t)) { const auto next = s.move(j, s.doorways[t]); assert(next.valid()); HeapPush(sq, next); } } } return result; } }; int main(int argc, char** argv) { aoc::AutoTimer t; auto f = aoc::open_argv_1(argc, argv); MapState map; std::string line; while (aoc::getline(f, line)) { constexpr int MinLineSize = 2 + (RoomCount * 2); constexpr int RoomOffset = 3; assert(line.size() > RoomOffset); const char c = line[RoomOffset]; assert(c == '#' || c == '.' || (c >= 'A' && c <= 'D')); if (c < 'A' || c > 'D') { continue; } assert(line.size() > MinLineSize); int room = 0; for (int i = RoomOffset; i < MinLineSize; i += 2) { map.rooms[room].push_back(line[i]); map.doorways.push_back(i - 1); room++; } } f.close(); const auto part1 = solve(map); aoc::print_result(1, part1); map.insertFish({ "DD", "CB", "BA", "AC" }); const auto part2 = solve(map); aoc::print_result(2, part2); return 0; }
9,594
3,423
// // MIT License // // Copyright (c) 2017-2018 Thibault Martinez and Simon Ninon // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // // #include <algorithm> #include <iota/constants.hpp> #include <iota/crypto/kerl.hpp> #include <iota/models/bundle.hpp> #include <iota/types/trinary.hpp> #include <iota/types/utils.hpp> namespace IOTA { namespace Models { Bundle::Bundle(const std::vector<Models::Transaction>& transactions) : transactions_(transactions) { if (!empty()) { hash_ = transactions_[0].getBundle(); } } const std::vector<Models::Transaction>& Bundle::getTransactions() const { return transactions_; } std::vector<Models::Transaction>& Bundle::getTransactions() { return transactions_; } std::size_t Bundle::getLength() const { return transactions_.size(); } bool Bundle::empty() const { return getLength() == 0; } const Types::Trytes& Bundle::getHash() const { return hash_; } void Bundle::setHash(const Types::Trytes& hash) { hash_ = hash; } void Bundle::addTransaction(const Transaction& transaction, int32_t signatureMessageLength) { if (empty()) { hash_ = transaction.getBundle(); } transactions_.push_back(transaction); if (signatureMessageLength > 1) { Transaction signatureTransaction = { transaction.getAddress(), 0, transaction.getTag(), transaction.getTimestamp() }; for (int i = 1; i < signatureMessageLength; i++) { transactions_.push_back(signatureTransaction); } } } void Bundle::generateHash() { Crypto::Kerl k; for (std::size_t i = 0; i < transactions_.size(); i++) { auto& trx = transactions_[i]; trx.setCurrentIndex(i); trx.setLastIndex(transactions_.size() - 1); auto value = Types::tritsToTrytes(Types::intToTrits(trx.getValue(), SeedLength)); auto timestamp = Types::tritsToTrytes(Types::intToTrits(trx.getTimestamp(), TryteAlphabetLength)); auto currentIndex = Types::tritsToTrytes(Types::intToTrits(trx.getCurrentIndex(), TryteAlphabetLength)); auto lastIndex = Types::tritsToTrytes(Types::intToTrits(trx.getLastIndex(), TryteAlphabetLength)); auto bytes = Types::trytesToBytes(trx.getAddress().toTrytes() + value + trx.getObsoleteTag().toTrytesWithPadding() + timestamp + currentIndex + lastIndex); k.absorb(bytes); } std::vector<uint8_t> hash(ByteHashLength); k.finalSqueeze(hash); hash_ = Types::bytesToTrytes(hash); } void Bundle::finalize() { bool validBundle = false; while (!validBundle) { //! generate hash generateHash(); //! check that normalized hash does not contain "13" (otherwise, this may lead to security flaw) auto normalizedHash = normalizedBundle(hash_); if (!transactions_.empty() && std::find(std::begin(normalizedHash), std::end(normalizedHash), 13 /* = M */) != std::end(normalizedHash)) { // Insecure bundle. Increment Tag and recompute bundle hash. auto tagTrits = Types::trytesToTrits(transactions_[0].getObsoleteTag().toTrytesWithPadding()); Types::incrementTrits(tagTrits); transactions_[0].setObsoleteTag(Types::tritsToTrytes(tagTrits)); } else { validBundle = true; } } //! set bundle hash for each underlying transaction for (std::size_t i = 0; i < transactions_.size(); i++) { transactions_[i].setBundle(hash_); } } void Bundle::addTrytes(const std::vector<Types::Trytes>& signatureFragments) { Types::Trytes emptySignatureFragment = Types::Utils::rightPad("", 2187, '9'); for (unsigned int i = 0; i < transactions_.size(); i++) { auto& transaction = transactions_[i]; // Fill empty signatureMessageFragment transaction.setSignatureFragments( (signatureFragments.size() <= i || signatureFragments[i].empty()) ? emptySignatureFragment : signatureFragments[i]); // Fill empty trunkTransaction transaction.setTrunkTransaction(EmptyHash); // Fill empty branchTransaction transaction.setBranchTransaction(EmptyHash); // Fill empty nonce transaction.setNonce(EmptyNonce); } } std::vector<int8_t> Bundle::normalizedBundle(const Types::Trytes& bundleHash) { std::vector<int8_t> normalizedBundle(SeedLength, 0); for (int i = 0; i < 3; i++) { long sum = 0; for (unsigned int j = 0; j < TryteAlphabetLength; j++) { sum += (normalizedBundle[i * TryteAlphabetLength + j] = Types::tritsToInt<int32_t>( Types::trytesToTrits(Types::Trytes(1, bundleHash[i * TryteAlphabetLength + j])))); } if (sum >= 0) { while (sum-- > 0) { for (unsigned int j = 0; j < TryteAlphabetLength; j++) { if (normalizedBundle[i * TryteAlphabetLength + j] > -13) { normalizedBundle[i * TryteAlphabetLength + j]--; break; } } } } else { while (sum++ < 0) { for (unsigned int j = 0; j < TryteAlphabetLength; j++) { if (normalizedBundle[i * TryteAlphabetLength + j] < 13) { normalizedBundle[i * TryteAlphabetLength + j]++; break; } } } } } return normalizedBundle; } bool Bundle::operator<(const Bundle& rhs) const { int64_t lhsTS = empty() ? 0 : transactions_[0].getAttachmentTimestamp(); int64_t rhsTS = rhs.empty() ? 0 : rhs[0].getAttachmentTimestamp(); return lhsTS < rhsTS; } bool Bundle::operator>(const Bundle& rhs) const { int64_t lhsTS = empty() ? 0 : transactions_[0].getAttachmentTimestamp(); int64_t rhsTS = rhs.empty() ? 0 : rhs[0].getAttachmentTimestamp(); return lhsTS > rhsTS; } bool Bundle::operator==(const Bundle& rhs) const { return getHash() == rhs.getHash(); } bool Bundle::operator!=(const Bundle& rhs) const { return !operator==(rhs); } Transaction& Bundle::operator[](const int index) { return transactions_[index]; } const Transaction& Bundle::operator[](const int index) const { return transactions_[index]; } } // namespace Models } // namespace IOTA
7,181
2,330
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////#include "tinyhal.h" #include "tinyhal.h" //////////////////////////////////////////////////////////////////////////////////////////////////// #if !defined(BUILD_RTM) void debug_printf(char const* format, ... ) { } void lcd_printf(char const * format,...) { } #endif const ConfigurationSector g_ConfigurationSector; int hal_strcpy_s( char* strDst, size_t sizeInBytes, const char* strSrc ) { strncpy(strDst, strSrc, sizeInBytes); } int hal_strncpy_s( char* strDst, size_t sizeInBytes, const char* strSrc, size_t count ) { strncpy(strDst, strSrc, __min(sizeInBytes, count)); } ///////////////////////////////////////////////////////////////////////////////////////////
1,180
278
// JPZsumofdigits.cpp : Defines the entry point for the console application. // Joshua Paz; a program that takes a whole integer and adds the digits for a sum #include "stdafx.h" #include <iostream> using namespace std; int main() { //variables int userint = 0; int intholder = 0; int sum = 0; //prompt for user to enter an integer cout << "Please enter an integer: "; cin >> userint; cout << endl; //storage for the integer intholder = userint; //create loop to run equation while (userint > 0) { intholder = userint % 10; cout << "Digit:" << intholder << endl; sum += intholder; userint /= 10; } cout << "" << endl; cout << "The sum of the digits is: " << sum << endl; // output the sum return 0; }
771
285
// -------------------------------------------------------------------------- // OpenMS -- Open-Source Mass Spectrometry // -------------------------------------------------------------------------- // Copyright The OpenMS Team -- Eberhard Karls University Tuebingen, // ETH Zurich, and Freie Universitaet Berlin 2002-2018. // // This software is released under a three-clause BSD license: // * 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 any author or any participating institution // may be used to endorse or promote products derived from this software // without specific prior written permission. // For a full list of authors, refer to the file AUTHORS. // -------------------------------------------------------------------------- // 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 ANY OF THE AUTHORS OR THE CONTRIBUTING // INSTITUTIONS 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. // // -------------------------------------------------------------------------- // $Maintainer: Eugen Netz $ // $Authors: Eugen Netz $ // -------------------------------------------------------------------------- #include <OpenMS/ANALYSIS/ID/PrecursorPurity.h> #include <OpenMS/CONCEPT/Constants.h> #include <OpenMS/CONCEPT/LogStream.h> namespace OpenMS { PrecursorPurity::PurityScores PrecursorPurity::computePrecursorPurity(const PeakSpectrum& ms1, const Precursor& pre, const double precursor_mass_tolerance, const bool precursor_mass_tolerance_unit_ppm) { PrecursorPurity::PurityScores score; double target_mz = pre.getMZ(); double lower = target_mz - pre.getIsolationWindowLowerOffset(); double upper = target_mz + pre.getIsolationWindowUpperOffset(); int charge = pre.getCharge(); double precursor_tolerance_abs = precursor_mass_tolerance_unit_ppm ? (target_mz * precursor_mass_tolerance*2 * 1e-6) : precursor_mass_tolerance*2; auto lower_it = ms1.MZBegin(lower); auto upper_it = ms1.MZEnd(upper); // std::cout << "charge: " << charge << " | lower: " << lower << " | target: " << target_mz << " | upper: " << upper << std::endl; // std::cout << "lower offset: " << pre.getIsolationWindowLowerOffset() << " | upper offset: " << pre.getIsolationWindowUpperOffset() << std::endl; // std::cout << "lower peak: " << (*lower_it).getMZ() << " | upper peak: " << (*upper_it).getMZ() << std::endl; PeakSpectrum isolated_window; while (lower_it != upper_it) { isolated_window.push_back(*lower_it); lower_it++; } // std::cout << "Isolation window peaks: " << isolated_window.size(); // for (auto peak : isolated_window) // { // std::cout << " | " << peak.getMZ(); // } // std::cout << std::endl; // total intensity in isolation window double total_intensity(0); double target_intensity(0); Size target_peak_count(0); for (auto peak : isolated_window) { total_intensity += peak.getIntensity(); } // search for the target peak, return scores with 0-values if it is not found if (isolated_window.empty()) { return score; } // estimate a lower boundary for isotopic peaks int negative_isotopes((pre.getIsolationWindowLowerOffset() * charge)); double iso = -negative_isotopes; // depending on the isolation window, the first estimated peak might be outside the window if (target_mz + (iso * Constants::C13C12_MASSDIFF_U / charge) < lower) { iso++; } // std::cout << "target peaks: "; // deisotoping (try to find isotopic peaks of the precursor mass, even if the actual precursor peak is missing) while (true) // runs as long as the next mz is within the isolation window { double next_peak = target_mz + (iso * Constants::C13C12_MASSDIFF_U / charge); // std::cout << iso << " : iso | " << next_peak << " : next peak | "; // stop loop when new mz is outside the isolation window // changes through the isotope index iso if (next_peak > upper) { break; } int next_iso_index = isolated_window.findNearest(next_peak, precursor_tolerance_abs); if (next_iso_index != -1) { target_intensity += isolated_window[next_iso_index].getIntensity(); // std::cout << isolated_window[next_iso_index].getMZ() << " : matched | "; isolated_window.erase(isolated_window.begin()+next_iso_index); target_peak_count++; } // always increment iso to progress the loop iso++; } // std::cout << std::endl; // // std::cout << "noise peaks: "; // double noise_intensity(0); // for (auto peak : isolated_window) // { // noise_intensity += peak.getIntensity(); // // std::cout << peak.getMZ() << " | "; // } // // std::cout << std::endl; double rel_sig(0); if (target_intensity > 0.0) { rel_sig = target_intensity / total_intensity; } double noise_intensity = total_intensity - target_intensity; score.total_intensity = total_intensity; score.target_intensity = target_intensity; score.residual_intensity = noise_intensity; score.signal_proportion = rel_sig; score.target_peak_count = target_peak_count; score.residual_peak_count = isolated_window.size(); return score; } PrecursorPurity::PurityScores PrecursorPurity::combinePrecursorPurities(const PrecursorPurity::PurityScores& score1, const PrecursorPurity::PurityScores& score2) { PrecursorPurity::PurityScores score; score.total_intensity = score1.total_intensity + score2.total_intensity; score.target_intensity = score1.target_intensity + score2.target_intensity; score.residual_intensity = score1.residual_intensity + score2.residual_intensity; if (score.target_intensity > 0.0) // otherwise default value of 0 is used { score.signal_proportion = score.target_intensity / score.total_intensity; } score.target_peak_count = score1.target_peak_count + score2.target_peak_count; score.residual_peak_count = score1.residual_peak_count + score2.residual_peak_count; return score; } std::vector<PrecursorPurity::PurityScores> PrecursorPurity::computePrecursorPurities(const PeakMap& spectra, double precursor_mass_tolerance, bool precursor_mass_tolerance_unit_ppm) { std::vector<PrecursorPurity::PurityScores> purityscores; // TODO throw an exception or at least a warning? // if there is no MS1 before the first MS2, the spectra datastructure is not suitable for this function if (spectra[0].getMSLevel() == 2) { LOG_WARN << "Warning: Input data not suitable for Precursor Purity computation. Will be skipped!\n"; return purityscores; } // keep the index of the two MS1 spectra flanking the current group of MS2 spectra Size current_parent_index = 0; Size next_parent_index = 0; bool lastMS1(false); for (Size i = 0; i < spectra.size(); ++i) { // change current parent index if a new MS1 spectrum is reached if (spectra[i].getMSLevel() == 1) { current_parent_index = i; } else if (spectra[i].getMSLevel() == 2) { // update next MS1 index, if it is lower than the current MS2 index if (next_parent_index < i) { for (Size j = i+1; j < spectra.size(); ++j) { if (spectra[j].getMSLevel() == 1) { next_parent_index = j; break; } } // if the next MS1 index was not updated, // the end of the PeakMap was reached right after this current group of MS2 spectra if (next_parent_index < i) { lastMS1 = true; } } // std::cout << "MS1 Spectrum: " << spectra[current_parent_index].getNativeID() << " | MS2 : " << spectra[i].getNativeID() << std::endl; PrecursorPurity::PurityScores score1 = PrecursorPurity::computePrecursorPurity(spectra[current_parent_index], spectra[i].getPrecursors()[0], precursor_mass_tolerance, precursor_mass_tolerance_unit_ppm); // use default values of 0, if there is an MS2 spectrum without an MS1 after it (may happen for the last group of MS2 spectra) PrecursorPurity::PurityScores score2; if (!lastMS1) // there is an MS1 after this MS2 { score2 = PrecursorPurity::computePrecursorPurity(spectra[next_parent_index], spectra[i].getPrecursors()[0], precursor_mass_tolerance, precursor_mass_tolerance_unit_ppm); } PrecursorPurity::PurityScores score = PrecursorPurity::combinePrecursorPurities(score1, score2); purityscores.push_back(score); // std::cout << "Score1 | Spectrum: " << i << " | total intensity: " << score1.total_intensity << " | target intensity: " << score1.target_intensity << " | noise intensity: " << score1.residual_intensity << " | rel_sig: " << score1.signal_proportion << std::endl; // std::cout << "Score2 | Spectrum: " << i << " | total intensity: " << score2.total_intensity << " | target intensity: " << score2.target_intensity << " | noise intensity: " << score2.residual_intensity << " | rel_sig: " << score2.signal_proportion << std::endl; // std::cout << "Combin | Spectrum: " << i << " | total intensity: " << score.total_intensity << " | target intensity: " << score.target_intensity << " | noise intensity: " << score.residual_intensity << " | rel_sig: " << score.signal_proportion << std::endl; // std::cout << "#################################################################################################################" << std::endl; } // end of MS2 spectrum } // spectra loop return purityscores; } // end of function def }
10,727
3,502
/* * Copyright (c) 2015 - 2022, Intel Corporation * SPDX-License-Identifier: BSD-3-Clause */ #ifndef ENVIRONMENT_HPP_INCLUDE #define ENVIRONMENT_HPP_INCLUDE #include <string> #include <vector> #include <utility> #include <map> #include <set> #include <memory> namespace geopm { /// @brief Environment class encapsulates all functionality related to /// dealing with runtime environment variables. class Environment { public: /// @brief Enum for controller launch methods /// /// The return value from pmpi_ctl() is one of these. enum m_ctl_e { M_CTL_NONE, M_CTL_PROCESS, M_CTL_PTHREAD, }; Environment() = default; virtual ~Environment() = default; virtual std::string report(void) const = 0; virtual std::string comm(void) const = 0; virtual std::string policy(void) const = 0; virtual std::string endpoint(void) const = 0; virtual std::string shmkey(void) const = 0; virtual std::string trace(void) const = 0; virtual std::string trace_profile(void) const = 0; virtual std::string trace_endpoint_policy(void) const = 0; virtual std::string profile(void) const = 0; virtual std::string frequency_map(void) const = 0; virtual std::string agent(void) const = 0; virtual std::vector<std::pair<std::string, int> > trace_signals(void) const = 0; virtual std::vector<std::pair<std::string, int> > report_signals(void) const = 0; virtual int max_fan_out(void) const = 0; virtual int pmpi_ctl(void) const = 0; virtual bool do_policy(void) const = 0; virtual bool do_endpoint(void) const = 0; virtual bool do_trace(void) const = 0; virtual bool do_trace_profile(void) const = 0; virtual bool do_trace_endpoint_policy(void) const = 0; virtual bool do_profile(void) const = 0; virtual int timeout(void) const = 0; virtual bool do_ompt(void) const = 0; virtual std::string default_config_path(void) const = 0; virtual std::string override_config_path(void) const = 0; virtual std::string record_filter(void) const = 0; virtual bool do_record_filter(void) const = 0; virtual bool do_debug_attach_all(void) const = 0; virtual bool do_debug_attach_one(void) const = 0; virtual int debug_attach_process(void) const = 0; static std::map<std::string, std::string> parse_environment_file(const std::string &env_file_path); }; class PlatformIO; class EnvironmentImp : public Environment { public: EnvironmentImp(); EnvironmentImp(const std::string &default_settings_path, const std::string &override_settings_path, const PlatformIO *platform_io); virtual ~EnvironmentImp() = default; std::string report(void) const override; std::string comm(void) const override; std::string policy(void) const override; std::string endpoint(void) const override; std::string shmkey(void) const override; std::string trace(void) const override; std::string trace_profile(void) const override; std::string trace_endpoint_policy(void) const override; std::string profile(void) const override; std::string frequency_map(void) const override; std::string agent(void) const override; std::vector<std::pair<std::string, int> > trace_signals(void) const override; std::vector<std::pair<std::string, int> > report_signals(void) const override; std::vector<std::pair<std::string, int> > signal_parser(std::string environment_variable_contents) const; int max_fan_out(void) const override; int pmpi_ctl(void) const override; bool do_policy(void) const override; bool do_endpoint(void) const override; bool do_trace(void) const override; bool do_trace_profile(void) const override; bool do_trace_endpoint_policy(void) const override; bool do_profile() const override; int timeout(void) const override; static std::set<std::string> get_all_vars(void); bool do_ompt(void) const override; std::string default_config_path(void) const override; std::string override_config_path(void) const override; static void parse_environment_file(const std::string &settings_path, const std::set<std::string> &all_names, const std::set<std::string> &user_defined_names, std::map<std::string, std::string> &name_value_map); std::string record_filter(void) const override; bool do_record_filter(void) const override; bool do_debug_attach_all(void) const override; bool do_debug_attach_one(void) const override; int debug_attach_process(void) const override; protected: void parse_environment(void); bool is_set(const std::string &env_var) const; std::string lookup(const std::string &env_var) const; const std::set<std::string> m_all_names; const std::set<std::string> m_runtime_names; std::set<std::string> m_user_defined_names; std::map<std::string, std::string> m_name_value_map; const std::string m_default_config_path; const std::string m_override_config_path; // Pointer used here to avoid calling the singleton too // early as the Environment is used in the top of // geopm_pmpi_init(). Do *NOT* delete this pointer. mutable const PlatformIO *m_platform_io; }; const Environment &environment(void); } #endif
6,211
1,680
// ================================================================================================= // This file is part of the CLBlast project. The project is licensed under Apache Version 2.0. This // project loosely follows the Google C++ styleguide and uses a tab-size of two spaces and a max- // width of 100 characters per line. // // Author(s): // Cedric Nugteren <www.cedricnugteren.nl> // // This file contains the a simple pre-processor for the OpenCL kernels. This pre-processor is used // in cases where the vendor's OpenCL compiler falls short in loop unrolling and array-to-register // promotion. This pre-processor is specific for the CLBlast code making many assumptions. // // ================================================================================================= #ifndef CLBLAST_KERNEL_PREPROCESSOR_H_ #define CLBLAST_KERNEL_PREPROCESSOR_H_ #include <string> #include "utilities/utilities.hpp" namespace clblast { // ================================================================================================= std::string PreprocessKernelSource(const std::string& kernel_source); // ================================================================================================= } // namespace clblast // CLBLAST_KERNEL_PREPROCESSOR_H_ #endif
1,290
336
#pragma once #include <stdint.h> #include <memory> #include <string> #include "ServerState.hh" #include "Lobby.hh" #include "Client.hh" void process_chat_command(std::shared_ptr<ServerState> s, std::shared_ptr<Lobby> l, std::shared_ptr<Client> c, const std::u16string& text);
297
115
//////////////////////////////////////////////////////////////////////////////// // // (C) 2020, Jason Curl // //////////////////////////////////////////////////////////////////////////////// // // Header: getcurrentprocessornumber.cpp // // Description: // Entry points to the Windows DLL. // //////////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "kernelfunc.h" #include "cpuidx.h" typedef DWORD (WINAPI *fnGetCurrentProcessorNumber)(); static int cGetCurrentProcessorNumber = 0; static fnGetCurrentProcessorNumber pGetCurrentProcessorNumber; int id_GetCurrentProcessorNumber() { if (!cGetCurrentProcessorNumber) { HMODULE kernel = GetModuleHandle(TEXT("kernel32.dll")); if (kernel == NULL) { SetLastError(ERROR_INVALID_FUNCTION); return -1; } pGetCurrentProcessorNumber = (fnGetCurrentProcessorNumber)GetProcAddress(kernel, "GetCurrentProcessorNumber"); cGetCurrentProcessorNumber = 1; } if (pGetCurrentProcessorNumber) { return pGetCurrentProcessorNumber(); } else { // Windows XP doesn't offer this function. Some examples use the APICID of the CPUID // instruction, but this is wrong, the APICID isn't necessarily a one-to-one mapping. // The APIC IDs could be 0, 2, 4 for CPU's 0, 1, 2. We can't second guess how the OS // scheduler is configured. // Until we find a better solution, just say we're always on the primary processor. return 0; } }
1,454
437
// // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited // Copyright (c) 2014-2017 Francois Beaune, The appleseedhq Organization // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // Interface header. #include "progressiveframerenderer.h" // appleseed.renderer headers. #include "renderer/global/globallogger.h" #include "renderer/kernel/rendering/iframerenderer.h" #include "renderer/kernel/rendering/isamplegenerator.h" #include "renderer/kernel/rendering/itilecallback.h" #include "renderer/kernel/rendering/progressive/samplecounter.h" #include "renderer/kernel/rendering/progressive/samplecounthistory.h" #include "renderer/kernel/rendering/progressive/samplegeneratorjob.h" #include "renderer/kernel/rendering/sampleaccumulationbuffer.h" #include "renderer/modeling/frame/frame.h" #include "renderer/modeling/project/project.h" #include "renderer/utility/settingsparsing.h" // appleseed.foundation headers. #include "foundation/core/concepts/noncopyable.h" #include "foundation/image/analysis.h" #include "foundation/image/canvasproperties.h" #include "foundation/image/genericimagefilereader.h" #include "foundation/image/image.h" #include "foundation/math/aabb.h" #include "foundation/math/scalar.h" #include "foundation/math/vector.h" #include "foundation/platform/defaulttimers.h" #include "foundation/platform/thread.h" #include "foundation/platform/timers.h" #include "foundation/platform/types.h" #include "foundation/utility/api/apistring.h" #include "foundation/utility/containers/dictionary.h" #include "foundation/utility/foreach.h" #include "foundation/utility/gnuplotfile.h" #include "foundation/utility/job.h" #include "foundation/utility/searchpaths.h" #include "foundation/utility/statistics.h" #include "foundation/utility/stopwatch.h" #include "foundation/utility/string.h" // Boost headers. #include "boost/filesystem.hpp" // Standard headers. #include <cassert> #include <cmath> #include <cstddef> #include <limits> #include <memory> #include <string> #include <vector> using namespace foundation; using namespace std; namespace bf = boost::filesystem; namespace renderer { namespace { // // Progressive frame renderer. // //#define PRINT_DISPLAY_THREAD_PERFS class ProgressiveFrameRenderer : public IFrameRenderer { public: ProgressiveFrameRenderer( const Project& project, ISampleGeneratorFactory* generator_factory, ITileCallbackFactory* callback_factory, const ParamArray& params) : m_project(project) , m_params(params) , m_sample_counter(m_params.m_max_sample_count) , m_ref_image_avg_lum(0.0) { // We must have a generator factory, but it's OK not to have a callback factory. assert(generator_factory); // Create an accumulation buffer. m_buffer.reset(generator_factory->create_sample_accumulation_buffer()); // Create and initialize the job manager. m_job_manager.reset( new JobManager( global_logger(), m_job_queue, m_params.m_thread_count, JobManager::KeepRunningOnEmptyQueue)); // Instantiate sample generators, one per rendering thread. m_sample_generators.reserve(m_params.m_thread_count); for (size_t i = 0; i < m_params.m_thread_count; ++i) { m_sample_generators.push_back( generator_factory->create(i, m_params.m_thread_count)); } // Create rendering jobs, one per rendering thread. m_sample_generator_jobs.reserve(m_params.m_thread_count); for (size_t i = 0; i < m_params.m_thread_count; ++i) { m_sample_generator_jobs.push_back( new SampleGeneratorJob( *m_buffer.get(), m_sample_generators[i], m_sample_counter, m_params.m_spectrum_mode, m_job_queue, i, // job index m_params.m_thread_count, // job count m_abort_switch)); } // Instantiate a single tile callback. if (callback_factory) m_tile_callback.reset(callback_factory->create()); // Load the reference image if one is specified. if (!m_params.m_ref_image_path.empty()) { const string ref_image_path = to_string(project.search_paths().qualify(m_params.m_ref_image_path)); RENDERER_LOG_DEBUG("loading reference image %s...", ref_image_path.c_str()); GenericImageFileReader reader; m_ref_image.reset(reader.read(ref_image_path.c_str())); if (are_images_compatible(m_project.get_frame()->image(), *m_ref_image)) { m_ref_image_avg_lum = compute_average_luminance(*m_ref_image.get()); RENDERER_LOG_DEBUG( "reference image average luminance is %s.", pretty_scalar(m_ref_image_avg_lum, 6).c_str()); } else { RENDERER_LOG_ERROR( "the reference image is not compatible with the output frame " "(different dimensions, tile size or number of channels)."); m_ref_image.reset(); } } RENDERER_LOG_INFO( "rendering settings:\n" " spectrum mode %s\n" " sampling mode %s\n" " threads %s", get_spectrum_mode_name(get_spectrum_mode(params)).c_str(), get_sampling_context_mode_name(get_sampling_context_mode(params)).c_str(), pretty_int(m_params.m_thread_count).c_str()); } ~ProgressiveFrameRenderer() override { // Stop the statistics thread. m_abort_switch.abort(); if (m_statistics_thread.get() && m_statistics_thread->joinable()) m_statistics_thread->join(); // Stop the display thread. m_display_thread_abort_switch.abort(); if (m_display_thread.get() && m_display_thread->joinable()) m_display_thread->join(); // Delete the tile callback. m_tile_callback.reset(); // Delete rendering jobs. for (const_each<SampleGeneratorJobVector> i = m_sample_generator_jobs; i; ++i) delete *i; // Delete sample generators. for (const_each<SampleGeneratorVector> i = m_sample_generators; i; ++i) (*i)->release(); } void release() override { delete this; } void render() override { start_rendering(); m_job_queue.wait_until_completion(); } bool is_rendering() const override { return m_job_queue.has_scheduled_or_running_jobs(); } void start_rendering() override { assert(!is_rendering()); assert(!m_job_queue.has_scheduled_or_running_jobs()); m_abort_switch.clear(); m_buffer->clear(); m_sample_counter.clear(); // Reset sample generators. for (size_t i = 0, e = m_sample_generators.size(); i < e; ++i) m_sample_generators[i]->reset(); // Schedule rendering jobs. for (size_t i = 0, e = m_sample_generator_jobs.size(); i < e; ++i) { m_job_queue.schedule( m_sample_generator_jobs[i], false); // don't transfer ownership of the job to the queue } // Start job execution. m_job_manager->start(); // Create and start the statistics thread. m_statistics_func.reset( new StatisticsFunc( m_project, *m_buffer.get(), m_params.m_perf_stats, m_params.m_luminance_stats, m_ref_image.get(), m_ref_image_avg_lum, m_abort_switch)); m_statistics_thread.reset( new boost::thread( ThreadFunctionWrapper<StatisticsFunc>(m_statistics_func.get()))); // Create and start the display thread. if (m_tile_callback.get() != nullptr && m_display_thread.get() == nullptr) { m_display_func.reset( new DisplayFunc( *m_project.get_frame(), *m_buffer.get(), m_tile_callback.get(), m_params.m_max_sample_count, m_params.m_max_fps, m_display_thread_abort_switch)); m_display_thread.reset( new boost::thread( ThreadFunctionWrapper<DisplayFunc>(m_display_func.get()))); } // Resume rendering if it was paused. resume_rendering(); } void stop_rendering() override { // First, delete scheduled jobs to prevent worker threads from picking them up. m_job_queue.clear_scheduled_jobs(); // Tell rendering jobs and the statistics thread to stop. m_abort_switch.abort(); // Wait until rendering jobs have effectively stopped. m_job_queue.wait_until_completion(); // Wait until the statistics thread has stopped. m_statistics_thread->join(); } void pause_rendering() override { m_job_manager->pause(); if (m_display_func.get()) m_display_func->pause(); m_statistics_func->pause(); } void resume_rendering() override { m_statistics_func->resume(); if (m_display_func.get()) m_display_func->resume(); m_job_manager->resume(); } void terminate_rendering() override { // Completely stop rendering. stop_rendering(); m_job_manager->stop(); // The statistics thread has already been joined in stop_rendering(). m_statistics_thread.reset(); m_statistics_func.reset(); // Join and delete the display thread. if (m_display_thread.get()) { m_display_thread_abort_switch.abort(); m_display_thread->join(); m_display_thread.reset(); } // Make sure the remaining calls of this method don't get interrupted. m_abort_switch.clear(); m_display_thread_abort_switch.clear(); if (m_display_func.get()) { // Merge the last samples and display the final frame. m_display_func->develop_and_display(); m_display_func.reset(); } else { // Just merge the last samples into the frame. m_buffer->develop_to_frame(*m_project.get_frame(), m_abort_switch); } // Merge and print sample generator statistics. print_sample_generators_stats(); } private: // // Progressive frame renderer parameters. // struct Parameters { const Spectrum::Mode m_spectrum_mode; const size_t m_thread_count; // number of rendering threads const uint64 m_max_sample_count; // maximum total number of samples to compute const double m_max_fps; // maximum display frequency in frames/second const bool m_perf_stats; // collect and print performance statistics? const bool m_luminance_stats; // collect and print luminance statistics? const string m_ref_image_path; // path to the reference image explicit Parameters(const ParamArray& params) : m_spectrum_mode(get_spectrum_mode(params)) , m_thread_count(get_rendering_thread_count(params)) , m_max_sample_count(params.get_optional<uint64>("max_samples", numeric_limits<uint64>::max())) , m_max_fps(params.get_optional<double>("max_fps", 30.0)) , m_perf_stats(params.get_optional<bool>("performance_statistics", false)) , m_luminance_stats(params.get_optional<bool>("luminance_statistics", false)) , m_ref_image_path(params.get_optional<string>("reference_image", "")) { } }; // // Frame display thread. // class DisplayFunc : public NonCopyable { public: DisplayFunc( Frame& frame, SampleAccumulationBuffer& buffer, ITileCallback* tile_callback, const uint64 max_sample_count, const double max_fps, IAbortSwitch& abort_switch) : m_frame(frame) , m_buffer(buffer) , m_tile_callback(tile_callback) , m_min_sample_count(min<uint64>(max_sample_count, 32 * 32 * 2)) , m_target_elapsed(1.0 / max_fps) , m_abort_switch(abort_switch) { } void pause() { m_pause_flag.set(); } void resume() { m_pause_flag.clear(); } void operator()() { set_current_thread_name("display"); DefaultWallclockTimer timer; const double rcp_timer_freq = 1.0 / timer.frequency(); uint64 last_time = timer.read(); #ifdef PRINT_DISPLAY_THREAD_PERFS m_stopwatch.start(); #endif while (!m_abort_switch.is_aborted()) { if (m_pause_flag.is_clear()) { // It's time to display but the sample accumulation buffer doesn't contain // enough samples yet. Giving up would lead to noticeable jerkiness, so we // wait until enough samples are available. while (!m_abort_switch.is_aborted() && m_buffer.get_sample_count() < m_min_sample_count) yield(); // Merge the samples and display the final frame. develop_and_display(); } // Compute time elapsed since last call to display(). const uint64 time = timer.read(); const double elapsed = (time - last_time) * rcp_timer_freq; last_time = time; // Limit display rate. if (elapsed < m_target_elapsed) { const double ms = ceil(1000.0 * (m_target_elapsed - elapsed)); sleep(truncate<uint32>(ms), m_abort_switch); } } } void develop_and_display() { #ifdef PRINT_DISPLAY_THREAD_PERFS m_stopwatch.measure(); const double t1 = m_stopwatch.get_seconds(); #endif // Develop the accumulation buffer to the frame. m_buffer.develop_to_frame(m_frame, m_abort_switch); #ifdef PRINT_DISPLAY_THREAD_PERFS m_stopwatch.measure(); const double t2 = m_stopwatch.get_seconds(); #endif // Make sure we don't present incomplete frames. if (m_abort_switch.is_aborted()) return; // Present the frame. m_tile_callback->on_progressive_frame_end(&m_frame); #ifdef PRINT_DISPLAY_THREAD_PERFS m_stopwatch.measure(); const double t3 = m_stopwatch.get_seconds(); RENDERER_LOG_DEBUG( "display thread:\n" " buffer to frame %s\n" " frame to widget %s\n" " total %s (%s fps)", pretty_time(t2 - t1).c_str(), pretty_time(t3 - t2).c_str(), pretty_time(t3 - t1).c_str(), pretty_ratio(1.0, t3 - t1).c_str()); #endif } private: Frame& m_frame; SampleAccumulationBuffer& m_buffer; ITileCallback* m_tile_callback; const uint64 m_min_sample_count; const double m_target_elapsed; IAbortSwitch& m_abort_switch; ThreadFlag m_pause_flag; Stopwatch<DefaultWallclockTimer> m_stopwatch; }; // // Statistics gathering and printing thread. // class StatisticsFunc : public NonCopyable { public: StatisticsFunc( const Project& project, SampleAccumulationBuffer& buffer, const bool perf_stats, const bool luminance_stats, const Image* ref_image, const double ref_image_avg_lum, IAbortSwitch& abort_switch) : m_project(project) , m_buffer(buffer) , m_perf_stats(perf_stats) , m_luminance_stats(luminance_stats) , m_ref_image(ref_image) , m_ref_image_avg_lum(ref_image_avg_lum) , m_abort_switch(abort_switch) , m_rcp_timer_frequency(1.0 / m_timer.frequency()) , m_timer_start_value(m_timer.read()) { const Vector2u crop_window_extent = m_project.get_frame()->get_crop_window().extent(); const size_t pixel_count = (crop_window_extent.x + 1) * (crop_window_extent.y + 1); m_rcp_pixel_count = 1.0 / pixel_count; } ~StatisticsFunc() { if (!m_sample_count_records.empty()) { const string filepath = (bf::path(m_project.search_paths().get_root_path().c_str()) / "sample_count.gnuplot").string(); RENDERER_LOG_DEBUG("writing %s...", filepath.c_str()); GnuplotFile plotfile; plotfile.set_xlabel("Time"); plotfile.set_ylabel("Samples"); plotfile .new_plot() .set_points(m_sample_count_records) .set_title("Total Sample Count Over Time"); plotfile.write(filepath); } if (!m_rmsd_records.empty()) { const string filepath = (bf::path(m_project.search_paths().get_root_path().c_str()) / "rms_deviation.gnuplot").string(); RENDERER_LOG_DEBUG("writing %s...", filepath.c_str()); GnuplotFile plotfile; plotfile.set_xlabel("Samples per Pixel"); plotfile.set_ylabel("RMS Deviation"); plotfile .new_plot() .set_points(m_rmsd_records) .set_title("RMS Deviation Over Time"); plotfile.write(filepath); } } void pause() { m_pause_flag.set(); } void resume() { m_pause_flag.clear(); } void operator()() { set_current_thread_name("statistics"); while (!m_abort_switch.is_aborted()) { if (m_pause_flag.is_clear()) { const double time = (m_timer.read() - m_timer_start_value) * m_rcp_timer_frequency; record_and_print_perf_stats(time); if (m_luminance_stats || m_ref_image) record_and_print_convergence_stats(); } sleep(1000, m_abort_switch); } } private: const Project& m_project; SampleAccumulationBuffer& m_buffer; const bool m_perf_stats; const bool m_luminance_stats; const Image* m_ref_image; const double m_ref_image_avg_lum; IAbortSwitch& m_abort_switch; ThreadFlag m_pause_flag; DefaultWallclockTimer m_timer; double m_rcp_timer_frequency; uint64 m_timer_start_value; double m_rcp_pixel_count; SampleCountHistory<128> m_sample_count_history; vector<Vector2d> m_sample_count_records; // total sample count over time vector<Vector2d> m_rmsd_records; // RMS deviation over time void record_and_print_perf_stats(const double time) { const uint64 samples = m_buffer.get_sample_count(); m_sample_count_history.insert(time, samples); const double samples_per_pixel = samples * m_rcp_pixel_count; const uint64 samples_per_second = truncate<uint64>(m_sample_count_history.get_samples_per_second()); RENDERER_LOG_INFO( "%s samples, %s samples/pixel, %s samples/second", pretty_uint(samples).c_str(), pretty_scalar(samples_per_pixel).c_str(), pretty_uint(samples_per_second).c_str()); if (m_perf_stats) m_sample_count_records.emplace_back(time, static_cast<double>(samples)); } void record_and_print_convergence_stats() { assert(m_luminance_stats || m_ref_image); string output; if (m_luminance_stats) { const double avg_lum = compute_average_luminance(m_project.get_frame()->image()); output += "average luminance " + pretty_scalar(avg_lum, 6); if (m_ref_image) { const double avg_lum_delta = abs(m_ref_image_avg_lum - avg_lum); output += " ("; output += pretty_percent(avg_lum_delta, m_ref_image_avg_lum, 3); output += " error)"; } } if (m_ref_image) { const double samples_per_pixel = m_buffer.get_sample_count() * m_rcp_pixel_count; const double rmsd = compute_rms_deviation(m_project.get_frame()->image(), *m_ref_image); m_rmsd_records.emplace_back(samples_per_pixel, rmsd); if (m_luminance_stats) output += ", "; output += "rms deviation " + pretty_scalar(rmsd, 6); } RENDERER_LOG_DEBUG("%s", output.c_str()); } }; // // Progressive frame renderer implementation details. // const Project& m_project; const Parameters m_params; SampleCounter m_sample_counter; unique_ptr<SampleAccumulationBuffer> m_buffer; JobQueue m_job_queue; unique_ptr<JobManager> m_job_manager; AbortSwitch m_abort_switch; typedef vector<ISampleGenerator*> SampleGeneratorVector; SampleGeneratorVector m_sample_generators; typedef vector<SampleGeneratorJob*> SampleGeneratorJobVector; SampleGeneratorJobVector m_sample_generator_jobs; auto_release_ptr<ITileCallback> m_tile_callback; unique_ptr<Image> m_ref_image; double m_ref_image_avg_lum; unique_ptr<DisplayFunc> m_display_func; unique_ptr<boost::thread> m_display_thread; AbortSwitch m_display_thread_abort_switch; unique_ptr<StatisticsFunc> m_statistics_func; unique_ptr<boost::thread> m_statistics_thread; void print_sample_generators_stats() const { assert(!m_sample_generators.empty()); StatisticsVector stats; for (size_t i = 0; i < m_sample_generators.size(); ++i) stats.merge(m_sample_generators[i]->get_statistics()); RENDERER_LOG_DEBUG("%s", stats.to_string().c_str()); } }; } // // ProgressiveFrameRendererFactory class implementation. // ProgressiveFrameRendererFactory::ProgressiveFrameRendererFactory( const Project& project, ISampleGeneratorFactory* generator_factory, ITileCallbackFactory* callback_factory, const ParamArray& params) : m_project(project) , m_generator_factory(generator_factory) , m_callback_factory(callback_factory) , m_params(params) { } void ProgressiveFrameRendererFactory::release() { delete this; } IFrameRenderer* ProgressiveFrameRendererFactory::create() { return new ProgressiveFrameRenderer( m_project, m_generator_factory, m_callback_factory, m_params); } IFrameRenderer* ProgressiveFrameRendererFactory::create( const Project& project, ISampleGeneratorFactory* generator_factory, ITileCallbackFactory* callback_factory, const ParamArray& params) { return new ProgressiveFrameRenderer( project, generator_factory, callback_factory, params); } Dictionary ProgressiveFrameRendererFactory::get_params_metadata() { Dictionary metadata; metadata.dictionaries().insert( "max_fps", Dictionary() .insert("type", "float") .insert("default", "30.0") .insert("label", "Max FPS") .insert("help", "Maximum progressive rendering update rate in frames per second")); metadata.dictionaries().insert( "max_samples", Dictionary() .insert("type", "int") .insert("label", "Max Samples") .insert("help", "Maximum number of samples per pixel")); return metadata; } } // namespace renderer
29,325
7,986
// // $Id: Matrix.cpp 1539 2009-11-19 20:12:28Z khoff $ // // // Original author: Kate Hoff <katherine.hoff@proteowizard.org> // // Copyright 2009 Center for Applied Molecular Medicine // University of Southern California, Los Angeles, CA // // 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. // /// /// Matrix.cpp /// #include "Matrix.hpp" #include <iostream> using namespace pwiz; using namespace eharmony; Matrix::Matrix(const int& r, const int& c) { _rows = vector<vector<double> >(r, vector<double>(c)); _columns = vector<vector<double> >(c, vector<double>(r)); for(int row_index = 0; row_index != r; ++row_index) { for(int column_index = 0; column_index != c; ++column_index) { _data.insert(make_pair(0,make_pair(row_index,column_index))); } } } void Matrix::insert(const double& value, const int& rowCoordinate, const int& columnCoordinate) { double oldValue = access(rowCoordinate, columnCoordinate); pair<multimap<double, pair<int,int> >::iterator, multimap<double, pair<int,int> >::iterator> candidates = _data.equal_range(oldValue); pair<int, int> coords = make_pair(rowCoordinate, columnCoordinate); multimap<double, pair<int,int> >::iterator it = candidates.first; for(; it != candidates.second; ++it ) if (it->second == coords) _data.erase(it); _rows.at(rowCoordinate).at(columnCoordinate) = value; _columns.at(columnCoordinate).at(rowCoordinate) = value; _data.insert(make_pair(value, make_pair(rowCoordinate, columnCoordinate))); } double Matrix::access(const int& rowCoordinate, const int& columnCoordinate) { return _rows.at(rowCoordinate).at(columnCoordinate); } ostream& Matrix::write(ostream& os) { vector<vector<double> >::const_iterator it = _rows.begin(); for( ; it != _rows.end(); ++it) { vector<double>::const_iterator jt = it->begin(); for( ; jt!= it->end(); ++jt) { os << *jt << " "; } os << endl; } return os; }
2,591
856
/****************************************************************************** Copyright (c) 2018, Alexander W. Winkler. 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 the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ******************************************************************************/ #include <towr/constraints/base_motion_constraint.h> #include <towr/variables/variable_names.h> #include <towr/variables/cartesian_dimensions.h> #include <towr/variables/spline_holder.h> namespace towr { BaseMotionConstraint::BaseMotionConstraint (double T, double dt, const SplineHolder& spline_holder) :TimeDiscretizationConstraint(T, dt, "baseMotion") { base_linear_ = spline_holder.base_linear_; base_angular_ = spline_holder.base_angular_; double dev_rad = 0.05; node_bounds_.resize(k6D); node_bounds_.at(AX) = Bounds(-dev_rad, dev_rad); node_bounds_.at(AY) = Bounds(-dev_rad, dev_rad); node_bounds_.at(AZ) = ifopt::NoBound;//Bounds(-dev_rad, dev_rad); double z_init = base_linear_->GetPoint(0.0).p().z(); node_bounds_.at(LX) = ifopt::NoBound; node_bounds_.at(LY) = ifopt::NoBound;//Bounds(-0.05, 0.05); node_bounds_.at(LZ) = Bounds(z_init-0.02, z_init+0.1); // allow to move dev_z cm up and down int n_constraints_per_node = node_bounds_.size(); SetRows(GetNumberOfNodes()*n_constraints_per_node); } void BaseMotionConstraint::UpdateConstraintAtInstance (double t, int k, VectorXd& g) const { g.middleRows(GetRow(k, LX), k3D) = base_linear_->GetPoint(t).p(); g.middleRows(GetRow(k, AX), k3D) = base_angular_->GetPoint(t).p(); } void BaseMotionConstraint::UpdateBoundsAtInstance (double t, int k, VecBound& bounds) const { for (int dim=0; dim<node_bounds_.size(); ++dim) bounds.at(GetRow(k,dim)) = node_bounds_.at(dim); } void BaseMotionConstraint::UpdateJacobianAtInstance (double t, int k, std::string var_set, Jacobian& jac) const { if (var_set == id::base_ang_nodes) jac.middleRows(GetRow(k,AX), k3D) = base_angular_->GetJacobianWrtNodes(t, kPos); if (var_set == id::base_lin_nodes) jac.middleRows(GetRow(k,LX), k3D) = base_linear_->GetJacobianWrtNodes(t, kPos); } int BaseMotionConstraint::GetRow (int node, int dim) const { return node*node_bounds_.size() + dim; } } /* namespace towr */
3,816
1,321
#include <Windows.h> #include "Includes.h" #include "Menu.h" #include "Keyboard.h" #include "Items.h" #include "Colors.h" #include "EnableDebug.h" #include "Hacks.h" #include "DrawMenu.h" BOOL APIENTRY DllMain(HMODULE hmodule, DWORD ui_reason_for_call, LPVOID lpReserved) { EnableDebugPrivilege(); if (ui_reason_for_call == DLL_PROCESS_ATTACH) { DrawMenu(); } return true; }
402
167
#include "AssignmentExpressionHandler.h" #include "StoreInstruction.h" #include "MathInstruction.h" #include "PopInstruction.h" #include "Assembler.h" namespace Powder { AssignmentExpressionHandler::AssignmentExpressionHandler() { } /*virtual*/ AssignmentExpressionHandler::~AssignmentExpressionHandler() { } /*virtual*/ void AssignmentExpressionHandler::HandleSyntaxNode(const Parser::SyntaxNode* syntaxNode, LinkedList<Instruction*>& instructionList, InstructionGenerator* instructionGenerator) { if (syntaxNode->childList.GetCount() != 3) throw new CompileTimeException("Expected \"assignment-expression\" in AST to have exactly 3 children.", &syntaxNode->fileLocation); // We treat assignment to identifiers (or other things) different than a generic binary expression, because it is not // supported by the math instruction. Rather, it is supported by the store instruction. The math instruction only // operates on concrete values. Yes, we could introduce symbolic variable values as another type of value floating // around in the VM, and have the math instruction store variables when given an assignment operation to perform, or // load concrete values when it encounters a symbolic variable value, but I think that starts to violate a clear separation // of concerns, and furthermore, it makes one instruction (in this case, the math instruction), more complicated than it needs to be. const Parser::SyntaxNode* operationNode = syntaxNode->childList.GetHead()->GetNext()->value; if (*operationNode->name != "=") throw new CompileTimeException("Expected \"assignment-expression\" to have quality child node in AST.", &operationNode->fileLocation); const Parser::SyntaxNode* storeLocationNode = syntaxNode->childList.GetHead()->value; if (*storeLocationNode->name != "identifier" && *storeLocationNode->name != "container-field-expression") throw new CompileTimeException(FormatString("Expected left operand of \"assignment-expression\" in AST to be a storable location (not \"%s\".)", storeLocationNode->name->c_str()), &storeLocationNode->fileLocation); if (*storeLocationNode->name == "identifier") { const Parser::SyntaxNode* storeLocationNameNode = storeLocationNode->childList.GetHead()->value; // Lay down the instructions that will generate the value to be stored on top of the evaluation stack. instructionGenerator->GenerateInstructionListRecursively(instructionList, syntaxNode->childList.GetHead()->GetNext()->GetNext()->value); // Now issue a store instruction. Note that this also pops the value off the stack, which is // symmetrically consistent with its counter-part, the load instruction. StoreInstruction* storeInstruction = Instruction::CreateForAssembly<StoreInstruction>(syntaxNode->fileLocation); AssemblyData::Entry entry; entry.string = *storeLocationNameNode->name; storeInstruction->assemblyData->configMap.Insert("name", entry); instructionList.AddTail(storeInstruction); // TODO: For the case a = b = 1, look at our parent syntax nodes to see if we should issue // a load instruction here for the next store instruction. } else if (*storeLocationNode->name == "container-field-expression") { // First goes the container value. instructionGenerator->GenerateInstructionListRecursively(instructionList, storeLocationNode->childList.GetHead()->value); // Second goes the field value. (Not to be confused with the value that will be stored at the field value in the container value.) instructionGenerator->GenerateInstructionListRecursively(instructionList, storeLocationNode->childList.GetHead()->GetNext()->value); // Third goes the value to be store in the container value at the field value. instructionGenerator->GenerateInstructionListRecursively(instructionList, syntaxNode->childList.GetHead()->GetNext()->GetNext()->value); // Finally, issue a math instruction to insert a value into the container value at the field value. MathInstruction* mathInstruction = Instruction::CreateForAssembly<MathInstruction>(syntaxNode->fileLocation); AssemblyData::Entry entry; entry.code = MathInstruction::MathOp::SET_FIELD; mathInstruction->assemblyData->configMap.Insert("mathOp", entry); instructionList.AddTail(mathInstruction); // Lastly, check out context. If nothing wants the value we leave on the stack-stop, pop it. if (this->PopNeededForExpression(syntaxNode)) { PopInstruction* popInstruction = Instruction::CreateForAssembly<PopInstruction>(syntaxNode->fileLocation); instructionList.AddTail(popInstruction); } } } }
4,627
1,287
#pragma once //------------------------------------------------------------------------------ namespace reporter::resources::different_type_report { //------------------------------------------------------------------------------ extern const char * const Name; extern const char * const Header; extern const char * const UserIncludeLabel; extern const char * const SystemIncludeLabel; extern const char * const FileFmt; extern const char * const DetailFmt; //------------------------------------------------------------------------------ }
548
116
#ifndef INITIALPOSE_NODE_H #define INITIALPOSE_NODE_H #include <initialpose_include.hpp> #include <initialpose_config.hpp> #include <initialpose_estimation.hpp> class initialpose_node { public: initialpose_node(std::string node_name); bool setTransform(std::string laser_topic_name); bool GetStaticMap(); void LaserScanCallback(const sensor_msgs::LaserScanConstPtr msg); void GameStatusCallback(const roborts_msgs::GameStatusPtr msg); public: std::unique_ptr<initialpose_estimation> estimator_ptr_; bool CheckSide_WithLaser_Valid_ = false; double x_lb_; double y_lb_; double alpha_lb_; double cos_alpha_lb_; double sin_alpha_lb_; private: ros::NodeHandle n_; ros::Subscriber LaserScan_sub_; ros::Subscriber GameStatus_sub_; ros::ServiceClient static_map_srv_; std::unique_ptr<tf::TransformListener> tf_listener_ptr_; std::string base_frame_; ros::Publisher initialpose_pub_; bool is_status_valid_; }; #endif
947
349
#include "util/openglhelper.h"
33
16
#include <iostream> #include <TNL/Algorithms/ParallelFor.h> #include <TNL/Matrices/DenseMatrix.h> #include <TNL/Matrices/MatrixWrapping.h> #include <TNL/Devices/Host.h> #include <TNL/Devices/Cuda.h> template< typename Device > void wrapMatrixView() { const int rows( 3 ), columns( 4 ); TNL::Containers::Vector< double, Device > valuesVector { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }; double* values = valuesVector.getData(); /*** * Wrap the array `values` to dense matrix view */ auto matrix = TNL::Matrices::wrapDenseMatrix< Device >( rows, columns, values ); std::cout << "Matrix reads as: " << std::endl << matrix << std::endl; } int main( int argc, char* argv[] ) { std::cout << "Wraping matrix view on host: " << std::endl; wrapMatrixView< TNL::Devices::Host >(); #ifdef HAVE_CUDA std::cout << "Wraping matrix view on CUDA device: " << std::endl; wrapMatrixView< TNL::Devices::Cuda >(); #endif }
967
372
/* * Copyright (C) [2020] Futurewei Technologies, Inc. All rights reverved. * * OpenArkFE is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR * FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "common_header_autogen.h" #include "ruletable_util.h" #include "rec_detect.h" #include "rule_summary.h" namespace maplefe { //////////////////////////////////////////////////////////////////////////////////// // The idea of Rursion Dectect is through a Depth First Traversal in the tree. // There are a few things we need make it clear. // 1) We are looking for back edge when traversing the tree. Those back edges form // the recursions. We differentiate a recursion using the first node, ie, the topmost // node in the tree in this recursion. // 2) Each node (ie rule table) could have multiple recursions. // 3) Recursions could include children recursions inside. // // [NOTE] The key point in recursion detector is to make sure for each loop, there // should be one and only one recursion counted, even if there are multiple // nodes in the loop. // To achieve this, we build the tree, and those back edges of recursion won't // be counted as tree edge. So in DFS traversal, children are done before parents. // If a child is involved in a loop, only the topmost ancestor will be the // leader of this loop. // // This DFS traversal also assures once a node is traversed, all the loops // containing it will be found at this single time. We don't need traverse // this node any more. -- This is the base of our algorithm. //////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////// // RecPath //////////////////////////////////////////////////////////////////////////////////// void RecPath::Dump() { for (unsigned i = 0; i < mPositions.GetNum(); i++) { std::cout << mPositions.ValueAtIndex(i) << ","; } std::cout << std::endl; } std::string RecPath::DumpToString() { std::string s; for (unsigned i = 0; i < mPositions.GetNum(); i++) { std::string num = std::to_string(mPositions.ValueAtIndex(i)); s += num; if (i < mPositions.GetNum() - 1) s += ","; } return s; } //////////////////////////////////////////////////////////////////////////////////// // Recursion //////////////////////////////////////////////////////////////////////////////////// void Recursion::AddRuleTable(RuleTable *rt) { if (!HaveRuleTable(rt)) mRuleTables.PushBack(rt); } void Recursion::Release() { for (unsigned i = 0; i < mPaths.GetNum(); i++) { RecPath *path = mPaths.ValueAtIndex(i); path->Release(); } mPaths.Release(); mRuleTables.Release(); } //////////////////////////////////////////////////////////////////////////////////// // Rule2Recursion //////////////////////////////////////////////////////////////////////////////////// // A rule table could have multiple instance in a recursion if the recursion has // multiple circle and the rule appears in multiple circles. void Rule2Recursion::AddRecursion(Recursion *rec) { for (unsigned i = 0; i < mRecursions.GetNum(); i++) { if (rec == mRecursions.ValueAtIndex(i)) return; } mRecursions.PushBack(rec); } //////////////////////////////////////////////////////////////////////////////////// // RecDetector //////////////////////////////////////////////////////////////////////////////////// void RecDetector::SetupTopTables() { for (unsigned i = 0; i < gTopRulesNum; i++) mToDo.PushBack(gTopRules[i]); } // A talbe is already been processed. bool RecDetector::IsInProcess(RuleTable *t) { for (unsigned i = 0; i < mInProcess.GetNum(); i++) { if (t == mInProcess.ValueAtIndex(i)) return true; } return false; } // A talbe is already done. bool RecDetector::IsDone(RuleTable *t) { for (unsigned i = 0; i < mDone.GetNum(); i++) { if (t == mDone.ValueAtIndex(i)) return true; } return false; } // A talbe is in ToDo bool RecDetector::IsToDo(RuleTable *t) { for (unsigned i = 0; i < mToDo.GetNum(); i++) { if (t == mToDo.ValueAtIndex(i)) return true; } return false; } // Add a rule to the ToDo list, if it's not in any of the following list, // mInProcess, mDone, mToDo. void RecDetector::AddToDo(RuleTable *rule) { if (!IsInProcess(rule) && !IsDone(rule) && !IsToDo(rule)) mToDo.PushBack(rule); } // Add all child rules into ToDo, starting from index 'start'. void RecDetector::AddToDo(RuleTable *rule_table, unsigned start) { for (unsigned i = start; i < rule_table->mNum; i++) { TableData *data = rule_table->mData + i; if (data->mType == DT_Subtable) { RuleTable *child = data->mData.mEntry; AddToDo(child); } } } bool RecDetector::IsMaybeZero(RuleTable *t) { for (unsigned i = 0; i < mMaybeZero.GetNum(); i++) { if (t == mMaybeZero.ValueAtIndex(i)) return true; } return false; } bool RecDetector::IsFail(RuleTable *t) { for (unsigned i = 0; i < mFail.GetNum(); i++) { if (t == mFail.ValueAtIndex(i)) return true; } return false; } Rule2Recursion* RecDetector::FindRule2Recursion(RuleTable *rule) { Rule2Recursion *map = NULL; for (unsigned i = 0; i < mRule2Recursions.GetNum(); i++) { Rule2Recursion *r2r = mRule2Recursions.ValueAtIndex(i); if (rule == r2r->mRule) { map = r2r; break; } } return map; } // Add 'rec' to the Rule2Recursion of 'rule' if not existing. void RecDetector::AddRule2Recursion(RuleTable *rule, Recursion *rec) { Rule2Recursion *map = FindRule2Recursion(rule); if (!map) { map = (Rule2Recursion*)gMemPool.Alloc(sizeof(Rule2Recursion)); new (map) Rule2Recursion(); map->mRule = rule; mRule2Recursions.PushBack(map); } // if the mapping already exists? bool found = false; for (unsigned i = 0; i < map->mRecursions.GetNum(); i++) { Recursion *r = map->mRecursions.ValueAtIndex(i); if (rec == r) { found = true; break; } } if (!found) { map->mRecursions.PushBack(rec); } } // There is a back edge from 'p' to the first appearance of 'rt'. Actually in our // traversal tree, in the current path (from 'p' upward to the root) there is one // and only node representing 'rt', which is the root. The successor of the back // edge is ignored. void RecDetector::AddRecursion(RuleTable *rt, ContTreeNode<RuleTable*> *p) { //std::cout << "Recursion in " << GetRuleTableName(rt) << std::endl; RecPath *path = (RecPath*)gMemPool.Alloc(sizeof(RecPath)); new (path) RecPath(); // Step 1. Traverse upwards to find the target tree node, and add the node // to the node_list. But the first to add is the back edge. ContTreeNode<RuleTable*> *target = NULL; ContTreeNode<RuleTable*> *node = p; SmallVector<RuleTable*> node_list; node_list.PushBack(rt); while (node) { if (node->GetData() == rt) { MASSERT(!target && "duplicated target node in a path."); target = node; break; } else { node_list.PushBack(node->GetData()); } node = node->GetParent(); } MASSERT(node_list.GetNum() > 0); MASSERT(target); MASSERT(target->GetData() == rt); // Step 2. Construct the path from target to 'p'. It's already in node_list, // and we simply read it in reverse order. Also find the index of // of each child rule in the parent rule. RuleTable *parent_rule = rt; for (int i = node_list.GetNum() - 1; i >= 0; i--) { RuleTable *child_rule = node_list.ValueAtIndex(i); unsigned index = 0; bool succ = RuleFindChildIndex(parent_rule, child_rule, index); MASSERT(succ && "Cannot find child rule in parent rule."); path->AddPos(index); parent_rule = child_rule; //std::cout << " child: " << GetRuleTableName(child_rule) << "@" << index << std::endl; } // Step 3. Get the right Recursion, Add the path to the Recursioin. Recursion *rec = FindOrCreateRecursion(rt); rec->AddPath(path); // Step 4. Add the Rule2Recursion mapping for (int i = node_list.GetNum() - 1; i >= 0; i--) { RuleTable *rule = node_list.ValueAtIndex(i); AddRule2Recursion(rule, rec); rec->AddRuleTable(rule); } } // Find the Recursion of 'rule'. // If Not found, create one. Recursion* RecDetector::FindOrCreateRecursion(RuleTable *rule) { for (unsigned i = 0; i < mRecursions.GetNum(); i++) { Recursion *rec = mRecursions.ValueAtIndex(i); if (rec->GetLead() == rule) return rec; } Recursion *rec = (Recursion*)gMemPool.Alloc(sizeof(Recursion)); new (rec) Recursion(); rec->SetLead(rule); mRecursions.PushBack(rec); return rec; } // 'done' is an IsDone node. // If 'p' can be reached from and to the recursion of 'done', add it to them. void RecDetector::HandleIsDoneRuleTable(RuleTable *done, ContTreeNode<RuleTable*> *p) { RuleTable *rule = p->GetData(); Rule2Recursion *map = FindRule2Recursion(done); if (map) { for (unsigned i = 0; i < map->mRecursions.GetNum(); i++) { Recursion *rec = map->mRecursions.ValueAtIndex(i); if (RuleReachable(rec->mLead, rule)) { AddRule2Recursion(rule, rec); rec->AddRuleTable(rule); } } } } TResult RecDetector::DetectRuleTable(RuleTable *rt, ContTreeNode<RuleTable*> *p) { // The children is done with traversal before. This means we need // stop here too, because all the further traversal from this point // have been done already. People may ask, what if I miss a recursion // from this rule table? The answer is you will never miss a single // one. Because any recursion including this rule will be found // the first time it's traversed. (We also addressed this at the // beginning of this file). // This guarantees there is one and only one recursion recorded for a loop // even if the loop has multiple nodes. // However, there is one complication scenario that we need take care. Please // see comments in BackPatch. if (IsDone(rt)) { return TRS_Done; } // If find a new Recursion, create the recursion. It is the successor of the // back edge. As mentioned in the comments in the beginning of this file, back // edge won't be furhter traversed as it is NOT part of the traversal tree. // // The key problem here is what value to return after AddRecursion(). The caller // does request a return value. We decided to return TRS_Fail because this is // the most possible value for a LeadNode of recursion. We actually don't expect // a lead node could be MaybeZero, which means it won't produce epsilon expression. if (IsInProcess(rt)) { AddRecursion(rt, p); return TRS_Fail; } else { mInProcess.PushBack(rt); } // Create new tree node. ContTreeNode<RuleTable*> *node = mTree.NewNode(rt, p); EntryType type = rt->mType; TResult res = TRS_MaybeZero; switch(type) { case ET_Oneof: res = DetectOneof(rt, node); break; case ET_Data: res = DetectData(rt, node); break; case ET_Zeroorone: case ET_Zeroormore: case ET_ASI: res = DetectZeroorXXX(rt, node); break; case ET_Concatenate: res = DetectConcatenate(rt, node); break; case ET_Null: default: MASSERT(0 && "Unexpected EntryType of rule."); break; } // Remove it from InProcess. MASSERT(IsInProcess(rt)); RuleTable *back = mInProcess.Back(); MASSERT(back == rt); mInProcess.PopBack(); // Add it to IsDone // It's clear that a node is push&pop in/off the stack just once, and then // it's set as IsDone. It's traversed only once. MASSERT(!IsDone(rt)); mDone.PushBack(rt); if (res == TRS_Fail) { MASSERT(!IsFail(rt)); mFail.PushBack(rt); } else if (res == TRS_MaybeZero) { MASSERT(!IsMaybeZero(rt)); mMaybeZero.PushBack(rt); } else { // It couldn't be TRS_Done or TRS_NA, since we already // handled TRS_Done in those DetectXXX(). MASSERT(0 && "Unexpected return result."); } return res; } // For Oneof rule, we try to detect for all its children if they are a rule table too. // 1. If there is one or more children are MaybeZero, the parent is MaybeZero // 2. Or the parent is Fail. // // No children will be put in ToDo, since all of them should be traversed. TResult RecDetector::DetectOneof(RuleTable *rule_table, ContTreeNode<RuleTable*> *p) { TResult result = TRS_NA; for (unsigned i = 0; i < rule_table->mNum; i++) { TableData *data = rule_table->mData + i; TResult temp_res = TRS_MaybeZero; RuleTable *child = NULL; if (data->mType == DT_Subtable) { child = data->mData.mEntry; temp_res = DetectRuleTable(child, p); } else { temp_res = TRS_Fail; } if (temp_res == TRS_MaybeZero) { result = TRS_MaybeZero; } else if (temp_res == TRS_Fail) { if (result != TRS_MaybeZero) result = TRS_Fail; } else if (temp_res == TRS_Done) { if (IsMaybeZero(child)) { result = TRS_MaybeZero; } else if (IsFail(child)) { if (result != TRS_MaybeZero) result = TRS_Fail; } else MASSERT(0 && "Unexpected result of done child."); } else MASSERT(0 && "Unexpected temp_res of child"); } return result; } // Zeroormore and Zeroorone and ASI has the same way to handle. TResult RecDetector::DetectZeroorXXX(RuleTable *rule_table, ContTreeNode<RuleTable*> *p) { TResult result = TRS_NA; MASSERT((rule_table->mNum == 1) && "zeroormore node has more than one elements?"); TableData *data = rule_table->mData; // For the non-table data, we just do nothing if (data->mType == DT_Subtable) { RuleTable *child = data->mData.mEntry; result = DetectRuleTable(child, p); } return TRS_MaybeZero; } TResult RecDetector::DetectData(RuleTable *rule_table, ContTreeNode<RuleTable*> *p) { TResult result = TRS_NA; RuleTable *child = NULL; MASSERT((rule_table->mNum == 1) && "Data node has more than one elements?"); TableData *data = rule_table->mData; if (data->mType == DT_Subtable) { child = data->mData.mEntry; result = DetectRuleTable(child, p); } else { result = TRS_Fail; } if (result == TRS_Done) { MASSERT(child); if (IsMaybeZero(child)) { MASSERT(!IsFail(child)); result = TRS_MaybeZero; } else if (IsFail(child)) { MASSERT(!IsMaybeZero(child)); result = TRS_Fail; } else { MASSERT(0 && "Child is not in any categories."); } } return result; } // The real challenge in left recursion detection is coming from Concatenate node. Before // we explain the details, we introduce three sets to keep rule table status. // ToDo : The main driver will walk on this list. Any rules which is encountered // in the traversal but we won't keep on traversing on it, will be put in // this todo list for later traversal. // InProcess: The rules are right now in the middle of traversal. This actually tells // the current working path of the DFS traversal. // Done : The rules that are finished. // The sum of the three sets is the total of rule tables. // And there is no overlapping among the three sets. // // We also elaborate a few rules which build the foundation of the algorithm. // // [Rule 1] // // E ---> '{' + E + '}', // |-> other rules // // It's obvious that E on RHS won't be considered as recursion child, and we can stop // at this point. The and parent rule will give up on it. // // [Rule 2] // // A ---> '{' + E + '}', // |-> other rules // // E on the RHS is not the first element. It won't be traversed at this DFS path. // The traversal stops at this point, and parent node will give up on this path. // But later we will work on it to see if there is recursion. So, E will be put into // ToDo list if it's not in Done or InProcess. // // Question is, what if the first element is not a token? // // [Rule 3] // // A ---> E + '}', // |-> other rules // // E is the first one. It always will go through the following traversal. // // [Rule 4] // // E ---> F + G, // |-> other rules // F ---> ZEROORMORE() // G ---> E + ... // // In this case F is an explicit ZeroorXXX() rule. E and G forms a left recursion. // Let's look at an even more complicated case. // // E ---> F + G, // |-> other rules // F ---> H // H ---> ZEROORMORE() // G ---> E + ... // // In this case F is an IMPLICIT ZeroorXXX() rule table. E and G form a left // recursion too. We cannot put G in ToDo list and give up the path. // Go further there are more complicated case like // // E ---> F + G, // |-> other rules // F ---> H // H ---> ZEROORMORE() + K // K ---> ZERORORMORE() // G ---> E + ... // // H is a ZeroorXXX() or not depends on all grand children's result. // // We introduce a set of TResult to indicate the result of a rule table. This is // corresponding to the three catagories of rule. // TRS_Fail: Definitely a fail for left recursion. Just stop here. // But the rest children could form some new recursions. // TRS_MaybeZero: The rule table could be empty. For a rule table, at the first // time it's traversed, we will save it to mMaybeZero if it's. // TRS_Done: This one is extra return result which doesn't have corresponding // rule catogeries of it. But the rule can be figured out by // checking IsFail() and IsMaybeZero(), because this // rule is done before. // Keep in mind, all TResult of leading elements are only used for determining // if the following element should be traversed, or just stop and put into ToDo list. // At any point when we want to return, we need take the remaining elements // to ToDo list, if they are not in any of InProcess, Done and ToDo. TResult RecDetector::DetectConcatenate(RuleTable *rule_table, ContTreeNode<RuleTable*> *p) { // We use 'res' to record the status of the leading children. TRS_MaybeZero is good // for the beginning as it means it's empty right now. TResult res = TRS_MaybeZero; TableData *data = rule_table->mData; RuleTable *child = NULL; // We accumulate and calculate the status from the beginning of the first child, and // make decision of the rest children accordingly. for (unsigned i = 0; i < rule_table->mNum; i++) { TableData *data = rule_table->mData + i; TResult temp_res = TRS_MaybeZero; child = NULL; if (data->mType == DT_Subtable) { child = data->mData.mEntry; temp_res = DetectRuleTable(child, p); } else { // Whenever we got a non-table child, eg. Token, the following children // won't be counted, and we return TRS_Fail at the end. temp_res = TRS_Fail; } MASSERT((res == TRS_MaybeZero)); if (temp_res == TRS_Fail) { // No matter how many leading children of MaybeZero, the first time // we get a Fail, the whole result is Fail. The rest children // cannot be traversed for these existing ancestors since they cannot // help form a LEFT recursion any more due to this Fail child. // However, we do need add them into ToDo list. res = TRS_Fail; AddToDo(rule_table, i+1); return res; } else if (temp_res == TRS_Done) { MASSERT(child); if (IsFail(child)) { res = TRS_Fail; AddToDo(rule_table, i+1); return res; } } } MASSERT(res == TRS_MaybeZero); return res; } // We start from the top tables. // Iterate until mToDo is empty. void RecDetector::Detect() { mDone.Clear(); SetupTopTables(); while(!mToDo.Empty()) { mInProcess.Clear(); mTree.Clear(); RuleTable *front = mToDo.Front(); mToDo.PopFront(); // It's possible that a rule is put in ToDo multiple times. So it's possible // the first instance IsDone while the second is still in ToDo. So is InProcess. if (!IsDone(front) && !IsInProcess(front)) DetectRuleTable(front, NULL); } // Back Patch // During TraverseRuleTable(), once we see a child IsDone(), we simply return. // This brings an issue that we may miss the opportunity to identify the parent // node as a Recursion Node. // Below is an example. // rule UnannClassType: ONEOF(Identifier + ZEROORONE(TypeArguments), // UnannClassOrInterfaceType + '.' + ...) // rule UnannClassOrInterfaceType: ONEOF(UnannClassType, UnannInterfaceType) // rule UnannInterfaceType : UnannClassType // // These rules form a recursion where there are 2 paths. During recdetect traversal // UnannClassOrInterfaceType is the first to hit and becomes the LeadNode. // The problem is when handling the edge UnannClassOrInterfaceType --> UnannClassType, // we find the first path, and UnannClassType becomes IsDone. Now, we need deal // with UnannClassOrInterfaceType --> UnannInterfaceType, but UnannClassType which // is the child of UnannInterfaceType is IsDone. // Why we do it after DetectRuleTable is completely done? We need the complete // information of IsDone, MaybeZero, Fail, which can be available only after all // DetectRuleTable is done. mChanged = true; while(mChanged) { mChanged = false; mDone.Clear(); mToDo.Clear(); SetupTopTables(); while(!mToDo.Empty()) { RuleTable *front = mToDo.Front(); mToDo.PopFront(); if (!IsDone(front)) { BackPatch(front); mDone.PushBack(front); } } } } // The algorithm is simple, we only check the direct children to see if they are // in some recursion which 'parent' is not in or not in the same group. void RecDetector::BackPatch(RuleTable *parent) { Rule2Recursion *parent_r2r = FindRule2Recursion(parent); Rule2Recursion *child_r2r = NULL; for (unsigned i = 0; i < parent->mNum; i++) { TableData *data = parent->mData + i; if (data->mType == DT_Subtable) { RuleTable *child = data->mData.mEntry; // add child to ToDo list if (!IsDone(child)) mToDo.PushBack(child); child_r2r = FindRule2Recursion(child); if (!child_r2r) continue; // If parent and child share some recursion, we skip bool found = false; for (unsigned j = 0; parent_r2r && (j < parent_r2r->mRecursions.GetNum()); j++) { Recursion *pr = parent_r2r->mRecursions.ValueAtIndex(j); for (unsigned k = 0; k < child_r2r->mRecursions.GetNum(); k++) { Recursion *cr = child_r2r->mRecursions.ValueAtIndex(k); if (cr == pr) { found = true; break; } } if (found) break; } if (found) continue; // Now they are sharing any common recursion, and child has its // exclusive recursions. bool lr_reachable = false; for (unsigned k = 0; k < child_r2r->mRecursions.GetNum(); k++) { Recursion *rec = child_r2r->mRecursions.ValueAtIndex(k); RuleTable *lead = rec->GetLead(); lr_reachable = LRReachable(lead, parent) && LRReachable(parent, child); // Adding parent to one of recursion is good enough. Don't need add // to all appropriate recursions since they will be grouped together // later and parsing is on group unit. if (lr_reachable) { AddRule2Recursion(parent, rec); rec->AddRuleTable(parent); mChanged = true; } } } } } // If there is a path from 'from' to 'to', and it's LeftRecursive reachable which // means 'from' to 'to' could be a left recursion valid path. // // Left Recursive Reachable is the fundamental idea of building recursion group. // We look for recursion group and parse on the groups like waves moving forward. // A non-left-recursive reachable group breaks this moving since it goes the different // tokens. bool RecDetector::LRReachable(RuleTable *from, RuleTable *to) { bool found = false; SmallList<RuleTable*> working_list; SmallVector<RuleTable*> done_list; working_list.PushBack(from); while (!working_list.Empty()) { RuleTable *rt = working_list.Front(); working_list.PopFront(); if (rt == to) { found = true; break; } bool is_done = false; for (unsigned i = 0; i < done_list.GetNum(); i++) { if (rt == done_list.ValueAtIndex(i)) { is_done = true; break; } } if (is_done) continue; EntryType type = rt->mType; switch(type) { case ET_Oneof: { // Add all table children to working list. for (unsigned i = 0; i < rt->mNum; i++) { TableData *data = rt->mData + i; if (data->mType == DT_Subtable) { RuleTable *child = data->mData.mEntry; working_list.PushBack(child); } } break; } case ET_Zeroorone: case ET_Zeroormore: case ET_ASI: case ET_Data: { MASSERT(rt->mNum == 1); TableData *data = rt->mData; if (data->mType == DT_Subtable) { RuleTable *child = data->mData.mEntry; working_list.PushBack(child); } break; } case ET_Concatenate: { for (unsigned i = 0; i < rt->mNum; i++) { TableData *data = rt->mData + i; // If the child is not a rule table, all the rest children // including this one are not left recursive legitimate. if (data->mType != DT_Subtable) break; RuleTable *child = data->mData.mEntry; working_list.PushBack(child); // If 'child' is not MaybeZero, the rest children are // not left recursive legitimate. if (!IsMaybeZero(child)) break; } break; } case ET_Null: default: MASSERT(0 && "Unexpected EntryType of rule."); break; } done_list.PushBack(rt); } return found; } // Return the RecursionGroup if there is one containing 'rec'. RecursionGroup* RecDetector::FindRecursionGroup(Recursion *rec) { RecursionGroup *group = NULL; for (unsigned i = 0; i < mRecursionGroups.GetNum(); i++) { RecursionGroup *rg = mRecursionGroups.ValueAtIndex(i); for (unsigned j = 0; j < rg->mRecursions.GetNum(); j++) { Recursion *r = rg->mRecursions.ValueAtIndex(j); if (rec == r) { group = rg; break; } } if (group) break; } return group; } // We are iterate the recursions in order. It has two level of iterations. // In this algorithm, // 1. The recursion which doesn't belong to any existing group is always // the one to create its group. // 2. All recursions of a group can be identified in just one single // inner iteration. void RecDetector::DetectGroups() { for (unsigned i = 0; i < mRecursions.GetNum(); i++) { Recursion *rec_i = mRecursions.ValueAtIndex(i); RecursionGroup *group_i = FindRecursionGroup(rec_i); // It's already done. if (group_i) continue; group_i = new RecursionGroup(); group_i->AddRecursion(rec_i); mRecursionGroups.PushBack(group_i); for (unsigned j = i + 1; j < mRecursions.GetNum(); j++) { Recursion *rec_j = mRecursions.ValueAtIndex(j); if (LRReachable(rec_i->GetLead(), rec_j->GetLead()) && LRReachable(rec_j->GetLead(), rec_i->GetLead())) { RecursionGroup *group_j = FindRecursionGroup(rec_j); MASSERT(!group_j); group_i->AddRecursion(rec_j); } } } // Build the rule2group for (unsigned i = 0; i < mRecursionGroups.GetNum(); i++) { RecursionGroup *group = mRecursionGroups.ValueAtIndex(i); for (unsigned j = 0; j < group->mRecursions.GetNum(); j++) { Recursion *rec = group->mRecursions.ValueAtIndex(j); for (unsigned k = 0; k < rec->mRuleTables.GetNum(); k++) { RuleTable *rt = rec->mRuleTables.ValueAtIndex(k); // Duplication is checked in AddRule2Group(). AddRule2Group(rt, group); } } } } void RecDetector::AddRule2Group(RuleTable *rt, RecursionGroup *group) { bool found = false; for (unsigned i = 0; i < mRule2Group.GetNum(); i++) { Rule2Group r2g = mRule2Group.ValueAtIndex(i); if ((r2g.mRuleTable == rt) && (r2g.mGroup == group)) { found = true; break; } } if (found) return; Rule2Group r2g = {rt, group}; mRule2Group.PushBack(r2g); } // The reason I have a Release() is to make sure the destructors of Recursion and Paths // are invoked ahead of destructor of gMemPool. void RecDetector::Release() { for (unsigned i = 0; i < mRecursions.GetNum(); i++) { Recursion *rec = mRecursions.ValueAtIndex(i); rec->Release(); } for (unsigned i = 0; i < mRule2Recursions.GetNum(); i++) { Rule2Recursion *map = mRule2Recursions.ValueAtIndex(i); map->Release(); } for (unsigned i = 0; i < mRecursionGroups.GetNum(); i++) { RecursionGroup *rg = mRecursionGroups.ValueAtIndex(i); rg->Release(); } mRule2Recursions.Release(); mRecursions.Release(); mRecursionGroups.Release(); mToDo.Release(); mInProcess.Release(); mDone.Release(); mMaybeZero.Release(); mFail.Release(); mTree.Release(); } // The header file would be java/include/gen_recursion.h. void RecDetector::WriteHeaderFile() { mHeaderFile->WriteOneLine("#ifndef __GEN_RECUR_H__", 23); mHeaderFile->WriteOneLine("#define __GEN_RECUR_H__", 23); mHeaderFile->WriteOneLine("#include \"recursion.h\"", 22); mHeaderFile->WriteOneLine("#endif", 6); } void RecDetector::WriteCppFile() { mCppFile->WriteOneLine("#include \"gen_recursion.h\"", 26); mCppFile->WriteOneLine("#include \"common_header_autogen.h\"", 34); mCppFile->WriteOneLine("namespace maplefe {", 19); //Step 1. Dump paths of a rule table's recursions. // unsigned tablename_path_1[N]={1, 2, ...}; // unsigned tablename_path_2[M]={1, 2, ...}; // unsigned *tablename_path_list[2] = {tablename_path_1, tablename_path_2}; // LeftRecursion tablename_rec = {&Tbltablename, 2, tablename_path_list}; for (unsigned i = 0; i < mRecursions.GetNum(); i++) { Recursion *rec = mRecursions.ValueAtIndex(i); const char *tablename = GetRuleTableName(rec->GetLead()); // dump comment of tablename std::string comment("// "); comment += tablename; mCppFile->WriteOneLine(comment.c_str(), comment.size()); // dump : unsigned tablename_path_1[N]={1, 2, ...}; for (unsigned j = 0; j < rec->PathsNum(); j++) { RecPath *path = rec->GetPath(j); std::string path_str = "unsigned "; path_str += tablename; path_str += "_path_"; std::string index_str = std::to_string(j); path_str += index_str; path_str += "["; // As mentioned in recursion.h, we put the #elem in the first element // tell the users of the array length. std::string num_str = std::to_string(path->PositionsNum()+1); path_str += num_str; path_str += "]= {"; num_str = std::to_string(path->PositionsNum()); path_str += num_str; path_str += ","; std::string path_dump = path->DumpToString(); path_str += path_dump; path_str += "};"; mCppFile->WriteOneLine(path_str.c_str(), path_str.size()); } // to dump // unsigned *tablename_path_list[2] = {tablename_path_1, tablename_path_2}; std::string path_list = "unsigned *"; path_list += tablename; path_list += "_path_list["; std::string num_str = std::to_string(rec->PathsNum()); path_list += num_str; path_list += "]={"; for (unsigned j = 0; j < rec->PathsNum(); j++) { std::string path_str; path_str += tablename; path_str += "_path_"; std::string index_str = std::to_string(j); path_str += index_str; if (j < rec->PathsNum() - 1) path_str += ","; path_list += path_str; } path_list += "};"; mCppFile->WriteOneLine(path_list.c_str(), path_list.size()); // dump // LeftRecursion tablename_rec = {&Tbltablename, 2, tablename_path_list}; std::string rec_str = "LeftRecursion "; rec_str += tablename; rec_str += "_rec = {&"; rec_str += tablename; rec_str += ", "; rec_str += num_str, rec_str += ", "; rec_str += tablename; rec_str += "_path_list};"; mCppFile->WriteOneLine(rec_str.c_str(), rec_str.size()); } // Step 2. Dump num of Recursions mCppFile->WriteOneLine("// Total recursions", 19); std::string s = "unsigned gLeftRecursionsNum="; std::string num = std::to_string(mRecursions.GetNum()); s += num; s += ';'; mCppFile->WriteOneLine(s.c_str(), s.size()); // Step 3. dump all the recursions array, as below // Recusion* TotalRecursions[N] = {&tablename_rec, &tablename_rec, ...}; // Recursion **gLeftRecursions = TotalRecursions; std::string total_str = "LeftRecursion* TotalRecursions["; std::string num_rec = std::to_string(mRecursions.GetNum()); total_str += num_rec; total_str += "] = {"; for (unsigned i = 0; i < mRecursions.GetNum(); i++) { Recursion *rec = mRecursions.ValueAtIndex(i); const char *tablename = GetRuleTableName(rec->GetLead()); total_str += "&"; total_str += tablename; total_str += "_rec"; if (i < mRecursions.GetNum() - 1) total_str += ", "; } total_str += "};"; mCppFile->WriteOneLine(total_str.c_str(), total_str.size()); std::string last_str = "LeftRecursion **gLeftRecursions = TotalRecursions;"; mCppFile->WriteOneLine(last_str.c_str(), last_str.size()); // Step 4. Write RecursionGroups last_str = "///////////////////////////////////////////////////////////////"; mCppFile->WriteOneLine(last_str.c_str(), last_str.size()); last_str = "// RecursionGroup //"; mCppFile->WriteOneLine(last_str.c_str(), last_str.size()); last_str = "///////////////////////////////////////////////////////////////"; mCppFile->WriteOneLine(last_str.c_str(), last_str.size()); WriteRecursionGroups(); // step 5. Write Rule2Recursion mapping. last_str = "///////////////////////////////////////////////////////////////"; mCppFile->WriteOneLine(last_str.c_str(), last_str.size()); last_str = "// Ruel2Recursion //"; mCppFile->WriteOneLine(last_str.c_str(), last_str.size()); last_str = "///////////////////////////////////////////////////////////////"; mCppFile->WriteOneLine(last_str.c_str(), last_str.size()); WriteRule2Recursion(); // step 6. Write Rule2Group mapping. last_str = "///////////////////////////////////////////////////////////////"; mCppFile->WriteOneLine(last_str.c_str(), last_str.size()); last_str = "// Ruel2Group //"; mCppFile->WriteOneLine(last_str.c_str(), last_str.size()); last_str = "///////////////////////////////////////////////////////////////"; mCppFile->WriteOneLine(last_str.c_str(), last_str.size()); WriteRule2Group(); // step 7. Write Group2Rule mapping. last_str = "///////////////////////////////////////////////////////////////"; mCppFile->WriteOneLine(last_str.c_str(), last_str.size()); last_str = "// Group2Rule //"; mCppFile->WriteOneLine(last_str.c_str(), last_str.size()); last_str = "///////////////////////////////////////////////////////////////"; mCppFile->WriteOneLine(last_str.c_str(), last_str.size()); WriteGroup2Rule(); mCppFile->WriteOneLine("}", 1); } // unsigned gRecursionGroupsNum = N; // unsigned group_sizes[N] = {1,2,...}; // unsigned *gRecursionGroupSizes = group_sizes; // LeftRecursion *RecursionGroup_1[1] = {&TblPrimary_rec, ...}; // LeftRecursion *RecursionGroup_2[1] = {&TblPrimary_rec, ...}; // LeftRecursion **recursion_groups[N] = {RecursionGroup_1, RecursionGroup_2...}; // LeftRecursion ***gRecursionGroups = recursion_groups; void RecDetector::WriteRecursionGroups() { // groups num std::string groups_num = "unsigned gRecursionGroupsNum = "; std::string num_str = std::to_string(mRecursionGroups.GetNum()); groups_num += num_str; groups_num += ";"; mCppFile->WriteOneLine(groups_num.c_str(), groups_num.size()); // group sizes std::string group_sizes = "unsigned group_sizes["; group_sizes += num_str; group_sizes += "] = {"; for (unsigned i = 0; i < mRecursionGroups.GetNum(); i++) { RecursionGroup *rg = mRecursionGroups.ValueAtIndex(i); unsigned size = rg->mRecursions.GetNum(); std::string size_str = std::to_string(size); group_sizes += size_str; if (i != (mRecursionGroups.GetNum() - 1)) group_sizes += ","; } group_sizes += "};"; mCppFile->WriteOneLine(group_sizes.c_str(), group_sizes.size()); group_sizes = "unsigned *gRecursionGroupSizes = group_sizes;"; mCppFile->WriteOneLine(group_sizes.c_str(), group_sizes.size()); // LeftRecursion *RecursionGroup_1[1] = {&TblPrimary_rec, ...}; // LeftRecursion *RecursionGroup_2[1] = {&TblPrimary_rec, ...}; for (unsigned i = 0; i < mRecursionGroups.GetNum(); i++) { std::string group = "LeftRecursion *RecursionGroup_"; std::string i_str = std::to_string(i); group += i_str; group += "["; RecursionGroup *rg = mRecursionGroups.ValueAtIndex(i); unsigned size = rg->mRecursions.GetNum(); i_str = std::to_string(size); group += i_str; group += "] = {"; for (unsigned j = 0; j < rg->mRecursions.GetNum(); j++) { Recursion *rec = rg->mRecursions.ValueAtIndex(j); RuleTable *rule_table = rec->GetLead(); const char *name = GetRuleTableName(rule_table); group += "&"; group += name; group += "_rec"; if (j < (rg->mRecursions.GetNum() - 1)) group += ","; } group += "};"; mCppFile->WriteOneLine(group.c_str(), group.size()); } // LeftRecursion **recursion_groups[N] = {RecursionGroup_1, RecursionGroup_2...}; // LeftRecursion ***gRecursionGroups = recursion_groups; std::string final_groups = "LeftRecursion **recursion_groups["; final_groups += num_str; final_groups += "] = {"; for (unsigned i = 0; i < mRecursionGroups.GetNum(); i++) { final_groups += "RecursionGroup_"; std::string i_str = std::to_string(i); final_groups += i_str; if (i < (mRecursionGroups.GetNum() - 1)) final_groups += ","; } final_groups += "};"; mCppFile->WriteOneLine(final_groups.c_str(), final_groups.size()); final_groups = "LeftRecursion ***gRecursionGroups = recursion_groups;"; mCppFile->WriteOneLine(final_groups.c_str(), final_groups.size()); } // We want to dump like below. // unsigned gRule2GroupNum = X; // void RecDetector::WriteRule2Group() { std::string comment = "// Rule2Group mapping"; mCppFile->WriteOneLine(comment.c_str(), comment.size()); std::string groups_num = "unsigned gRule2GroupNum = "; std::string num_str = std::to_string(mRule2Group.GetNum()); groups_num += num_str; groups_num += ";"; mCppFile->WriteOneLine(groups_num.c_str(), groups_num.size()); std::string groups = "int rule2group["; groups += std::to_string(RuleTableNum); groups += "] = {"; for (unsigned rt_idx = 0; rt_idx < RuleTableNum; rt_idx++) { const RuleTable *rt_target = gRuleTableSummarys[rt_idx].mAddr; bool found = false; RecursionGroup *group = NULL; for (unsigned i = 0; i < mRule2Group.GetNum(); i++) { Rule2Group r2g = mRule2Group.ValueAtIndex(i); RuleTable *rt = r2g.mRuleTable; if (rt == rt_target) { found = true; group = r2g.mGroup; break; } } if (found) { // find the index of group. int index = -1; for (unsigned j = 0; j < mRecursionGroups.GetNum(); j++) { if (group == mRecursionGroups.ValueAtIndex(j)) { index = j; break; } } MASSERT(index >= 0); std::string id_str = std::to_string(index); groups += id_str; } else { groups += "-1"; } if (rt_idx < RuleTableNum - 1) groups += ", "; } // The ending groups += "};"; mCppFile->WriteOneLine(groups.c_str(), groups.size()); groups = "int *gRule2Group = rule2group;"; mCppFile->WriteOneLine(groups.c_str(), groups.size()); } // Dump group to rule mapping. // RuleTable* RuleTableArray_1[] = {&TblStatement,...} // RuleTable* RuleTableArray_2[] = {&TblStatement,...} // ... // Group2Rule gGroup2Rule[num of groups] = { // {1, RuleTableArray_1}, // {1, RuleTableArray_2}, // }; void RecDetector::WriteGroup2Rule() { SmallVector<unsigned> group2rule_num; for (unsigned i = 0; i < mRecursionGroups.GetNum(); i++) { std::string array = "RuleTable* RuleTableArray_"; std::string i_str = std::to_string(i); array += i_str; array += "[] = {"; RecursionGroup *target_group = mRecursionGroups.ValueAtIndex(i); unsigned num = 0; for (unsigned r2g_idx = 0; r2g_idx < mRule2Group.GetNum(); r2g_idx++) { Rule2Group r2g = mRule2Group.ValueAtIndex(r2g_idx); RuleTable *rule = r2g.mRuleTable; RecursionGroup *group = r2g.mGroup; if (group == target_group) { num++; const char *tablename = GetRuleTableName(rule); array += "&"; array += tablename; array += ", "; } } MASSERT(num > 0); group2rule_num.PushBack(num); array += "};"; mCppFile->WriteOneLine(array.c_str(), array.size()); } // Group2Rule gGroup2Rule[num of groups] = { std::string group2rule = "Group2Rule ggroup2rule["; std::string g_num_str = std::to_string(mRecursionGroups.GetNum()); group2rule += g_num_str; group2rule += "] = {"; mCppFile->WriteOneLine(group2rule.c_str(), group2rule.size()); for (unsigned i = 0; i < mRecursionGroups.GetNum(); i++) { group2rule = "{"; std::string i_str = std::to_string(i); std::string num_str = std::to_string(group2rule_num.ValueAtIndex(i)); group2rule += num_str; group2rule += ", RuleTableArray_"; group2rule += i_str; group2rule += "},"; mCppFile->WriteOneLine(group2rule.c_str(), group2rule.size()); } group2rule = "};"; mCppFile->WriteOneLine(group2rule.c_str(), group2rule.size()); group2rule = "Group2Rule *gGroup2Rule = ggroup2rule;"; mCppFile->WriteOneLine(group2rule.c_str(), group2rule.size()); } // Dump rule2recursion mapping, as below // LeftRecursion *TblPrimary_r2r_data[2] = {&TblPrimary_rec, &TblBinary_rec}; // Rule2Recursion TblPrimary_r2r = {&TblPrimary, 2, TblPrimary_r2r_data}; // .... // Rule2Recursion *arrayRule2Recursion[yyy] = {&TblPrimary_r2r, &TblTypeOrPackNam_r2r,...} // gRule2RecursionNum = xxx; // Rule2Recursion **gRule2Recursion = arrayRule2Recursion; void RecDetector::WriteRule2Recursion() { std::string comment = "// Rule2Recursion mapping"; mCppFile->WriteOneLine(comment.c_str(), comment.size()); // Step 1. Write each r2r data. for (unsigned i = 0; i < mRule2Recursions.GetNum(); i++) { // Dump: // LeftRecursion *TblPrimary_r2r_data[2] = {&TblPrimary_rec, &TblBinary_rec}; Rule2Recursion *r2r = mRule2Recursions.ValueAtIndex(i); const char *tablename = GetRuleTableName(r2r->mRule); std::string dump = "LeftRecursion *"; dump += tablename; dump += "_r2r_data["; std::string num = std::to_string(r2r->mRecursions.GetNum()); dump += num; dump += "] = {"; // get the list of recursions. std::string lr_str; for (unsigned j = 0; j < r2r->mRecursions.GetNum(); j++) { Recursion *lr = r2r->mRecursions.ValueAtIndex(j); lr_str += "&"; const char *n = GetRuleTableName(lr->GetLead()); lr_str += n; lr_str += "_rec"; if (j < (r2r->mRecursions.GetNum() - 1)) lr_str += ","; } dump += lr_str; dump += "};"; mCppFile->WriteOneLine(dump.c_str(), dump.size()); // Dump: // Rule2Recursion TblPrimary_r2r = {&TblPrimary, 2, TblPrimary_r2r_data}; dump = "Rule2Recursion "; dump += tablename; dump += "_r2r = {&"; dump += tablename; dump += ", "; dump += num; dump += ", "; dump += tablename; dump += "_r2r_data};"; mCppFile->WriteOneLine(dump.c_str(), dump.size()); } // Step 2. Write arryRule2Recursion as below // Rule2Recursion *arrayRule2Recursion[yyy] = {&TblPrimary_r2r, &TblTypeOrPackNam_r2r,...} std::string dump = "Rule2Recursion *arrayRule2Recursion["; std::string num = std::to_string(mRule2Recursions.GetNum()); dump += num; dump += "] = {"; std::string r2r_list; for (unsigned i = 0; i < mRule2Recursions.GetNum(); i++) { // &TblPrimary_rec, &TblBinary_rec, .. Rule2Recursion *r2r = mRule2Recursions.ValueAtIndex(i); const char *tablename = GetRuleTableName(r2r->mRule); r2r_list += "&"; r2r_list += tablename; r2r_list += "_r2r"; if (i < (mRule2Recursions.GetNum() - 1)) r2r_list += ", "; } dump += r2r_list; dump += "};"; mCppFile->WriteOneLine(dump.c_str(), dump.size()); // Step 3. Write gRule2RecursionNum and gRule2Recursion // gRule2RecursionNum = xxx; // Rule2Recursion **gRule2Recursion = arrayRule2Recursion; dump = "unsigned gRule2RecursionNum = "; dump += num; dump += ";"; mCppFile->WriteOneLine(dump.c_str(), dump.size()); dump = "Rule2Recursion **gRule2Recursion = arrayRule2Recursion;"; mCppFile->WriteOneLine(dump.c_str(), dump.size()); } // Write the recursion to java/gen_recursion.h and java/gen_recursion.cpp void RecDetector::Write() { std::string lang_path("../gen/"); std::string file_name = lang_path + "genmore_recursion.cpp"; mCppFile = new Write2File(file_name); file_name = lang_path + "gen_recursion.h"; mHeaderFile = new Write2File(file_name); WriteHeaderFile(); WriteCppFile(); delete mCppFile; delete mHeaderFile; } } int main(int argc, char *argv[]) { maplefe::gMemPool.SetBlockSize(4096); maplefe::RecDetector dtc; dtc.Detect(); dtc.DetectGroups(); dtc.Write(); dtc.Release(); return 0; }
46,314
15,899
#include "wkbreader.hpp" #include <sstream> WKBReader::WKBReader() { _reader = new geos::io::WKBReader(); } WKBReader::WKBReader(const geos::geom::GeometryFactory *gf) { _reader = new geos::io::WKBReader(*gf); } WKBReader::~WKBReader() {} Persistent<Function> WKBReader::constructor; void WKBReader::Initialize(Handle<Object> target) { Isolate* isolate = Isolate::GetCurrent(); HandleScope scope(isolate); Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, WKBReader::New); tpl->InstanceTemplate()->SetInternalFieldCount(1); tpl->SetClassName(String::NewFromUtf8(isolate, "WKBReader")); NODE_SET_PROTOTYPE_METHOD(tpl, "readHEX", WKBReader::ReadHEX); constructor.Reset(isolate, tpl->GetFunction()); target->Set(String::NewFromUtf8(isolate, "WKBReader"), tpl->GetFunction()); } void WKBReader::New(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = Isolate::GetCurrent(); HandleScope scope(isolate); WKBReader *wkbReader; if(args.Length() == 1) { GeometryFactory *factory = ObjectWrap::Unwrap<GeometryFactory>(args[0]->ToObject()); wkbReader = new WKBReader(factory->_factory); } else { wkbReader = new WKBReader(); } wkbReader->Wrap(args.This()); args.GetReturnValue().Set(args.This()); } void WKBReader::ReadHEX(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = Isolate::GetCurrent(); HandleScope scope(isolate); WKBReader* reader = ObjectWrap::Unwrap<WKBReader>(args.This()); String::Utf8Value hex(args[0]->ToString()); std::string str = std::string(*hex); std::istringstream is( str ); try { geos::geom::Geometry* geom = reader->_reader->readHEX(is); args.GetReturnValue().Set(Geometry::New(geom)); } catch (geos::io::ParseException e) { isolate->ThrowException(Exception::Error(String::NewFromUtf8(isolate, e.what()))); } catch (geos::util::GEOSException e) { isolate->ThrowException(Exception::Error(String::NewFromUtf8(isolate, e.what()))); } catch (...) { isolate->ThrowException(Exception::Error(String::NewFromUtf8(isolate, "Exception while reading WKB."))); } }
2,199
743
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. #include "SoundUtilitiesEditorModule.h" #include "CoreMinimal.h" #include "Stats/Stats.h" #include "Modules/ModuleInterface.h" #include "Modules/ModuleManager.h" #include "AssetToolsModule.h" #include "AssetTypeActions_SoundSimple.h" #include "AssetTypeActions_Base.h" #include "AudioEditorModule.h" IMPLEMENT_MODULE(FSoundUtilitiesEditorModule, FSynthesisEditor) void FSoundUtilitiesEditorModule::StartupModule() { SoundWaveAssetActionExtender = TSharedPtr<ISoundWaveAssetActionExtensions>(new FSoundWaveAssetActionExtender()); IAssetTools& AssetTools = FModuleManager::LoadModuleChecked<FAssetToolsModule>("AssetTools").Get(); // Now that we've loaded this module, we need to register our effect preset actions IAudioEditorModule* AudioEditorModule = &FModuleManager::LoadModuleChecked<IAudioEditorModule>("AudioEditor"); AudioEditorModule->AddSoundWaveActionExtender(SoundWaveAssetActionExtender); // Register asset actions AssetTools.RegisterAssetTypeActions(MakeShareable(new FAssetTypeActions_SoundSimple)); } void FSoundUtilitiesEditorModule::ShutdownModule() { }
1,148
356
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: bool isSameTree(TreeNode* p, TreeNode* q) { stack<TreeNode*> s1; stack<TreeNode*> s2; if (p != NULL) s1.push(p); if (q != NULL) s2.push(q); while(!s1.empty() && !s2.empty()) { TreeNode* t1 = s1.top(); TreeNode* t2 = s2.top(); s1.pop(); s2.pop(); if (t1 == NULL && t2 == NULL) continue; if (t1 == NULL || t2 == NULL) return false; if (t1->val != t2->val) return false; s1.push(t1->right); s1.push(t1->left); s2.push(t2->right); s2.push(t2->left); } return s1.empty() && s2.empty(); } }; void trimLeftTrailingSpaces(string &input) { input.erase(input.begin(), find_if(input.begin(), input.end(), [](int ch) { return !isspace(ch); })); } void trimRightTrailingSpaces(string &input) { input.erase(find_if(input.rbegin(), input.rend(), [](int ch) { return !isspace(ch); }).base(), input.end()); } TreeNode* stringToTreeNode(string input) { trimLeftTrailingSpaces(input); trimRightTrailingSpaces(input); input = input.substr(1, input.length() - 2); if (!input.size()) { return nullptr; } string item; stringstream ss; ss.str(input); getline(ss, item, ','); TreeNode* root = new TreeNode(stoi(item)); queue<TreeNode*> nodeQueue; nodeQueue.push(root); while (true) { TreeNode* node = nodeQueue.front(); nodeQueue.pop(); if (!getline(ss, item, ',')) { break; } trimLeftTrailingSpaces(item); if (item != "null") { int leftNumber = stoi(item); node->left = new TreeNode(leftNumber); nodeQueue.push(node->left); } if (!getline(ss, item, ',')) { break; } trimLeftTrailingSpaces(item); if (item != "null") { int rightNumber = stoi(item); node->right = new TreeNode(rightNumber); nodeQueue.push(node->right); } } return root; } string boolToString(bool input) { return input ? "True" : "False"; } int main() { string line; while (getline(cin, line)) { TreeNode* p = stringToTreeNode(line); getline(cin, line); TreeNode* q = stringToTreeNode(line); bool ret = Solution().isSameTree(p, q); string out = boolToString(ret); cout << out << endl; } return 0; }
2,848
937
// Copyright (c) Improbable Worlds Ltd, All Rights Reserved #include "Utils/SpatialDebugger.h" #include "EngineClasses/SpatialNetDriver.h" #include "Interop/SpatialReceiver.h" #include "Interop/SpatialSender.h" #include "Interop/SpatialStaticComponentView.h" #include "LoadBalancing/GridBasedLBStrategy.h" #include "LoadBalancing/LayeredLBStrategy.h" #include "LoadBalancing/WorkerRegion.h" #include "Schema/AuthorityIntent.h" #include "Schema/SpatialDebugging.h" #include "SpatialCommonTypes.h" #include "Utils/InspectionColors.h" #include "Debug/DebugDrawService.h" #include "Engine/Engine.h" #include "GameFramework/Pawn.h" #include "GameFramework/PlayerController.h" #include "GameFramework/PlayerState.h" #include "GenericPlatform/GenericPlatformMath.h" #include "Kismet/GameplayStatics.h" #include "Net/UnrealNetwork.h" using namespace SpatialGDK; DEFINE_LOG_CATEGORY(LogSpatialDebugger); namespace { const FString DEFAULT_WORKER_REGION_MATERIAL = TEXT("/SpatialGDK/SpatialDebugger/Materials/TranslucentWorkerRegion.TranslucentWorkerRegion"); } ASpatialDebugger::ASpatialDebugger(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { PrimaryActorTick.bCanEverTick = true; PrimaryActorTick.bStartWithTickEnabled = true; PrimaryActorTick.TickInterval = 1.f; bAlwaysRelevant = true; bNetLoadOnClient = false; bReplicates = true; NetUpdateFrequency = 1.f; NetDriver = Cast<USpatialNetDriver>(GetNetDriver()); // For GDK design reasons, this is the approach chosen to get a pointer // on the net driver to the client ASpatialDebugger. Various alternatives // were considered and this is the best of a bad bunch. if (NetDriver != nullptr && GetNetMode() == NM_Client) { NetDriver->SetSpatialDebugger(this); } } void ASpatialDebugger::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const { Super::GetLifetimeReplicatedProps(OutLifetimeProps); DOREPLIFETIME_CONDITION(ASpatialDebugger, WorkerRegions, COND_SimulatedOnly); } void ASpatialDebugger::Tick(float DeltaSeconds) { Super::Tick(DeltaSeconds); check(NetDriver != nullptr); if (!NetDriver->IsServer()) { for (TMap<Worker_EntityId_Key, TWeakObjectPtr<AActor>>::TIterator It = EntityActorMapping.CreateIterator(); It; ++It) { if (!It->Value.IsValid()) { It.RemoveCurrent(); } } // Since we have no guarantee on the order we'll receive the PC/Pawn/PlayerState // over the wire, we check here once per tick (currently 1 Hz tick rate) to setup our local pointers. // Note that we can capture the PC in OnEntityAdded() since we know we will only receive one of those. if (LocalPawn.IsValid() == false && LocalPlayerController.IsValid()) { LocalPawn = LocalPlayerController->GetPawn(); } if (LocalPlayerState.IsValid() == false && LocalPawn.IsValid()) { LocalPlayerState = LocalPawn->GetPlayerState(); } if (LocalPawn.IsValid()) { SCOPE_CYCLE_COUNTER(STAT_SortingActors); const FVector& PlayerLocation = LocalPawn->GetActorLocation(); EntityActorMapping.ValueSort([PlayerLocation](const TWeakObjectPtr<AActor>& A, const TWeakObjectPtr<AActor>& B) { return FVector::Dist(PlayerLocation, A->GetActorLocation()) > FVector::Dist(PlayerLocation, B->GetActorLocation()); }); } } } void ASpatialDebugger::BeginPlay() { Super::BeginPlay(); check(NetDriver != nullptr); if (!NetDriver->IsServer()) { EntityActorMapping.Reserve(ENTITY_ACTOR_MAP_RESERVATION_COUNT); LoadIcons(); TArray<Worker_EntityId_Key> EntityIds; NetDriver->StaticComponentView->GetEntityIds(EntityIds); // Capture any entities that are already present on this client (ie they came over the wire before the SpatialDebugger did). for (const Worker_EntityId_Key EntityId : EntityIds) { OnEntityAdded(EntityId); } // Register callbacks to get notified of all future entity arrivals / deletes. OnEntityAddedHandle = NetDriver->Receiver->OnEntityAddedDelegate.AddUObject(this, &ASpatialDebugger::OnEntityAdded); OnEntityRemovedHandle = NetDriver->Receiver->OnEntityRemovedDelegate.AddUObject(this, &ASpatialDebugger::OnEntityRemoved); FontRenderInfo.bClipText = true; FontRenderInfo.bEnableShadow = true; RenderFont = GEngine->GetSmallFont(); if (bAutoStart) { SpatialToggleDebugger(); } } } void ASpatialDebugger::OnAuthorityGained() { if (NetDriver->LoadBalanceStrategy) { const ULayeredLBStrategy* LayeredLBStrategy = Cast<ULayeredLBStrategy>(NetDriver->LoadBalanceStrategy); if (LayeredLBStrategy == nullptr) { UE_LOG(LogSpatialDebugger, Warning, TEXT("SpatialDebugger enabled but unable to get LayeredLBStrategy.")); return; } if (const UGridBasedLBStrategy* GridBasedLBStrategy = Cast<UGridBasedLBStrategy>(LayeredLBStrategy->GetLBStrategyForVisualRendering())) { const UGridBasedLBStrategy::LBStrategyRegions LBStrategyRegions = GridBasedLBStrategy->GetLBStrategyRegions(); WorkerRegions.SetNum(LBStrategyRegions.Num()); for (int i = 0; i < LBStrategyRegions.Num(); i++) { const TPair<VirtualWorkerId, FBox2D>& LBStrategyRegion = LBStrategyRegions[i]; const PhysicalWorkerName* WorkerName = NetDriver->VirtualWorkerTranslator->GetPhysicalWorkerForVirtualWorker(LBStrategyRegion.Key); FWorkerRegionInfo WorkerRegionInfo; WorkerRegionInfo.Color = (WorkerName == nullptr) ? InvalidServerTintColor : SpatialGDK::GetColorForWorkerName(*WorkerName); WorkerRegionInfo.Extents = LBStrategyRegion.Value; WorkerRegions[i] = WorkerRegionInfo; } } } } void ASpatialDebugger::CreateWorkerRegions() { UMaterial* WorkerRegionMaterial = LoadObject<UMaterial>(nullptr, *DEFAULT_WORKER_REGION_MATERIAL); if (WorkerRegionMaterial == nullptr) { UE_LOG(LogSpatialDebugger, Error, TEXT("Worker regions were not rendered. Could not find default material: %s"), *DEFAULT_WORKER_REGION_MATERIAL); return; } // Create new actors for all new worker regions FActorSpawnParameters SpawnParams; SpawnParams.bNoFail = true; SpawnParams.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn; for (const FWorkerRegionInfo& WorkerRegionData : WorkerRegions) { AWorkerRegion* WorkerRegion = GetWorld()->SpawnActor<AWorkerRegion>(SpawnParams); WorkerRegion->Init(WorkerRegionMaterial, WorkerRegionData.Color, WorkerRegionData.Extents, WorkerRegionVerticalScale); WorkerRegion->SetActorEnableCollision(false); } } void ASpatialDebugger::DestroyWorkerRegions() { TArray<AActor*> WorkerRegionsToRemove; UGameplayStatics::GetAllActorsOfClass(this, AWorkerRegion::StaticClass(), WorkerRegionsToRemove); for (AActor* WorkerRegion : WorkerRegionsToRemove) { WorkerRegion->Destroy(); } } void ASpatialDebugger::OnRep_SetWorkerRegions() { if (NetDriver != nullptr && !NetDriver->IsServer() && DrawDebugDelegateHandle.IsValid() && bShowWorkerRegions) { DestroyWorkerRegions(); CreateWorkerRegions(); } } void ASpatialDebugger::Destroyed() { if (NetDriver != nullptr && NetDriver->Receiver != nullptr) { if (OnEntityAddedHandle.IsValid()) { NetDriver->Receiver->OnEntityAddedDelegate.Remove(OnEntityAddedHandle); } if (OnEntityRemovedHandle.IsValid()) { NetDriver->Receiver->OnEntityRemovedDelegate.Remove(OnEntityRemovedHandle); } } if (DrawDebugDelegateHandle.IsValid()) { UDebugDrawService::Unregister(DrawDebugDelegateHandle); DestroyWorkerRegions(); } Super::Destroyed(); } void ASpatialDebugger::LoadIcons() { check(NetDriver != nullptr && !NetDriver->IsServer()); UTexture2D* DefaultTexture = LoadObject<UTexture2D>(nullptr, TEXT("/Engine/EngineResources/DefaultTexture.DefaultTexture")); const float IconWidth = 16.0f; const float IconHeight = 16.0f; Icons[ICON_AUTH] = UCanvas::MakeIcon(AuthTexture != nullptr ? AuthTexture : DefaultTexture, 0.0f, 0.0f, IconWidth, IconHeight); Icons[ICON_AUTH_INTENT] = UCanvas::MakeIcon(AuthIntentTexture != nullptr ? AuthIntentTexture : DefaultTexture, 0.0f, 0.0f, IconWidth, IconHeight); Icons[ICON_UNLOCKED] = UCanvas::MakeIcon(UnlockedTexture != nullptr ? UnlockedTexture : DefaultTexture, 0.0f, 0.0f, IconWidth, IconHeight); Icons[ICON_LOCKED] = UCanvas::MakeIcon(LockedTexture != nullptr ? LockedTexture : DefaultTexture, 0.0f, 0.0f, IconWidth, IconHeight); Icons[ICON_BOX] = UCanvas::MakeIcon(BoxTexture != nullptr ? BoxTexture : DefaultTexture, 0.0f, 0.0f, IconWidth, IconHeight); } void ASpatialDebugger::OnEntityAdded(const Worker_EntityId EntityId) { check(NetDriver != nullptr && !NetDriver->IsServer()); TWeakObjectPtr<AActor>* ExistingActor = EntityActorMapping.Find(EntityId); if (ExistingActor != nullptr) { return; } if (AActor* Actor = Cast<AActor>(NetDriver->PackageMap->GetObjectFromEntityId(EntityId).Get())) { EntityActorMapping.Add(EntityId, Actor); // Each client will only receive a PlayerController once. if (Actor->IsA<APlayerController>()) { LocalPlayerController = Cast<APlayerController>(Actor); } } } void ASpatialDebugger::OnEntityRemoved(const Worker_EntityId EntityId) { check(NetDriver != nullptr && !NetDriver->IsServer()); EntityActorMapping.Remove(EntityId); } void ASpatialDebugger::ActorAuthorityChanged(const Worker_AuthorityChangeOp& AuthOp) const { check(AuthOp.authority == WORKER_AUTHORITY_AUTHORITATIVE && AuthOp.component_id == SpatialConstants::AUTHORITY_INTENT_COMPONENT_ID); if (NetDriver->VirtualWorkerTranslator == nullptr) { // Currently, there's nothing to display in the debugger other than load balancing information. return; } VirtualWorkerId LocalVirtualWorkerId = NetDriver->VirtualWorkerTranslator->GetLocalVirtualWorkerId(); FColor LocalVirtualWorkerColor = SpatialGDK::GetColorForWorkerName(NetDriver->VirtualWorkerTranslator->GetLocalPhysicalWorkerName()); SpatialDebugging* DebuggingInfo = NetDriver->StaticComponentView->GetComponentData<SpatialDebugging>(AuthOp.entity_id); if (DebuggingInfo == nullptr) { // Some entities won't have debug info, so create it now. SpatialDebugging NewDebuggingInfo(LocalVirtualWorkerId, LocalVirtualWorkerColor, SpatialConstants::INVALID_VIRTUAL_WORKER_ID, InvalidServerTintColor, false); NetDriver->Sender->SendAddComponents(AuthOp.entity_id, { NewDebuggingInfo.CreateSpatialDebuggingData() }); return; } DebuggingInfo->AuthoritativeVirtualWorkerId = LocalVirtualWorkerId; DebuggingInfo->AuthoritativeColor = LocalVirtualWorkerColor; FWorkerComponentUpdate DebuggingUpdate = DebuggingInfo->CreateSpatialDebuggingUpdate(); NetDriver->Connection->SendComponentUpdate(AuthOp.entity_id, &DebuggingUpdate); } void ASpatialDebugger::ActorAuthorityIntentChanged(Worker_EntityId EntityId, VirtualWorkerId NewIntentVirtualWorkerId) const { SpatialDebugging* DebuggingInfo = NetDriver->StaticComponentView->GetComponentData<SpatialDebugging>(EntityId); check(DebuggingInfo != nullptr); DebuggingInfo->IntentVirtualWorkerId = NewIntentVirtualWorkerId; const PhysicalWorkerName* NewAuthoritativePhysicalWorkerName = NetDriver->VirtualWorkerTranslator->GetPhysicalWorkerForVirtualWorker(NewIntentVirtualWorkerId); check(NewAuthoritativePhysicalWorkerName != nullptr); DebuggingInfo->IntentColor = SpatialGDK::GetColorForWorkerName(*NewAuthoritativePhysicalWorkerName); FWorkerComponentUpdate DebuggingUpdate = DebuggingInfo->CreateSpatialDebuggingUpdate(); NetDriver->Connection->SendComponentUpdate(EntityId, &DebuggingUpdate); } void ASpatialDebugger::DrawTag(UCanvas* Canvas, const FVector2D& ScreenLocation, const Worker_EntityId EntityId, const FString& ActorName) { SCOPE_CYCLE_COUNTER(STAT_DrawTag); // TODO: Smarter positioning of elements so they're centered no matter how many are enabled https://improbableio.atlassian.net/browse/UNR-2360. int32 HorizontalOffset = -32.0f; check(NetDriver != nullptr && !NetDriver->IsServer()); if (!NetDriver->StaticComponentView->HasComponent(EntityId, SpatialConstants::SPATIAL_DEBUGGING_COMPONENT_ID)) { return; } const SpatialDebugging* DebuggingInfo = NetDriver->StaticComponentView->GetComponentData<SpatialDebugging>(EntityId); static const float BaseHorizontalOffset(16.0f); if (!FApp::CanEverRender()) // DrawIcon can attempt to use the underlying texture resource even when using nullrhi { return; } if (bShowLock) { SCOPE_CYCLE_COUNTER(STAT_DrawIcons); const bool bIsLocked = DebuggingInfo->IsLocked; const EIcon LockIcon = bIsLocked ? ICON_LOCKED : ICON_UNLOCKED; Canvas->SetDrawColor(FColor::White); Canvas->DrawIcon(Icons[LockIcon], ScreenLocation.X + HorizontalOffset, ScreenLocation.Y, 1.0f); HorizontalOffset += BaseHorizontalOffset; } if (bShowAuth) { SCOPE_CYCLE_COUNTER(STAT_DrawIcons); const FColor& ServerWorkerColor = DebuggingInfo->AuthoritativeColor; Canvas->SetDrawColor(FColor::White); Canvas->DrawIcon(Icons[ICON_AUTH], ScreenLocation.X + HorizontalOffset, ScreenLocation.Y, 1.0f); HorizontalOffset += BaseHorizontalOffset; Canvas->SetDrawColor(ServerWorkerColor); const float BoxScaleBasedOnNumberSize = 0.75f * GetNumberOfDigitsIn(DebuggingInfo->AuthoritativeVirtualWorkerId); Canvas->DrawScaledIcon(Icons[ICON_BOX], ScreenLocation.X + HorizontalOffset, ScreenLocation.Y, FVector(BoxScaleBasedOnNumberSize, 1.f, 1.f)); Canvas->SetDrawColor(GetTextColorForBackgroundColor(ServerWorkerColor)); Canvas->DrawText(RenderFont, FString::FromInt(DebuggingInfo->AuthoritativeVirtualWorkerId), ScreenLocation.X + HorizontalOffset + 1, ScreenLocation.Y, 1.1f, 1.1f, FontRenderInfo); HorizontalOffset += (BaseHorizontalOffset * BoxScaleBasedOnNumberSize); } if (bShowAuthIntent) { SCOPE_CYCLE_COUNTER(STAT_DrawIcons); const FColor& VirtualWorkerColor = DebuggingInfo->IntentColor; Canvas->SetDrawColor(FColor::White); Canvas->DrawIcon(Icons[ICON_AUTH_INTENT], ScreenLocation.X + HorizontalOffset, ScreenLocation.Y, 1.0f); HorizontalOffset += 16.0f; Canvas->SetDrawColor(VirtualWorkerColor); const float BoxScaleBasedOnNumberSize = 0.75f * GetNumberOfDigitsIn(DebuggingInfo->IntentVirtualWorkerId); Canvas->DrawScaledIcon(Icons[ICON_BOX], ScreenLocation.X + HorizontalOffset, ScreenLocation.Y, FVector(BoxScaleBasedOnNumberSize, 1.f, 1.f)); Canvas->SetDrawColor(GetTextColorForBackgroundColor(VirtualWorkerColor)); Canvas->DrawText(RenderFont, FString::FromInt(DebuggingInfo->IntentVirtualWorkerId), ScreenLocation.X + HorizontalOffset + 1, ScreenLocation.Y, 1.1f, 1.1f, FontRenderInfo); HorizontalOffset += (BaseHorizontalOffset * BoxScaleBasedOnNumberSize); } FString Label; if (bShowEntityId) { SCOPE_CYCLE_COUNTER(STAT_BuildText); Label += FString::Printf(TEXT("%lld "), EntityId); } if (bShowActorName) { SCOPE_CYCLE_COUNTER(STAT_BuildText); Label += FString::Printf(TEXT("(%s)"), *ActorName); } if (bShowEntityId || bShowActorName) { SCOPE_CYCLE_COUNTER(STAT_DrawText); Canvas->SetDrawColor(FColor::Green); Canvas->DrawText(RenderFont, Label, ScreenLocation.X + HorizontalOffset, ScreenLocation.Y, 1.0f, 1.0f, FontRenderInfo); } } FColor ASpatialDebugger::GetTextColorForBackgroundColor(const FColor& BackgroundColor) const { return BackgroundColor.ReinterpretAsLinear().ComputeLuminance() > 0.5 ? FColor::Black : FColor::White; } // This will break once we have more than 10,000 workers, happily kicking that can down the road. int32 ASpatialDebugger::GetNumberOfDigitsIn(int32 SomeNumber) const { SomeNumber = FMath::Abs(SomeNumber); return (SomeNumber < 10 ? 1 : (SomeNumber < 100 ? 2 : (SomeNumber < 1000 ? 3 : 4))); } void ASpatialDebugger::DrawDebug(UCanvas* Canvas, APlayerController* /* Controller */) // Controller is invalid. { SCOPE_CYCLE_COUNTER(STAT_DrawDebug); check(NetDriver != nullptr && !NetDriver->IsServer()); #if WITH_EDITOR // Prevent one client's data rendering in another client's view in PIE when using UDebugDrawService. Lifted from EQSRenderingComponent. if (Canvas && Canvas->SceneView && Canvas->SceneView->Family && Canvas->SceneView->Family->Scene && Canvas->SceneView->Family->Scene->GetWorld() != GetWorld()) { return; } #endif DrawDebugLocalPlayer(Canvas); FVector PlayerLocation = FVector::ZeroVector; if (LocalPawn.IsValid()) { PlayerLocation = LocalPawn->GetActorLocation(); } for (TPair<Worker_EntityId_Key, TWeakObjectPtr<AActor>>& EntityActorPair : EntityActorMapping) { const TWeakObjectPtr<AActor> Actor = EntityActorPair.Value; const Worker_EntityId EntityId = EntityActorPair.Key; if (Actor != nullptr) { FVector ActorLocation = Actor->GetActorLocation(); if (ActorLocation.IsZero()) { continue; } if (FVector::Dist(PlayerLocation, ActorLocation) > MaxRange) { continue; } FVector2D ScreenLocation = FVector2D::ZeroVector; if (LocalPlayerController.IsValid()) { SCOPE_CYCLE_COUNTER(STAT_Projection); UGameplayStatics::ProjectWorldToScreen(LocalPlayerController.Get(), ActorLocation + WorldSpaceActorTagOffset, ScreenLocation, false); } if (ScreenLocation.IsZero()) { continue; } DrawTag(Canvas, ScreenLocation, EntityId, Actor->GetName()); } } } void ASpatialDebugger::DrawDebugLocalPlayer(UCanvas* Canvas) { if (LocalPawn == nullptr || LocalPlayerController == nullptr || LocalPlayerState == nullptr) { return; } const TArray<TWeakObjectPtr<AActor>> LocalPlayerActors = { LocalPawn, LocalPlayerController, LocalPlayerState }; FVector2D ScreenLocation(PlayerPanelStartX, PlayerPanelStartY); for (int32 i = 0; i < LocalPlayerActors.Num(); ++i) { if (LocalPlayerActors[i].IsValid()) { const Worker_EntityId EntityId = NetDriver->PackageMap->GetEntityIdFromObject(LocalPlayerActors[i].Get()); DrawTag(Canvas, ScreenLocation, EntityId, LocalPlayerActors[i]->GetName()); ScreenLocation.Y -= PLAYER_TAG_VERTICAL_OFFSET; } } } void ASpatialDebugger::SpatialToggleDebugger() { check(NetDriver != nullptr && !NetDriver->IsServer()); if (DrawDebugDelegateHandle.IsValid()) { UDebugDrawService::Unregister(DrawDebugDelegateHandle); DrawDebugDelegateHandle.Reset(); DestroyWorkerRegions(); } else { DrawDebugDelegateHandle = UDebugDrawService::Register(TEXT("Game"), FDebugDrawDelegate::CreateUObject(this, &ASpatialDebugger::DrawDebug)); if (bShowWorkerRegions) { CreateWorkerRegions(); } } }
18,247
6,399
/* * This is a simple example program to demonstrate the usage of the * PPUtils::UniformObjectPool class template. * * Author: Perttu Paarlahti perttu.paarlahti@gmail.com * Created: 29-June-2015 */ #include <iostream> #include <functional> #include "../../source/PPUtils/uniformobjectpool.hh" class VeryComplexClass { static int n; public: VeryComplexClass() { // Very expensive construction std::cout << "Constructing a massively complex object" << std::endl; ++n; } void foo() { std::cout << "Expensive constructor was called " << n << " times\n"; } }; int VeryComplexClass::n = 0; int main() { // Create the object pool PPUtils::UniformObjectPool<VeryComplexClass> pool; std::cout << "Pool contains: " << pool.size() << " objects" << std::endl; std::unique_ptr<VeryComplexClass> obj = pool.reserve(); std::cout << "Pool contains: " << pool.size() << " objects" << std::endl; pool.release( std::move(obj) ); std::cout << "Pool contains: " << pool.size() << " objects" << std::endl; obj = pool.reserve(); std::cout << "Pool contains: " << pool.size() << " objects" << std::endl; obj->foo(); return 0; } /* * Expected output: * * Pool contains 0 objects * Constructing a massively complex object * Pool contains 0 objects * Pool contains 1 objects * Pool contains 0 objects * Expensive constructor was called 1 times * */
1,490
493
#include "rutil/ParseException.hxx" namespace resip { ParseException::ParseException(const Data& msg, const Data& context, const Data& file, const int line) : resip::BaseException(msg, file, line), mContext(context) {} ParseException::~ParseException() throw() {} const char* ParseException::name() const { return "ParseException"; } const Data& ParseException::getContext() const { return mContext; } }
530
152
/******************************************************************************* * Copyright (C) 2017 Advanced Micro Devices, Inc. All rights reserved. *******************************************************************************/ #ifndef GUARD_MIOPENGEMM_DEGEMMAPIQQ_HPP #define GUARD_MIOPENGEMM_DEGEMMAPIQQ_HPP #include <memory> #include <stdlib.h> #include <string> #include <vector> #include <miopengemm/geometry.hpp> #include <miopengemm/oclutil.hpp> #include <miopengemm/solution.hpp> #include <miopengemm/tinyone.hpp> namespace MIOpenGEMM { namespace dev { class TinyTwo { private: std::unique_ptr<TinyOne<double>> d_moa{nullptr}; std::unique_ptr<TinyOne<float>> f_moa{nullptr}; char active_type{'?'}; template <typename TFloat> std::unique_ptr<TinyOne<TFloat>>& get_up_moa() { throw miog_error("unrecognised template parameter TFloat in TinyTwo get_up_moa"); } template <typename TFloat> void set_active_type() { throw miog_error("unrecognised template parameter TFloat in TinyTwo set_active_type"); } public: template <typename TFloat> TinyTwo(Geometry gg_, Offsets toff_, const TFloat* a_, const TFloat* b_, const TFloat* c_, owrite::Writer& mowri_, const CLHint& xhint) { get_up_moa<TFloat>().reset(new TinyOne<TFloat>(gg_, toff_, a_, b_, c_, mowri_, xhint)); set_active_type<TFloat>(); } TinyTwo(Geometry gg_, Offsets toff_, owrite::Writer& mowri_, const CLHint& xhint); std::vector<std::vector<double>> benchgemm(const std::vector<HyPas>& hps, const Halt& hl); Solution find2(const FindParams& find_params, const Constraints& constraints); // template <typename TFloat> // void accuracy_test(const HyPas& hp) //{ // get_up_moa<TFloat>()->accuracy_test(hp); //} void accuracy_test(const HyPas& hp); }; template <> std::unique_ptr<TinyOne<float>>& TinyTwo::get_up_moa<float>(); template <> std::unique_ptr<TinyOne<double>>& TinyTwo::get_up_moa<double>(); template <> void TinyTwo::set_active_type<float>(); template <> void TinyTwo::set_active_type<double>(); } } #endif
2,183
788
/* * Copyright (c) 2020, Andreas Kling <kling@seguebaseos.org> * * SPDX-License-Identifier: BSD-2-Clause */ #include <AK/Badge.h> #include <AK/Function.h> #include <AK/HashMap.h> #include <LibGUI/DisplayLink.h> #include <LibGUI/WindowServerConnection.h> namespace GUI { class DisplayLinkCallback : public RefCounted<DisplayLinkCallback> { public: DisplayLinkCallback(i32 link_id, Function<void(i32)> callback) : m_link_id(link_id) , m_callback(move(callback)) { } void invoke() { m_callback(m_link_id); } private: i32 m_link_id { 0 }; Function<void(i32)> m_callback; }; static HashMap<i32, RefPtr<DisplayLinkCallback>>& callbacks() { static HashMap<i32, RefPtr<DisplayLinkCallback>>* map; if (!map) map = new HashMap<i32, RefPtr<DisplayLinkCallback>>; return *map; } static i32 s_next_callback_id = 1; i32 DisplayLink::register_callback(Function<void(i32)> callback) { if (callbacks().is_empty()) WindowServerConnection::the().async_enable_display_link(); i32 callback_id = s_next_callback_id++; callbacks().set(callback_id, adopt_ref(*new DisplayLinkCallback(callback_id, move(callback)))); return callback_id; } bool DisplayLink::unregister_callback(i32 callback_id) { VERIFY(callbacks().contains(callback_id)); callbacks().remove(callback_id); if (callbacks().is_empty()) WindowServerConnection::the().async_disable_display_link(); return true; } void DisplayLink::notify(Badge<WindowServerConnection>) { auto copy_of_callbacks = callbacks(); for (auto& it : copy_of_callbacks) it.value->invoke(); } }
1,664
588
// Copyright Epic Games, Inc. All Rights Reserved. #include "BombastManifestDemo.h" #include "Modules/ModuleManager.h" IMPLEMENT_PRIMARY_GAME_MODULE( FDefaultGameModuleImpl, BombastManifestDemo, "BombastManifestDemo" );
223
81
#include <stdio.h> #include <stdlib.h> void * Realloc(void *ptr, int size) { if (size == 0) size = sizeof(int); if (ptr == NULL) ptr = calloc(size,1); else ptr = realloc(ptr, size); return(ptr); }
220
94
#include "Terminal.h" #include "STL/Graphics/Framebuffer.h" #include "STL/String/String.h" #include "STL/String/cstr.h" #include "STL/System/System.h" #include "Version.h" #define NEWLINE_OFFSET RAISED_WIDTH * 3 namespace Terminal { uint64_t PrevTick = 0; char Command[64]; STL::String Text; STL::Point CursorPos = STL::Point(0, 0); bool RedrawText = false; bool DrawUnderline = false; bool ClearCommand = false; void Write(const char* cstr) { Text += cstr; } STL::PROR Procedure(STL::PROM Message, STL::PROI Input) { switch(Message) { case STL::PROM::INIT: { STL::PINFO* Info = (STL::PINFO*)Input; Info->Type = STL::PROT::WINDOWED; Info->Depth = 1; Info->Left = 360; Info->Top = 200; Info->Width = 1000 + NEWLINE_OFFSET * 2; Info->Height = 650; Info->Title = "Terminal"; Text = ""; Command[0] = 0; CursorPos = STL::Point(0, 0); Write("\n\r"); Write("Welcome to the Terminal of "); Write(OS_VERSION); Write("!\n\r"); Write("Type \"help\" for a list of all available commands.\n\n\r"); Write(STL::System("sysfetch")); Write("\n\r"); Write("> "); RedrawText = true; } break; case STL::PROM::TICK: { uint64_t CurrentTick = *(uint64_t*)Input; if (PrevTick + 50 < CurrentTick) { DrawUnderline = !DrawUnderline; PrevTick = CurrentTick; return STL::PROR::DRAW; } } break; case STL::PROM::DRAW: { STL::Framebuffer* Buffer = (STL::Framebuffer*)Input; //Clear command for (uint32_t i = 0; i < STL::Length(Command) + 2; i++) { Buffer->PutChar(' ', STL::Point(CursorPos.X + 8 * i, CursorPos.Y), 1, STL::ARGB(255), STL::ARGB(0)); } //Scroll up if (CursorPos.Y + STL::LineAmount(Text.cstr()) * 16 + NEWLINE_OFFSET * 2 > Buffer->Height) { uint64_t Amount = (CursorPos.Y + STL::LineAmount(Text.cstr()) * 16 + NEWLINE_OFFSET * 2) - Buffer->Height; for (uint32_t y = NEWLINE_OFFSET; y < Buffer->Height - NEWLINE_OFFSET - Amount; y++) { for (uint32_t x = NEWLINE_OFFSET; x < Buffer->Width - NEWLINE_OFFSET; x++) { *(STL::ARGB*)((uint64_t)Buffer->Base + x * 4 + y * Buffer->PixelsPerScanline * 4) = *(STL::ARGB*)((uint64_t)Buffer->Base + x * 4 + (y + Amount) * Buffer->PixelsPerScanline * 4); } } for (uint32_t y = Buffer->Height - NEWLINE_OFFSET - Amount; y < Buffer->Height; y++) { for (uint32_t x = NEWLINE_OFFSET; x < Buffer->Width - NEWLINE_OFFSET; x++) { *(STL::ARGB*)((uint64_t)Buffer->Base + x * 4 + y * Buffer->PixelsPerScanline * 4) = STL::ARGB(0); } } CursorPos.Y -= Amount; if (CursorPos.Y < 0) { CursorPos.Y = 0; } } if (RedrawText) { //Print text Buffer->Print(Text.cstr(), CursorPos, 1, STL::ARGB(255), STL::ARGB(0), NEWLINE_OFFSET); Text = ""; Command[0] = 0; RedrawText = false; //Draw Edge Buffer->DrawRect(STL::Point(0, 0), STL::Point(Buffer->Width, RAISED_WIDTH * 2), STL::ARGB(200)); Buffer->DrawRect(STL::Point(0, 0), STL::Point(RAISED_WIDTH * 2, Buffer->Height), STL::ARGB(200)); Buffer->DrawRect(STL::Point(Buffer->Width - RAISED_WIDTH * 2, 0), STL::Point(Buffer->Width, Buffer->Height), STL::ARGB(200)); Buffer->DrawRect(STL::Point(0, Buffer->Height - RAISED_WIDTH * 2), STL::Point(Buffer->Width, Buffer->Height), STL::ARGB(200)); Buffer->DrawSunkenRectEdge(STL::Point(RAISED_WIDTH * 2, RAISED_WIDTH * 2), STL::Point(Buffer->Width - RAISED_WIDTH * 2, Buffer->Height - RAISED_WIDTH * 2)); } //Print command STL::Point Temp = CursorPos; Buffer->Print(Command, Temp, 1, STL::ARGB(255), STL::ARGB(0), NEWLINE_OFFSET); //Print underline if (DrawUnderline) { Buffer->PutChar('_', Temp, 1, STL::ARGB(255), STL::ARGB(0)); } else { Buffer->PutChar(' ', Temp, 1, STL::ARGB(255), STL::ARGB(0)); } } break; case STL::PROM::KEYPRESS: { uint8_t Key = *(uint8_t*)Input; if (Key == ENTER) { Text += Command; Text += "\n\r"; Text += STL::System(Command); Text += "\n\r> "; RedrawText = true; } else if (Key == BACKSPACE) { uint64_t CommandLength = STL::Length(Command); if (CommandLength != 0) { Command[CommandLength - 1] = 0; Command[CommandLength] = 0; } } else { uint64_t CommandLength = STL::Length(Command); if (CommandLength < 63) { Command[CommandLength] = Key; Command[CommandLength + 1] = 0; } } return STL::PROR::DRAW; } break; case STL::PROM::CLEAR: { Text = ""; Command[0] = 0; CursorPos = STL::Point(0, 0); } break; case STL::PROM::KILL: { Text = ""; Command[0] = 0; } break; default: { } break; } return STL::PROR::SUCCESS; } }
6,346
2,072
// Borland C++ Builder // Copyright (c) 1995, 2002 by Borland Software Corporation // All rights reserved // (DO NOT EDIT: machine generated header) 'ElTreeDTPickEdit.pas' rev: 6.00 #ifndef ElTreeDTPickEditHPP #define ElTreeDTPickEditHPP #pragma delphiheader begin #pragma option push -w- #pragma option push -Vx #include <ElDTPick.hpp> // Pascal unit #include <ElHeader.hpp> // Pascal unit #include <ElTree.hpp> // Pascal unit #include <Types.hpp> // Pascal unit #include <Classes.hpp> // Pascal unit #include <SysUtils.hpp> // Pascal unit #include <Forms.hpp> // Pascal unit #include <Controls.hpp> // Pascal unit #include <Messages.hpp> // Pascal unit #include <Windows.hpp> // Pascal unit #include <SysInit.hpp> // Pascal unit #include <System.hpp> // Pascal unit //-- user supplied ----------------------------------------------------------- namespace Eltreedtpickedit { //-- type declarations ------------------------------------------------------- class DELPHICLASS TElTreeInplaceDateTimePicker; class PASCALIMPLEMENTATION TElTreeInplaceDateTimePicker : public Eltree::TElTreeInplaceEditor { typedef Eltree::TElTreeInplaceEditor inherited; private: Classes::TWndMethod SaveWndProc; void __fastcall EditorWndProc(Messages::TMessage &Message); protected: Eldtpick::TElDateTimePicker* FEditor; virtual void __fastcall DoStartOperation(void); virtual void __fastcall DoStopOperation(bool Accepted); virtual bool __fastcall GetVisible(void); virtual void __fastcall TriggerAfterOperation(bool &Accepted, bool &DefaultConversion); virtual void __fastcall TriggerBeforeOperation(bool &DefaultConversion); virtual void __fastcall SetEditorParent(void); public: __fastcall virtual TElTreeInplaceDateTimePicker(Classes::TComponent* AOwner); __fastcall virtual ~TElTreeInplaceDateTimePicker(void); __property Eldtpick::TElDateTimePicker* Editor = {read=FEditor}; }; //-- var, const, procedure --------------------------------------------------- } /* namespace Eltreedtpickedit */ using namespace Eltreedtpickedit; #pragma option pop // -w- #pragma option pop // -Vx #pragma delphiheader end. //-- end unit ---------------------------------------------------------------- #endif // ElTreeDTPickEdit
2,223
669
// Boost.Geometry (aka GGL, Generic Geometry Library) // Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands. // Copyright (c) 2008-2012 Bruno Lalande, Paris, France. // Copyright (c) 2009-2012 Mateusz Loskot, London, UK. // Parts of Boost.Geometry are redesigned from Geodan's Geographic Library // (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands. // Use, modification and distribution is subject to 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_GEOMETRY_ALGORITHMS_DISJOINT_HPP #define BOOST_GEOMETRY_ALGORITHMS_DISJOINT_HPP #include <cstddef> #include <deque> #include <boost/mpl/if.hpp> #include <boost/range.hpp> #include <boost/static_assert.hpp> #include <boost/geometry/core/access.hpp> #include <boost/geometry/core/coordinate_dimension.hpp> #include <boost/geometry/core/reverse_dispatch.hpp> #include <boost/geometry/algorithms/detail/disjoint.hpp> #include <boost/geometry/algorithms/detail/for_each_range.hpp> #include <boost/geometry/algorithms/detail/point_on_border.hpp> #include <boost/geometry/algorithms/detail/overlay/get_turns.hpp> #include <boost/geometry/algorithms/within.hpp> #include <boost/geometry/geometries/concepts/check.hpp> #include <boost/geometry/util/math.hpp> namespace boost { namespace geometry { #ifndef DOXYGEN_NO_DETAIL namespace detail { namespace disjoint { template<typename Geometry> struct check_each_ring_for_within { bool has_within; Geometry const& m_geometry; inline check_each_ring_for_within(Geometry const& g) : has_within(false) , m_geometry(g) {} template <typename Range> inline void apply(Range const& range) { typename geometry::point_type<Range>::type p; geometry::point_on_border(p, range); if (geometry::within(p, m_geometry)) { has_within = true; } } }; template <typename FirstGeometry, typename SecondGeometry> inline bool rings_containing(FirstGeometry const& geometry1, SecondGeometry const& geometry2) { check_each_ring_for_within<FirstGeometry> checker(geometry1); geometry::detail::for_each_range(geometry2, checker); return checker.has_within; } struct assign_disjoint_policy { // We want to include all points: static bool const include_no_turn = true; static bool const include_degenerate = true; static bool const include_opposite = true; // We don't assign extra info: template < typename Info, typename Point1, typename Point2, typename IntersectionInfo, typename DirInfo > static inline void apply(Info& , Point1 const& , Point2 const&, IntersectionInfo const&, DirInfo const&) {} }; template <typename Geometry1, typename Geometry2> struct disjoint_linear { static inline bool apply(Geometry1 const& geometry1, Geometry2 const& geometry2) { typedef typename geometry::point_type<Geometry1>::type point_type; typedef overlay::turn_info<point_type> turn_info; std::deque<turn_info> turns; // Specify two policies: // 1) Stop at any intersection // 2) In assignment, include also degenerate points (which are normally skipped) disjoint_interrupt_policy policy; geometry::get_turns < false, false, assign_disjoint_policy >(geometry1, geometry2, turns, policy); if (policy.has_intersections) { return false; } return true; } }; template <typename Segment1, typename Segment2> struct disjoint_segment { static inline bool apply(Segment1 const& segment1, Segment2 const& segment2) { typedef typename point_type<Segment1>::type point_type; segment_intersection_points<point_type> is = strategy::intersection::relate_cartesian_segments < policies::relate::segments_intersection_points < Segment1, Segment2, segment_intersection_points<point_type> > >::apply(segment1, segment2); return is.count == 0; } }; template <typename Geometry1, typename Geometry2> struct general_areal { static inline bool apply(Geometry1 const& geometry1, Geometry2 const& geometry2) { if (! disjoint_linear<Geometry1, Geometry2>::apply(geometry1, geometry2)) { return false; } // If there is no intersection of segments, they might located // inside each other if (rings_containing(geometry1, geometry2) || rings_containing(geometry2, geometry1)) { return false; } return true; } }; }} // namespace detail::disjoint #endif // DOXYGEN_NO_DETAIL #ifndef DOXYGEN_NO_DISPATCH namespace dispatch { template < typename GeometryTag1, typename GeometryTag2, typename Geometry1, typename Geometry2, std::size_t DimensionCount > struct disjoint : detail::disjoint::general_areal<Geometry1, Geometry2> {}; template <typename Point1, typename Point2, std::size_t DimensionCount> struct disjoint<point_tag, point_tag, Point1, Point2, DimensionCount> : detail::disjoint::point_point<Point1, Point2, 0, DimensionCount> {}; template <typename Box1, typename Box2, std::size_t DimensionCount> struct disjoint<box_tag, box_tag, Box1, Box2, DimensionCount> : detail::disjoint::box_box<Box1, Box2, 0, DimensionCount> {}; template <typename Point, typename Box, std::size_t DimensionCount> struct disjoint<point_tag, box_tag, Point, Box, DimensionCount> : detail::disjoint::point_box<Point, Box, 0, DimensionCount> {}; template <typename Linestring1, typename Linestring2> struct disjoint<linestring_tag, linestring_tag, Linestring1, Linestring2, 2> : detail::disjoint::disjoint_linear<Linestring1, Linestring2> {}; template <typename Linestring1, typename Linestring2> struct disjoint<segment_tag, segment_tag, Linestring1, Linestring2, 2> : detail::disjoint::disjoint_segment<Linestring1, Linestring2> {}; template <typename Linestring, typename Segment> struct disjoint<linestring_tag, segment_tag, Linestring, Segment, 2> : detail::disjoint::disjoint_linear<Linestring, Segment> {}; template < typename GeometryTag1, typename GeometryTag2, typename Geometry1, typename Geometry2, std::size_t DimensionCount > struct disjoint_reversed { static inline bool apply(Geometry1 const& g1, Geometry2 const& g2) { return disjoint < GeometryTag2, GeometryTag1, Geometry2, Geometry1, DimensionCount >::apply(g2, g1); } }; } // namespace dispatch #endif // DOXYGEN_NO_DISPATCH /*! \brief \brief_check2{are disjoint} \ingroup disjoint \tparam Geometry1 \tparam_geometry \tparam Geometry2 \tparam_geometry \param geometry1 \param_geometry \param geometry2 \param_geometry \return \return_check2{are disjoint} \qbk{[include reference/algorithms/disjoint.qbk]} */ template <typename Geometry1, typename Geometry2> inline bool disjoint(Geometry1 const& geometry1, Geometry2 const& geometry2) { concept::check_concepts_and_equal_dimensions < Geometry1 const, Geometry2 const >(); return boost::mpl::if_c < reverse_dispatch<Geometry1, Geometry2>::type::value, dispatch::disjoint_reversed < typename tag<Geometry1>::type, typename tag<Geometry2>::type, Geometry1, Geometry2, dimension<Geometry1>::type::value >, dispatch::disjoint < typename tag<Geometry1>::type, typename tag<Geometry2>::type, Geometry1, Geometry2, dimension<Geometry1>::type::value > >::type::apply(geometry1, geometry2); } }} // namespace boost::geometry #endif // BOOST_GEOMETRY_ALGORITHMS_DISJOINT_HPP
8,541
2,758
/* * The MIT License (MIT) * * Copyright (c) 2015 Microsoft Corporation * * -=- Robust Distributed System Nucleus (rDSN) -=- * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /* * Description: * Replication testing framework. * * Revision history: * Nov., 2015, @qinzuoyan (Zuoyan Qin), first version * xxxx-xx-xx, author, fix bug about xxx */ # include "checker.h" # include "case.h" # include "dsn/utility/factory_store.h" # include "../../replica_server/replication_lib/replica.h" # include "../../replica_server/replication_lib/replica_stub.h" # include "../../replica_server/replication_lib/mutation_log.h" # include "../../meta_server/meta_server_lib/meta_service.h" # include "../../meta_server/meta_server_lib/meta_server_failure_detector.h" # include "../../meta_server/meta_server_lib/server_state.h" # include "../../meta_server/meta_server_lib/server_load_balancer.h" # include "../../common/replication_ds.h" # include <sstream> # include <boost/lexical_cast.hpp> # include <dsn/tool_api.h> # ifdef __TITLE__ # undef __TITLE__ # endif # define __TITLE__ "simple_kv.checker" namespace dsn { namespace replication { namespace test { class checker_load_balancer: public simple_load_balancer { public: static bool s_disable_balancer; public: checker_load_balancer(meta_service* svc): simple_load_balancer(svc) {} pc_status cure(const meta_view &view, const dsn::gpid& gpid, configuration_proposal_action &action) override { const partition_configuration& pc = *get_config(*view.apps, gpid); action.type = config_type::CT_INVALID; if (s_disable_balancer) return pc_status::healthy; pc_status result; if (pc.primary.is_invalid()) { if (pc.secondaries.size() > 0) { action.node = pc.secondaries[0]; for (unsigned int i=1; i<pc.secondaries.size(); ++i) if (pc.secondaries[i] < action.node) action.node = pc.secondaries[i]; action.type = config_type::CT_UPGRADE_TO_PRIMARY; result = pc_status::ill; } else if (pc.last_drops.size() == 0) { std::vector<rpc_address> sort_result; sort_alive_nodes(*view.nodes, primary_comparator(*view.nodes), sort_result); action.node = sort_result[0]; action.type = config_type::CT_ASSIGN_PRIMARY; result = pc_status::ill; } // DDD else { action.node = *pc.last_drops.rbegin(); action.type = config_type::CT_ASSIGN_PRIMARY; derror("%d.%d enters DDD state, we are waiting for its last primary node %s to come back ...", pc.pid.get_app_id(), pc.pid.get_partition_index(), action.node.to_string() ); result = pc_status::dead; } action.target = action.node; } else if (static_cast<int>(pc.secondaries.size()) + 1 < pc.max_replica_count) { std::vector<rpc_address> sort_result; sort_alive_nodes(*view.nodes, partition_comparator(*view.nodes), sort_result); for (auto& node: sort_result) { if (!is_member(pc, node)) { action.node = node; break; } } action.target = pc.primary; action.type = config_type::CT_ADD_SECONDARY; result = pc_status::ill; } else { result = pc_status::healthy; } return result; } }; bool test_checker::s_inited = false; bool checker_load_balancer::s_disable_balancer = false; test_checker::test_checker() { } void test_checker::control_balancer(bool disable_it) { checker_load_balancer::s_disable_balancer = disable_it; if (disable_it && meta_leader()) { server_state* ss = meta_leader()->_service->_state.get(); for (auto& kv: ss->_exist_apps) { std::shared_ptr<app_state>& app = kv.second; app->helpers->clear_proposals(); } } } bool test_checker::init(const char* name, dsn_app_info* info, int count) { if (s_inited) return false; _apps.resize(count); for (int i = 0; i < count; i++) { _apps[i] = info[i]; } utils::factory_store<replication::server_load_balancer>::register_factory( "checker_load_balancer", replication::server_load_balancer::create<checker_load_balancer>, PROVIDER_TYPE_MAIN); for (auto& app : _apps) { if (0 == strcmp(app.type, "meta")) { meta_service_app* meta_app = (meta_service_app*)app.app.app_context_ptr; meta_app->_service->_state->set_config_change_subscriber_for_test( std::bind(&test_checker::on_config_change, this, std::placeholders::_1)); meta_app->_service->_meta_opts.server_load_balancer_type = "checker_load_balancer"; _meta_servers.push_back(meta_app); } else if (0 == strcmp(app.type, "replica")) { replication_service_app* replica_app = (replication_service_app*)app.app.app_context_ptr; replica_app->_stub->set_replica_state_subscriber_for_test( std::bind(&test_checker::on_replica_state_change, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3), false); _replica_servers.push_back(replica_app); } } for (int i = 0; i < count; i++) { auto& node = _apps[i]; int id = node.app_id; std::string name = node.name; rpc_address paddr(node.primary_address); int port = paddr.port(); _node_to_address[name] = paddr; ddebug("=== node_to_address[%s]=%s", name.c_str(), paddr.to_string()); _address_to_node[port] = name; ddebug("=== address_to_node[%u]=%s", port, name.c_str()); if (id != port) { _address_to_node[id] = name; ddebug("=== address_to_node[%u]=%s", id, name.c_str()); } } s_inited = true; if (!test_case::instance().init(g_case_input)) { std::cerr << "init test_case failed" << std::endl; s_inited = false; return false; } return true; } void test_checker::exit() { if (!s_inited) return; for (meta_service_app* app : _meta_servers) { app->_service->_started = false; } if (test_case::s_close_replica_stub_on_exit) { dsn::tools::tool_app* app = dsn::tools::get_current_tool(); app->stop_all_apps(true); } } void test_checker::check() { test_case::instance().on_check(); if (g_done) return; // 'config_change' and 'replica_state_change' are detected in two ways: // - each time this check() is called, checking will be applied // - register subscribers on meta_server and replica_server to be notified parti_config cur_config; if (get_current_config(cur_config) && cur_config != _last_config) { test_case::instance().on_config_change(_last_config, cur_config); _last_config = cur_config; } state_snapshot cur_states; get_current_states(cur_states); if (cur_states != _last_states) { test_case::instance().on_state_change(_last_states, cur_states); _last_states = cur_states; } } void test_checker::on_replica_state_change(::dsn::rpc_address from, const replica_configuration& new_config, bool is_closing) { state_snapshot cur_states; get_current_states(cur_states); if (cur_states != _last_states) { test_case::instance().on_state_change(_last_states, cur_states); _last_states = cur_states; } } void test_checker::on_config_change(const app_mapper& new_config) { const partition_configuration* pc = get_config(new_config, g_default_gpid); dassert(pc != nullptr, "drop table is not allowed in test"); parti_config cur_config; cur_config.convert_from(*pc); if (cur_config != _last_config) { test_case::instance().on_config_change(_last_config, cur_config); _last_config = cur_config; } } void test_checker::get_current_states(state_snapshot& states) { states.state_map.clear(); for (auto& app : _replica_servers) { if (!app->is_started()) continue; for (auto& kv : app->_stub->_replicas) { replica_ptr r = kv.second; dassert(kv.first == r->get_gpid(), ""); replica_id id(r->get_gpid(), app->name()); replica_state& rs = states.state_map[id]; rs.id = id; rs.status = r->status(); rs.ballot = r->get_ballot(); rs.last_committed_decree = r->last_committed_decree(); rs.last_durable_decree = r->last_durable_decree(); } } } bool test_checker::get_current_config(parti_config& config) { meta_service_app* meta = meta_leader(); if (meta == nullptr) return false; partition_configuration c; //we should never try to acquire lock when we are in checker. Because we are the only //thread that is running. //The app and emulator have lots in common with the OS's userspace and kernel space. //In normal case, "apps" runs in "userspace". You can "trap into kernel(i.e. the emulator)" by the rDSN's //"enqueue,dequeue and lock..." //meta->_service->_state->query_configuration_by_gpid(g_default_gpid, c); const meta_view view = meta->_service->_state->get_meta_view(); const partition_configuration* pc = get_config(*(view.apps), g_default_gpid); c = *pc; config.convert_from(c); return true; } meta_service_app* test_checker::meta_leader() { for (auto& meta : _meta_servers) { if (!meta->is_started()) return nullptr; if (meta->_service->_failure_detector->is_primary()) return meta; } return nullptr; } bool test_checker::is_server_normal() { auto meta = meta_leader(); if (!meta) return false; return check_replica_state(1, 2, 0); } bool test_checker::check_replica_state(int primary_count, int secondary_count, int inactive_count) { int p = 0; int s = 0; int i = 0; for (auto& rs : _replica_servers) { if (!rs->is_started()) return false; for (auto& replica : rs->_stub->_replicas) { auto status = replica.second->status(); if (status == partition_status::PS_PRIMARY) p++; else if (status == partition_status::PS_SECONDARY) s++; else if (status == partition_status::PS_INACTIVE) i++; } } return p == primary_count && s == secondary_count && i == inactive_count; } std::string test_checker::address_to_node_name(rpc_address addr) { auto find = _address_to_node.find(addr.port()); if (find != _address_to_node.end()) return find->second; return "node@" + boost::lexical_cast<std::string>(addr.port()); } rpc_address test_checker::node_name_to_address(const std::string& name) { auto find = _node_to_address.find(name); if (find != _node_to_address.end()) return find->second; return rpc_address(); } void install_checkers() { dsn_register_app_checker( "simple_kv.checker", ::dsn::tools::checker::create<wrap_checker>, ::dsn::tools::checker::apply ); } }}}
12,782
4,194
// solved: 2014-03-06 21:38:08 // https://codeforces.com/contest/394/problem/B #include <bits/stdc++.h> using namespace std; int main() { int p, x, n = 0, rem = 0, last; vector<int> num; cin >> p >> x; for (int i = 1; i <= 9; i++) { n = 1; last = i; rem = 0; num.push_back(i); if (p + x == 2) { cout << 1; return 0; } while (n < p) { int L = last; last = (L * x + rem) % 10; rem = ((L * x + rem) - (L * x + rem) % 10) / 10; num.push_back(last); n = num.size(); if ((last * x + rem) == i && num.size() == p && last != 0) { for (int i = p - 1; i >= 0; i--) cout << num[i]; return 0; } } num.clear(); } cout << "Impossible"; return 0; }
925
357
/** * Copyright (c) 2012 - 2014 TideSDK contributors * http://www.tidesdk.org * Includes modified sources under the Apache 2 License * Copyright (c) 2008 - 2012 Appcelerator Inc * Refer to LICENSE for details of distribution and use. **/ #include "file_stream.h" #include <cstring> #include <sstream> #include <sys/stat.h> #include <Poco/LineEndingConverter.h> namespace ti { FileStream::FileStream(std::string filename) : Stream("Filesystem.FileStream"), istream(0), ostream(0), stream(0) { #ifdef OS_OSX // in OSX, we need to expand ~ in paths to their absolute path value // we do that with a nifty helper method in NSString this->filename = [[[NSString stringWithUTF8String:filename.c_str()] stringByExpandingTildeInPath] fileSystemRepresentation]; #else this->filename = filename; #endif this->SetMethod("open", &FileStream::_Open); this->SetMethod("isOpen", &FileStream::_IsOpen); this->SetMethod("close", &FileStream::_Close); this->SetMethod("seek", &FileStream::_Seek); this->SetMethod("tell", &FileStream::_Tell); this->SetMethod("write", &FileStream::_Write); this->SetMethod("read", &FileStream::_Read); this->SetMethod("readLine", &FileStream::_ReadLine); this->SetMethod("writeLine", &FileStream::_WriteLine); this->SetMethod("ready", &FileStream::_Ready); // These should be depricated and no longer used. // All constants should be kept on Ti.Filesystem object. this->Set("MODE_READ", Value::NewInt(MODE_READ)); this->Set("MODE_APPEND", Value::NewInt(MODE_APPEND)); this->Set("MODE_WRITE", Value::NewInt(MODE_WRITE)); } FileStream::~FileStream() { this->Close(); } bool FileStream::Open(FileStreamMode mode, bool binary, bool append) { // close the prev stream if needed this->Close(); try { std::ios::openmode flags = (std::ios::openmode) 0; bool output = false; if (binary) { flags|=std::ios::binary; } if (mode == MODE_APPEND) { flags|=std::ios::out|std::ios::app; output = true; } else if (mode == MODE_WRITE) { flags |= std::ios::out|std::ios::trunc; output = true; } else if (mode == MODE_READ) { flags |= std::ios::in; } if (output) { this->ostream = new Poco::FileOutputStream(this->filename,flags); this->stream = this->ostream; #ifndef OS_WIN32 chmod(this->filename.c_str(),S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH); #endif } else { this->istream = new Poco::FileInputStream(this->filename,flags); this->stream = this->istream; } return true; } catch (Poco::Exception& exc) { Logger* logger = Logger::Get("Filesystem.FileStream"); logger->Error("Error in open. Exception: %s",exc.displayText().c_str()); throw ValueException::FromString(exc.displayText()); } } bool FileStream::IsOpen() const { return this->stream != NULL; } void FileStream::Close() { try { if (this->stream) { if (this->ostream) { this->ostream->flush(); } this->stream->close(); delete this->stream; this->stream = NULL; this->istream = NULL; this->ostream = NULL; } } catch (Poco::Exception& exc) { Logger* logger = Logger::Get("Filesystem.FileStream"); logger->Error("Error in close. Exception: %s",exc.displayText().c_str()); throw ValueException::FromString(exc.displayText()); } } void FileStream::Seek(int offset, int direction) { if (this->istream) this->istream->seekg(offset, (std::ios::seekdir)direction); else if (this->ostream) this->ostream->seekp(offset, (std::ios::seekdir)direction); else throw ValueException::FromString("FileStream must be opened before seeking"); } int FileStream::Tell() { if (this->istream) return this->istream->tellg(); else if (this->ostream) return this->ostream->tellp(); throw ValueException::FromString("FileStream must be opend before using tell"); } void FileStream::Write(const char* buffer, size_t size) { if(!this->ostream) throw ValueException::FromString("FileStream must be opened for writing before calling write"); try { this->ostream->write(buffer, size); } catch (Poco::Exception& ex) { Logger* logger = Logger::Get("Filesystem.FileStream"); logger->Error("Error in write. Exception: %s",ex.displayText().c_str()); throw ValueException::FromString(ex.displayText()); } } bool FileStream::IsWritable() const { return this->ostream != NULL; } size_t FileStream::Read(const char* buffer, size_t size) { if(!this->istream) throw ValueException::FromString("FileStream must be opened for writing before calling write"); try { this->istream->read((char*)buffer, size); return this->istream->gcount(); } catch (Poco::Exception& ex) { Logger* logger = Logger::Get("Filesystem.FileStream"); logger->Error("Error in read. Exception: %s",ex.displayText().c_str()); throw ValueException::FromString(ex.displayText()); } } bool FileStream::IsReadable() const { return this->istream != NULL; } void FileStream::_Open(const ValueList& args, ValueRef result) { args.VerifyException("open", "?ibb"); FileStreamMode mode = (FileStreamMode) args.GetInt(0, MODE_READ); bool binary = args.GetBool(1, false); bool append = args.GetBool(2, false); bool opened = this->Open(mode, binary, append); result->SetBool(opened); } void FileStream::_IsOpen(const ValueList& args, ValueRef result) { result->SetBool(this->IsOpen()); } void FileStream::_Close(const ValueList& args, ValueRef result) { this->Close(); } void FileStream::_Seek(const ValueList& args, ValueRef result) { args.VerifyException("seek", "i?i"); int offset = args.GetInt(0); int direction = args.GetInt(1, std::ios::beg); this->Seek(offset, direction); } void FileStream::_Tell(const ValueList& args, ValueRef result) { result->SetInt(this->Tell()); } void FileStream::_Write(const ValueList& args, ValueRef result) { args.VerifyException("write", "s|o|n"); char *text = NULL; int size = 0; if (args.at(0)->IsObject()) { TiObjectRef b = args.at(0)->ToObject(); AutoPtr<Bytes> bytes = b.cast<Bytes>(); if (!bytes.isNull()) { text = (char*)bytes->Pointer(); size = (int)bytes->Length(); } } else if (args.at(0)->IsString()) { text = (char*)args.at(0)->ToString(); } else if (args.at(0)->IsInt()) { std::stringstream ostr; ostr << args.at(0)->ToInt(); text = (char*)ostr.str().c_str(); size = ostr.str().length(); } else if (args.at(0)->IsDouble()) { std::stringstream ostr; ostr << args.at(0)->ToDouble(); text = (char*)ostr.str().c_str(); size = ostr.str().length(); } else { throw ValueException::FromString("Could not write with type passed"); } if (size==0) { size = strlen(text); } if (text == NULL || size <= 0) { result->SetBool(false); return; } Write(text,size); result->SetBool(true); } void FileStream::_Read(const ValueList& args, ValueRef result) { args.VerifyException("read", "?i"); try { if (args.size() >= 1) { int size = args.GetInt(0); if (size <= 0) throw ValueException::FromString("File.read() size must be greater than zero"); BytesRef buffer = new Bytes(size + 1); int readCount = this->Read(buffer->Pointer(), size); if (readCount > 0) { buffer->Write("\0", 1, readCount); result->SetObject(buffer); } else { // No data read, must be at EOF result->SetNull(); } } else { // If no read size is provided, read the entire file. // TODO: this is not a very efficent method and should be deprecated // and replaced by buffered stream transports std::vector<char> buffer; char data[4096]; while (!this->istream->eof()) { this->istream->read((char*)&data, 4095); int length = this->istream->gcount(); if (length > 0) { buffer.insert(buffer.end(), data, data+length); } else break; } result->SetObject(new Bytes(&(buffer[0]), buffer.size())); } } catch (Poco::Exception& exc) { Logger* logger = Logger::Get("Filesystem.FileStream"); logger->Error("Error in read. Exception: %s",exc.displayText().c_str()); throw ValueException::FromString(exc.displayText()); } } void FileStream::_ReadLine(const ValueList& args, ValueRef result) { try { if (!this->istream) { Logger* logger = Logger::Get("Filesystem.FileStream"); logger->Error("Error in readLine. FileInputStream is null"); throw ValueException::FromString("FileStream must be opened for reading before calling readLine"); } if (this->istream->eof()) { // close the file result->SetNull(); } else { std::string line; std::getline(*this->istream, line); #ifdef OS_WIN32 // In some cases std::getline leaves a CR on the end of the line in win32 -- why God, why? if (!line.empty()) { char lastChar = line.at(line.size()-1); if (lastChar == '\r') { line = line.substr(0, line.size()-1); } } #endif if (line.empty() || line.size()==0) { if (this->istream->eof()) { // if this is EOF, return null result->SetNull(); } else { // this is an empty line, just empty Bytes object. result->SetObject(new Bytes()); } } else { result->SetObject(new Bytes(line)); } } } catch (Poco::Exception& exc) { Logger* logger = Logger::Get("Filesystem.FileStream"); logger->Error("Error in readLine. Exception: %s",exc.displayText().c_str()); throw ValueException::FromString(exc.displayText()); } } void FileStream::_WriteLine(const ValueList& args, ValueRef result) { args.VerifyException("writeLine", "s|o|n"); if(! this->stream) { throw ValueException::FromString("FileStream must be opened before calling readLine"); } char *text = NULL; int size = 0; if (args.at(0)->IsObject()) { TiObjectRef b = args.at(0)->ToObject(); AutoPtr<Bytes> bytes = b.cast<Bytes>(); if (!bytes.isNull()) { text = (char*)bytes->Pointer(); size = (int)bytes->Length(); } } else if (args.at(0)->IsString()) { text = (char*)args.at(0)->ToString(); } else if (args.at(0)->IsInt()) { std::stringstream ostr; ostr << args.at(0)->ToInt(); text = (char*)ostr.str().c_str(); size = ostr.str().length(); } else if (args.at(0)->IsDouble()) { std::stringstream ostr; ostr << args.at(0)->ToDouble(); text = (char*)ostr.str().c_str(); size = ostr.str().length(); } else { throw ValueException::FromString("Could not write with type passed"); } if (size==0) { size = strlen(text); } if (text == NULL || size <= 0) { result->SetBool(false); return; } std::string astr = text; #ifdef OS_WIN32 astr += "\r\n"; #else astr += "\n"; #endif Write((char*)astr.c_str(),astr.length()); result->SetBool(true); } void FileStream::_Ready(const ValueList& args, ValueRef result) { if(!this->stream) { result->SetBool(false); } else { result->SetBool(this->stream->eof()==false); } } }
12,750
3,924
/* * Open Source Movement Analysis Library * Copyright (C) 2016, Moveck Solution Inc., all rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the following * disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * Neither the name(s) of the copyright holders nor the names * of its contributors may be used to endorse or promote products * derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "openma/bindings/loggerdevice.h" namespace ma { namespace bindings { LoggerDevice::LoggerDevice() : m_ErrorFlag(false), m_ErrorMessage() {}; void LoggerDevice::clearError() { this->m_ErrorFlag = false; this->m_ErrorMessage.clear(); }; bool LoggerDevice::errorFlag() const _OPENMA_NOEXCEPT { return this->m_ErrorFlag; }; const std::string& LoggerDevice::errorMessage() const _OPENMA_NOEXCEPT { return this->m_ErrorMessage; }; void LoggerDevice::write(ma::Message category, const char* msg) _OPENMA_NOEXCEPT { if (category == ma::Message::Error) { this->m_ErrorFlag = true; this->m_ErrorMessage.append("\n"); this->m_ErrorMessage.append(msg); } }; }; };
2,439
827
/* * Copyright (C) 2010 University of Szeged * Copyright (C) 2010 Zoltan Herczeg * Copyright (C) 2013 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY UNIVERSITY OF SZEGED ``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 UNIVERSITY OF SZEGED OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "third_party/blink/renderer/platform/graphics/filters/fe_lighting.h" #include "third_party/blink/renderer/platform/graphics/filters/distant_light_source.h" #include "third_party/blink/renderer/platform/graphics/filters/paint_filter_builder.h" #include "third_party/blink/renderer/platform/graphics/filters/point_light_source.h" #include "third_party/blink/renderer/platform/graphics/filters/spot_light_source.h" #include "third_party/skia/include/core/SkPoint3.h" namespace blink { FELighting::FELighting(Filter* filter, LightingType lighting_type, const Color& lighting_color, float surface_scale, float diffuse_constant, float specular_constant, float specular_exponent, scoped_refptr<LightSource> light_source) : FilterEffect(filter), lighting_type_(lighting_type), light_source_(std::move(light_source)), lighting_color_(lighting_color), surface_scale_(surface_scale), diffuse_constant_(std::max(diffuse_constant, 0.0f)), specular_constant_(std::max(specular_constant, 0.0f)), specular_exponent_(clampTo(specular_exponent, 1.0f, 128.0f)) {} sk_sp<PaintFilter> FELighting::CreateImageFilter() { if (!light_source_) return CreateTransparentBlack(); base::Optional<PaintFilter::CropRect> crop_rect = GetCropRect(); const PaintFilter::CropRect* rect = base::OptionalOrNullptr(crop_rect); Color light_color = AdaptColorToOperatingInterpolationSpace(lighting_color_); sk_sp<PaintFilter> input(paint_filter_builder::Build( InputEffect(0), OperatingInterpolationSpace())); switch (light_source_->GetType()) { case LS_DISTANT: { DistantLightSource* distant_light_source = static_cast<DistantLightSource*>(light_source_.get()); float azimuth_rad = deg2rad(distant_light_source->Azimuth()); float elevation_rad = deg2rad(distant_light_source->Elevation()); const SkPoint3 direction = SkPoint3::Make( cosf(azimuth_rad) * cosf(elevation_rad), sinf(azimuth_rad) * cosf(elevation_rad), sinf(elevation_rad)); return sk_make_sp<LightingDistantPaintFilter>( GetLightingType(), direction, light_color.Rgb(), surface_scale_, GetFilterConstant(), specular_exponent_, std::move(input), rect); } case LS_POINT: { PointLightSource* point_light_source = static_cast<PointLightSource*>(light_source_.get()); const FloatPoint3D position = point_light_source->GetPosition(); const SkPoint3 sk_position = SkPoint3::Make(position.X(), position.Y(), position.Z()); return sk_make_sp<LightingPointPaintFilter>( GetLightingType(), sk_position, light_color.Rgb(), surface_scale_, GetFilterConstant(), specular_exponent_, std::move(input), rect); } case LS_SPOT: { SpotLightSource* spot_light_source = static_cast<SpotLightSource*>(light_source_.get()); const SkPoint3 location = SkPoint3::Make(spot_light_source->GetPosition().X(), spot_light_source->GetPosition().Y(), spot_light_source->GetPosition().Z()); const SkPoint3 target = SkPoint3::Make(spot_light_source->Direction().X(), spot_light_source->Direction().Y(), spot_light_source->Direction().Z()); float specular_exponent = spot_light_source->SpecularExponent(); float limiting_cone_angle = spot_light_source->LimitingConeAngle(); if (!limiting_cone_angle || limiting_cone_angle > 90 || limiting_cone_angle < -90) limiting_cone_angle = 90; return sk_make_sp<LightingSpotPaintFilter>( GetLightingType(), location, target, specular_exponent, limiting_cone_angle, light_color.Rgb(), surface_scale_, GetFilterConstant(), specular_exponent_, std::move(input), rect); } default: NOTREACHED(); return nullptr; } } PaintFilter::LightingType FELighting::GetLightingType() { return specular_constant_ > 0 ? PaintFilter::LightingType::kSpecular : PaintFilter::LightingType::kDiffuse; } float FELighting::GetFilterConstant() { return GetLightingType() == PaintFilter::LightingType::kSpecular ? specular_constant_ : diffuse_constant_; } } // namespace blink
5,921
1,893
/* * Copyright (C) 2004-2010 NXP Software * Copyright (C) 2010 The Android Open Source Project * * 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 "LVPSA.h" #include "LVPSA_Private.h" #include "LVM_Macros.h" #include "VectorArithmetic.h" #define LVM_MININT_32 0x80000000 static LVM_INT32 mult32x32in32_shiftr(LVM_INT32 a, LVM_INT32 b, LVM_INT32 c) { LVM_INT64 result = ((LVM_INT64)a * b) >> c; if (result >= INT32_MAX) { return INT32_MAX; } else if (result <= INT32_MIN) { return INT32_MIN; } else { return (LVM_INT32)result; } } /************************************************************************************/ /* */ /* FUNCTION: LVPSA_Process */ /* */ /* DESCRIPTION: */ /* The process applies band pass filters to the signal. Each output */ /* feeds a quasi peak filter for level detection. */ /* */ /* PARAMETERS: */ /* hInstance Pointer to the instance */ /* pLVPSA_InputSamples Pointer to the input samples buffer */ /* InputBlockSize Number of mono samples to process */ /* AudioTime Playback time of the input samples */ /* */ /* */ /* RETURNS: */ /* LVPSA_OK Succeeds */ /* otherwise Error due to bad parameters */ /* */ /************************************************************************************/ LVPSA_RETURN LVPSA_Process ( pLVPSA_Handle_t hInstance, LVM_FLOAT *pLVPSA_InputSamples, LVM_UINT16 InputBlockSize, LVPSA_Time AudioTime ) { LVPSA_InstancePr_t *pLVPSA_Inst = (LVPSA_InstancePr_t*)hInstance; LVM_FLOAT *pScratch; LVM_INT16 ii; LVM_INT32 AudioTimeInc; extern LVM_UINT32 LVPSA_SampleRateInvTab[]; LVM_UINT8 *pWrite_Save; /* Position of the write pointer at the beginning of the process */ /****************************************************************************** CHECK PARAMETERS *******************************************************************************/ if(hInstance == LVM_NULL || pLVPSA_InputSamples == LVM_NULL) { return(LVPSA_ERROR_NULLADDRESS); } if(InputBlockSize == 0 || InputBlockSize > pLVPSA_Inst->MaxInputBlockSize) { return(LVPSA_ERROR_INVALIDPARAM); } pScratch = (LVM_FLOAT*)pLVPSA_Inst->MemoryTable.Region[LVPSA_MEMREGION_SCRATCH].pBaseAddress; pWrite_Save = pLVPSA_Inst->pSpectralDataBufferWritePointer; /****************************************************************************** APPLY NEW SETTINGS IF NEEDED *******************************************************************************/ if (pLVPSA_Inst->bControlPending == LVM_TRUE) { pLVPSA_Inst->bControlPending = 0; LVPSA_ApplyNewSettings( pLVPSA_Inst); } /****************************************************************************** PROCESS SAMPLES *******************************************************************************/ /* Put samples in range [-0.5;0.5[ for BP filters (see Biquads documentation) */ Copy_Float(pLVPSA_InputSamples, pScratch, (LVM_INT16)InputBlockSize); Shift_Sat_Float(-1, pScratch, pScratch, (LVM_INT16)InputBlockSize); for (ii = 0; ii < pLVPSA_Inst->nRelevantFilters; ii++) { switch(pLVPSA_Inst->pBPFiltersPrecision[ii]) { case LVPSA_SimplePrecisionFilter: BP_1I_D16F16C14_TRC_WRA_01 ( &pLVPSA_Inst->pBP_Instances[ii], pScratch, pScratch + InputBlockSize, (LVM_INT16)InputBlockSize); break; case LVPSA_DoublePrecisionFilter: BP_1I_D16F32C30_TRC_WRA_01 ( &pLVPSA_Inst->pBP_Instances[ii], pScratch, pScratch + InputBlockSize, (LVM_INT16)InputBlockSize); break; default: break; } LVPSA_QPD_Process_Float ( pLVPSA_Inst, pScratch + InputBlockSize, (LVM_INT16)InputBlockSize, ii); } /****************************************************************************** UPDATE SpectralDataBufferAudioTime *******************************************************************************/ if(pLVPSA_Inst->pSpectralDataBufferWritePointer != pWrite_Save) { AudioTimeInc = mult32x32in32_shiftr( (AudioTime + ((LVM_INT32)pLVPSA_Inst->LocalSamplesCount * 1000)), (LVM_INT32)LVPSA_SampleRateInvTab[pLVPSA_Inst->CurrentParams.Fs], LVPSA_FsInvertShift); pLVPSA_Inst->SpectralDataBufferAudioTime = AudioTime + AudioTimeInc; } return(LVPSA_OK); } /************************************************************************************/ /* */ /* FUNCTION: LVPSA_GetSpectrum */ /* */ /* DESCRIPTION: */ /* Gets the levels values at a certain point in time */ /* */ /* */ /* PARAMETERS: */ /* hInstance Pointer to the instance */ /* GetSpectrumAudioTime Retrieve the values at this time */ /* pCurrentValues Pointer to a buffer that will contain levels' values */ /* pMaxValues Pointer to a buffer that will contain max levels' values */ /* */ /* */ /* RETURNS: */ /* LVPSA_OK Succeeds */ /* otherwise Error due to bad parameters */ /* */ /************************************************************************************/ LVPSA_RETURN LVPSA_GetSpectrum ( pLVPSA_Handle_t hInstance, LVPSA_Time GetSpectrumAudioTime, LVM_UINT8 *pCurrentValues, LVM_UINT8 *pPeakValues ) { LVPSA_InstancePr_t *pLVPSA_Inst = (LVPSA_InstancePr_t*)hInstance; LVM_INT32 StatusDelta, ii; LVM_UINT8 *pRead; if(hInstance == LVM_NULL || pCurrentValues == LVM_NULL || pPeakValues == LVM_NULL) { return(LVPSA_ERROR_NULLADDRESS); } /* First find the place where to look in the status buffer */ if(GetSpectrumAudioTime <= pLVPSA_Inst->SpectralDataBufferAudioTime) { MUL32x32INTO32((pLVPSA_Inst->SpectralDataBufferAudioTime - GetSpectrumAudioTime),LVPSA_InternalRefreshTimeInv,StatusDelta,LVPSA_InternalRefreshTimeShift); if((StatusDelta * LVPSA_InternalRefreshTime) != (pLVPSA_Inst->SpectralDataBufferAudioTime - GetSpectrumAudioTime)) { StatusDelta += 1; } } else { /* This part handles the wrap around */ MUL32x32INTO32(((pLVPSA_Inst->SpectralDataBufferAudioTime - (LVM_INT32)LVM_MININT_32) + ((LVM_INT32)LVM_MAXINT_32 - GetSpectrumAudioTime)),LVPSA_InternalRefreshTimeInv,StatusDelta,LVPSA_InternalRefreshTimeShift) if(((LVM_INT32)(StatusDelta * LVPSA_InternalRefreshTime)) != ((LVM_INT32)((pLVPSA_Inst->SpectralDataBufferAudioTime - (LVM_INT32)LVM_MININT_32) + ((LVM_INT32)LVM_MAXINT_32 - GetSpectrumAudioTime)))) { StatusDelta += 1; } } /* Check whether the desired level is not too "old" (see 2.10 in LVPSA_DesignNotes.doc)*/ if( ((GetSpectrumAudioTime < pLVPSA_Inst->SpectralDataBufferAudioTime)&& ((GetSpectrumAudioTime<0)&&(pLVPSA_Inst->SpectralDataBufferAudioTime>0))&& (((LVM_INT32)(-GetSpectrumAudioTime + pLVPSA_Inst->SpectralDataBufferAudioTime))>LVM_MAXINT_32))|| ((GetSpectrumAudioTime > pLVPSA_Inst->SpectralDataBufferAudioTime)&& (((GetSpectrumAudioTime>=0)&&(pLVPSA_Inst->SpectralDataBufferAudioTime>=0))|| ((GetSpectrumAudioTime<=0)&&(pLVPSA_Inst->SpectralDataBufferAudioTime<=0))|| (((GetSpectrumAudioTime>=0)&&(pLVPSA_Inst->SpectralDataBufferAudioTime<=0))&& (((LVM_INT32)(GetSpectrumAudioTime - pLVPSA_Inst->SpectralDataBufferAudioTime))<LVM_MAXINT_32))))|| (StatusDelta > (LVM_INT32)pLVPSA_Inst->SpectralDataBufferLength) || (!StatusDelta)) { for(ii = 0; ii < pLVPSA_Inst->nBands; ii++) { pCurrentValues[ii] = 0; pPeakValues[ii] = 0; } return(LVPSA_OK); } /* Set the reading pointer */ if((LVM_INT32)(StatusDelta * pLVPSA_Inst->nBands) > (pLVPSA_Inst->pSpectralDataBufferWritePointer - pLVPSA_Inst->pSpectralDataBufferStart)) { pRead = pLVPSA_Inst->pSpectralDataBufferWritePointer + (pLVPSA_Inst->SpectralDataBufferLength - (LVM_UINT32)StatusDelta) * pLVPSA_Inst->nBands; } else { pRead = pLVPSA_Inst->pSpectralDataBufferWritePointer - StatusDelta * pLVPSA_Inst->nBands; } /* Read the status buffer and fill the output buffers */ for(ii = 0; ii < pLVPSA_Inst->nBands; ii++) { pCurrentValues[ii] = pRead[ii]; if(pLVPSA_Inst->pPreviousPeaks[ii] <= pRead[ii]) { pLVPSA_Inst->pPreviousPeaks[ii] = pRead[ii]; } else if(pLVPSA_Inst->pPreviousPeaks[ii] != 0) { LVM_INT32 temp; /*Re-compute max values for decay */ temp = (LVM_INT32)(LVPSA_MAXUNSIGNEDCHAR - pLVPSA_Inst->pPreviousPeaks[ii]); temp = ((temp * LVPSA_MAXLEVELDECAYFACTOR)>>LVPSA_MAXLEVELDECAYSHIFT); /* If the gain has no effect, "help" the value to increase */ if(temp == (LVPSA_MAXUNSIGNEDCHAR - pLVPSA_Inst->pPreviousPeaks[ii])) { temp += 1; } /* Saturate */ temp = (temp > LVPSA_MAXUNSIGNEDCHAR) ? LVPSA_MAXUNSIGNEDCHAR : temp; /* Store new max level */ pLVPSA_Inst->pPreviousPeaks[ii] = (LVM_UINT8)(LVPSA_MAXUNSIGNEDCHAR - temp); } pPeakValues[ii] = pLVPSA_Inst->pPreviousPeaks[ii]; } return(LVPSA_OK); }
12,808
3,777
// // fetch_request_test.cpp // ---------------------- // // Copyright (c) 2015 Daniel Joos // // Distributed under MIT license. (See file LICENSE) // #include <gtest/gtest.h> #include <libkafka_asio/libkafka_asio.h> class FetchRequestTest : public ::testing::Test { protected: virtual void SetUp() { ASSERT_EQ(0, request.topics().size()); } libkafka_asio::FetchRequest request; }; TEST_F(FetchRequestTest, FetchTopic_New) { request.FetchTopic("mytopic", 1, 2); ASSERT_EQ(1, request.topics().size()); ASSERT_EQ(1, request.topics()[0].partitions.size()); ASSERT_STREQ("mytopic", request.topics()[0].topic_name.c_str()); ASSERT_EQ(1, request.topics()[0].partitions[0].partition); ASSERT_EQ(2, request.topics()[0].partitions[0].fetch_offset); ASSERT_EQ(libkafka_asio::constants::kDefaultFetchMaxBytes, request.topics()[0].partitions[0].max_bytes); } TEST_F(FetchRequestTest, FetchTopic_Override) { request.FetchTopic("mytopic", 1, 2); ASSERT_EQ(1, request.topics().size()); ASSERT_EQ(1, request.topics()[0].partitions.size()); ASSERT_EQ(2, request.topics()[0].partitions[0].fetch_offset); request.FetchTopic("mytopic", 1, 4); ASSERT_EQ(1, request.topics().size()); ASSERT_EQ(1, request.topics()[0].partitions.size()); ASSERT_EQ(4, request.topics()[0].partitions[0].fetch_offset); } TEST_F(FetchRequestTest, FetchTopic_MultiplePartitions) { request.FetchTopic("mytopic", 0, 2); request.FetchTopic("mytopic", 1, 4); ASSERT_EQ(1, request.topics().size()); ASSERT_EQ(2, request.topics()[0].partitions.size()); ASSERT_EQ(2, request.topics()[0].partitions[0].fetch_offset); ASSERT_EQ(4, request.topics()[0].partitions[1].fetch_offset); } TEST_F(FetchRequestTest, FetchTopic_MultipleTopics) { request.FetchTopic("foo", 0, 2); request.FetchTopic("bar", 1, 4); ASSERT_EQ(2, request.topics().size()); ASSERT_EQ(1, request.topics()[0].partitions.size()); ASSERT_EQ(1, request.topics()[1].partitions.size()); ASSERT_EQ(2, request.topics()[0].partitions[0].fetch_offset); ASSERT_EQ(4, request.topics()[1].partitions[0].fetch_offset); }
2,109
866
/* * Copyright (C) 2006, 2008 Apple Inc. All rights reserved. * Copyright (C) 2010 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "third_party/blink/renderer/core/editing/commands/apply_block_element_command.h" #include "third_party/blink/renderer/core/dom/node_computed_style.h" #include "third_party/blink/renderer/core/dom/text.h" #include "third_party/blink/renderer/core/editing/commands/editing_commands_utilities.h" #include "third_party/blink/renderer/core/editing/editing_utilities.h" #include "third_party/blink/renderer/core/editing/selection_template.h" #include "third_party/blink/renderer/core/editing/visible_position.h" #include "third_party/blink/renderer/core/editing/visible_selection.h" #include "third_party/blink/renderer/core/editing/visible_units.h" #include "third_party/blink/renderer/core/html/html_br_element.h" #include "third_party/blink/renderer/core/html/html_element.h" #include "third_party/blink/renderer/core/html_names.h" #include "third_party/blink/renderer/core/style/computed_style.h" #include "third_party/blink/renderer/platform/bindings/exception_state.h" #include "third_party/blink/renderer/platform/heap/heap.h" namespace blink { ApplyBlockElementCommand::ApplyBlockElementCommand( Document& document, const QualifiedName& tag_name, const AtomicString& inline_style) : CompositeEditCommand(document), tag_name_(tag_name), inline_style_(inline_style) {} ApplyBlockElementCommand::ApplyBlockElementCommand( Document& document, const QualifiedName& tag_name) : CompositeEditCommand(document), tag_name_(tag_name) {} void ApplyBlockElementCommand::DoApply(EditingState* editing_state) { // ApplyBlockElementCommands are only created directly by editor commands' // execution, which updates layout before entering doApply(). DCHECK(!GetDocument().NeedsLayoutTreeUpdate()); if (!RootEditableElementOf(EndingSelection().Base())) return; VisiblePosition visible_end = EndingVisibleSelection().VisibleEnd(); VisiblePosition visible_start = EndingVisibleSelection().VisibleStart(); if (visible_start.IsNull() || visible_start.IsOrphan() || visible_end.IsNull() || visible_end.IsOrphan()) return; // When a selection ends at the start of a paragraph, we rarely paint // the selection gap before that paragraph, because there often is no gap. // In a case like this, it's not obvious to the user that the selection // ends "inside" that paragraph, so it would be confusing if Indent/Outdent // operated on that paragraph. // FIXME: We paint the gap before some paragraphs that are indented with left // margin/padding, but not others. We should make the gap painting more // consistent and then use a left margin/padding rule here. if (visible_end.DeepEquivalent() != visible_start.DeepEquivalent() && IsStartOfParagraph(visible_end)) { const Position& new_end = PreviousPositionOf(visible_end, kCannotCrossEditingBoundary) .DeepEquivalent(); SelectionInDOMTree::Builder builder; builder.Collapse(visible_start.ToPositionWithAffinity()); if (new_end.IsNotNull()) builder.Extend(new_end); SetEndingSelection(SelectionForUndoStep::From(builder.Build())); ABORT_EDITING_COMMAND_IF(EndingVisibleSelection().VisibleStart().IsNull()); ABORT_EDITING_COMMAND_IF(EndingVisibleSelection().VisibleEnd().IsNull()); } VisibleSelection selection = SelectionForParagraphIteration(EndingVisibleSelection()); VisiblePosition start_of_selection = selection.VisibleStart(); ABORT_EDITING_COMMAND_IF(start_of_selection.IsNull()); VisiblePosition end_of_selection = selection.VisibleEnd(); ABORT_EDITING_COMMAND_IF(end_of_selection.IsNull()); ContainerNode* start_scope = nullptr; int start_index = IndexForVisiblePosition(start_of_selection, start_scope); ContainerNode* end_scope = nullptr; int end_index = IndexForVisiblePosition(end_of_selection, end_scope); FormatSelection(start_of_selection, end_of_selection, editing_state); if (editing_state->IsAborted()) return; GetDocument().UpdateStyleAndLayout(DocumentUpdateReason::kEditing); DCHECK_EQ(start_scope, end_scope); DCHECK_GE(start_index, 0); DCHECK_LE(start_index, end_index); if (start_scope == end_scope && start_index >= 0 && start_index <= end_index) { VisiblePosition start(VisiblePositionForIndex(start_index, start_scope)); VisiblePosition end(VisiblePositionForIndex(end_index, end_scope)); if (start.IsNotNull() && end.IsNotNull()) { SetEndingSelection(SelectionForUndoStep::From( SelectionInDOMTree::Builder() .Collapse(start.ToPositionWithAffinity()) .Extend(end.DeepEquivalent()) .Build())); } } } static bool IsAtUnsplittableElement(const Position& pos) { Node* node = pos.AnchorNode(); return node == RootEditableElementOf(pos) || node == EnclosingNodeOfType(pos, &IsTableCell); } void ApplyBlockElementCommand::FormatSelection( const VisiblePosition& start_of_selection, const VisiblePosition& end_of_selection, EditingState* editing_state) { // Special case empty unsplittable elements because there's nothing to split // and there's nothing to move. const Position& caret_position = MostForwardCaretPosition(start_of_selection.DeepEquivalent()); if (IsAtUnsplittableElement(caret_position)) { HTMLElement* blockquote = CreateBlockElement(); InsertNodeAt(blockquote, caret_position, editing_state); if (editing_state->IsAborted()) return; auto* placeholder = MakeGarbageCollected<HTMLBRElement>(GetDocument()); AppendNode(placeholder, blockquote, editing_state); if (editing_state->IsAborted()) return; SetEndingSelection(SelectionForUndoStep::From( SelectionInDOMTree::Builder() .Collapse(Position::BeforeNode(*placeholder)) .Build())); return; } HTMLElement* blockquote_for_next_indent = nullptr; VisiblePosition end_of_current_paragraph = EndOfParagraph(start_of_selection); const VisiblePosition& visible_end_of_last_paragraph = EndOfParagraph(end_of_selection); const Position& end_of_next_last_paragraph = EndOfParagraph(NextPositionOf(visible_end_of_last_paragraph)) .DeepEquivalent(); Position end_of_last_paragraph = visible_end_of_last_paragraph.DeepEquivalent(); bool at_end = false; while (end_of_current_paragraph.DeepEquivalent() != end_of_next_last_paragraph && !at_end) { if (end_of_current_paragraph.DeepEquivalent() == end_of_last_paragraph) at_end = true; Position start, end; RangeForParagraphSplittingTextNodesIfNeeded( end_of_current_paragraph, end_of_last_paragraph, start, end); end_of_current_paragraph = CreateVisiblePosition(end); Node* enclosing_cell = EnclosingNodeOfType(start, &IsTableCell); PositionWithAffinity end_of_next_paragraph = EndOfNextParagrahSplittingTextNodesIfNeeded( end_of_current_paragraph, end_of_last_paragraph, start, end) .ToPositionWithAffinity(); FormatRange(start, end, end_of_last_paragraph, blockquote_for_next_indent, editing_state); if (editing_state->IsAborted()) return; // Don't put the next paragraph in the blockquote we just created for this // paragraph unless the next paragraph is in the same cell. if (enclosing_cell && enclosing_cell != EnclosingNodeOfType(end_of_next_paragraph.GetPosition(), &IsTableCell)) blockquote_for_next_indent = nullptr; // indentIntoBlockquote could move more than one paragraph if the paragraph // is in a list item or a table. As a result, // |endOfNextLastParagraph| could refer to a position no longer in the // document. if (end_of_next_last_paragraph.IsNotNull() && !end_of_next_last_paragraph.IsConnected()) break; // Sanity check: Make sure our moveParagraph calls didn't remove // endOfNextParagraph.anchorNode() If somehow, e.g. mutation // event handler, we did, return to prevent crashes. if (end_of_next_paragraph.IsNotNull() && !end_of_next_paragraph.IsConnected()) return; GetDocument().UpdateStyleAndLayout(DocumentUpdateReason::kEditing); end_of_current_paragraph = CreateVisiblePosition(end_of_next_paragraph); } } static bool IsNewLineAtPosition(const Position& position) { auto* text_node = DynamicTo<Text>(position.ComputeContainerNode()); int offset = position.OffsetInContainerNode(); if (!text_node || offset < 0 || offset >= static_cast<int>(text_node->length())) return false; DummyExceptionStateForTesting exception_state; String text_at_position = text_node->substringData(offset, 1, exception_state); if (exception_state.HadException()) return false; return text_at_position[0] == '\n'; } static const ComputedStyle* ComputedStyleOfEnclosingTextNode( const Position& position) { if (!position.IsOffsetInAnchor() || !position.ComputeContainerNode() || !position.ComputeContainerNode()->IsTextNode()) return nullptr; return position.ComputeContainerNode()->GetComputedStyle(); } void ApplyBlockElementCommand::RangeForParagraphSplittingTextNodesIfNeeded( const VisiblePosition& end_of_current_paragraph, Position& end_of_last_paragraph, Position& start, Position& end) { start = StartOfParagraph(end_of_current_paragraph).DeepEquivalent(); end = end_of_current_paragraph.DeepEquivalent(); bool is_start_and_end_on_same_node = false; if (const ComputedStyle* start_style = ComputedStyleOfEnclosingTextNode(start)) { is_start_and_end_on_same_node = ComputedStyleOfEnclosingTextNode(end) && start.ComputeContainerNode() == end.ComputeContainerNode(); bool is_start_and_end_of_last_paragraph_on_same_node = ComputedStyleOfEnclosingTextNode(end_of_last_paragraph) && start.ComputeContainerNode() == end_of_last_paragraph.ComputeContainerNode(); // Avoid obtanining the start of next paragraph for start // TODO(yosin) We should use |PositionMoveType::CodePoint| for // |previousPositionOf()|. if (start_style->PreserveNewline() && IsNewLineAtPosition(start) && !IsNewLineAtPosition( PreviousPositionOf(start, PositionMoveType::kCodeUnit)) && start.OffsetInContainerNode() > 0) start = StartOfParagraph(CreateVisiblePosition(PreviousPositionOf( end, PositionMoveType::kCodeUnit))) .DeepEquivalent(); // If start is in the middle of a text node, split. if (!start_style->CollapseWhiteSpace() && start.OffsetInContainerNode() > 0) { int start_offset = start.OffsetInContainerNode(); auto* start_text = To<Text>(start.ComputeContainerNode()); SplitTextNode(start_text, start_offset); GetDocument().UpdateStyleAndLayoutTree(); start = Position::FirstPositionInNode(*start_text); if (is_start_and_end_on_same_node) { DCHECK_GE(end.OffsetInContainerNode(), start_offset); end = Position(start_text, end.OffsetInContainerNode() - start_offset); } if (is_start_and_end_of_last_paragraph_on_same_node) { DCHECK_GE(end_of_last_paragraph.OffsetInContainerNode(), start_offset); end_of_last_paragraph = Position(start_text, end_of_last_paragraph.OffsetInContainerNode() - start_offset); } } } if (const ComputedStyle* end_style = ComputedStyleOfEnclosingTextNode(end)) { bool is_end_and_end_of_last_paragraph_on_same_node = ComputedStyleOfEnclosingTextNode(end_of_last_paragraph) && end.AnchorNode() == end_of_last_paragraph.AnchorNode(); // Include \n at the end of line if we're at an empty paragraph if (end_style->PreserveNewline() && start == end && end.OffsetInContainerNode() < static_cast<int>(To<Text>(end.ComputeContainerNode())->length())) { int end_offset = end.OffsetInContainerNode(); // TODO(yosin) We should use |PositionMoveType::CodePoint| for // |previousPositionOf()|. if (!IsNewLineAtPosition( PreviousPositionOf(end, PositionMoveType::kCodeUnit)) && IsNewLineAtPosition(end)) end = Position(end.ComputeContainerNode(), end_offset + 1); if (is_end_and_end_of_last_paragraph_on_same_node && end.OffsetInContainerNode() >= end_of_last_paragraph.OffsetInContainerNode()) end_of_last_paragraph = end; } // If end is in the middle of a text node, split. if (end_style->UserModify() != EUserModify::kReadOnly && !end_style->CollapseWhiteSpace() && end.OffsetInContainerNode() && end.OffsetInContainerNode() < static_cast<int>(To<Text>(end.ComputeContainerNode())->length())) { auto* end_container = To<Text>(end.ComputeContainerNode()); SplitTextNode(end_container, end.OffsetInContainerNode()); GetDocument().UpdateStyleAndLayoutTree(); const Node* const previous_sibling_of_end = end_container->previousSibling(); DCHECK(previous_sibling_of_end); if (is_start_and_end_on_same_node) { start = FirstPositionInOrBeforeNode(*previous_sibling_of_end); } if (is_end_and_end_of_last_paragraph_on_same_node) { if (end_of_last_paragraph.OffsetInContainerNode() == end.OffsetInContainerNode()) { end_of_last_paragraph = LastPositionInOrAfterNode(*previous_sibling_of_end); } else { end_of_last_paragraph = Position( end_container, end_of_last_paragraph.OffsetInContainerNode() - end.OffsetInContainerNode()); } } end = Position::LastPositionInNode(*previous_sibling_of_end); } } } VisiblePosition ApplyBlockElementCommand::EndOfNextParagrahSplittingTextNodesIfNeeded( VisiblePosition& end_of_current_paragraph, Position& end_of_last_paragraph, Position& start, Position& end) { const VisiblePosition& end_of_next_paragraph = EndOfParagraph(NextPositionOf(end_of_current_paragraph)); const Position& end_of_next_paragraph_position = end_of_next_paragraph.DeepEquivalent(); const ComputedStyle* style = ComputedStyleOfEnclosingTextNode(end_of_next_paragraph_position); if (!style) return end_of_next_paragraph; auto* const end_of_next_paragraph_text = To<Text>(end_of_next_paragraph_position.ComputeContainerNode()); if (!style->PreserveNewline() || !end_of_next_paragraph_position.OffsetInContainerNode() || !IsNewLineAtPosition( Position::FirstPositionInNode(*end_of_next_paragraph_text))) return end_of_next_paragraph; // \n at the beginning of the text node immediately following the current // paragraph is trimmed by moveParagraphWithClones. If endOfNextParagraph was // pointing at this same text node, endOfNextParagraph will be shifted by one // paragraph. Avoid this by splitting "\n" SplitTextNode(end_of_next_paragraph_text, 1); GetDocument().UpdateStyleAndLayout(DocumentUpdateReason::kEditing); Text* const previous_text = DynamicTo<Text>(end_of_next_paragraph_text->previousSibling()); if (end_of_next_paragraph_text == start.ComputeContainerNode() && previous_text) { DCHECK_LT(start.OffsetInContainerNode(), end_of_next_paragraph_position.OffsetInContainerNode()); start = Position(previous_text, start.OffsetInContainerNode()); } if (end_of_next_paragraph_text == end.ComputeContainerNode() && previous_text) { DCHECK_LT(end.OffsetInContainerNode(), end_of_next_paragraph_position.OffsetInContainerNode()); end = Position(previous_text, end.OffsetInContainerNode()); } if (end_of_next_paragraph_text == end_of_last_paragraph.ComputeContainerNode()) { if (end_of_last_paragraph.OffsetInContainerNode() < end_of_next_paragraph_position.OffsetInContainerNode()) { // We can only fix endOfLastParagraph if the previous node was still text // and hasn't been modified by script. if (previous_text && static_cast<unsigned>( end_of_last_paragraph.OffsetInContainerNode()) <= previous_text->length()) { end_of_last_paragraph = Position( previous_text, end_of_last_paragraph.OffsetInContainerNode()); } } else { end_of_last_paragraph = Position(end_of_next_paragraph_text, end_of_last_paragraph.OffsetInContainerNode() - 1); } } return CreateVisiblePosition( Position(end_of_next_paragraph_text, end_of_next_paragraph_position.OffsetInContainerNode() - 1)); } HTMLElement* ApplyBlockElementCommand::CreateBlockElement() const { HTMLElement* element = CreateHTMLElement(GetDocument(), tag_name_); if (inline_style_.length()) element->setAttribute(html_names::kStyleAttr, inline_style_); return element; } } // namespace blink
18,533
5,655
#include "Color.h" #include "Colorf.h" #include <nctl/algorithms.h> namespace ncine { /////////////////////////////////////////////////////////// // STATIC DEFINITIONS /////////////////////////////////////////////////////////// const Color Color::Black(0, 0, 0, 255); const Color Color::White(255, 255, 255, 255); const Color Color::Red(255, 0, 0, 255); const Color Color::Green(0, 255, 0, 255); const Color Color::Blue(0, 0, 255, 255); const Color Color::Yellow(255, 255, 0, 255); const Color Color::Magenta(255, 0, 255, 255); const Color Color::Cyan(0, 255, 255, 255); /////////////////////////////////////////////////////////// // CONSTRUCTORS and DESTRUCTOR /////////////////////////////////////////////////////////// Color::Color() : Color(255, 255, 255, 255) { } Color::Color(unsigned int red, unsigned int green, unsigned int blue) : Color(red, green, blue, 255) { } Color::Color(unsigned int red, unsigned int green, unsigned int blue, unsigned int alpha) : channels_(nctl::StaticArrayMode::EXTEND_SIZE) { set(red, green, blue, alpha); } Color::Color(unsigned int hex) : channels_(nctl::StaticArrayMode::EXTEND_SIZE) { setAlpha(255); // The following method might set the alpha channel set(hex); } Color::Color(const unsigned int channels[NumChannels]) : channels_(nctl::StaticArrayMode::EXTEND_SIZE) { setVec(channels); } Color::Color(const Colorf &color) : channels_(nctl::StaticArrayMode::EXTEND_SIZE) { channels_[0] = static_cast<unsigned char>(color.r() * 255); channels_[1] = static_cast<unsigned char>(color.g() * 255); channels_[2] = static_cast<unsigned char>(color.b() * 255); channels_[3] = static_cast<unsigned char>(color.a() * 255); } /////////////////////////////////////////////////////////// // PUBLIC FUNCTIONS /////////////////////////////////////////////////////////// unsigned int Color::rgba() const { return (channels_[0] << 24) + (channels_[1] << 16) + (channels_[2] << 8) + channels_[3]; } unsigned int Color::argb() const { return (channels_[3] << 24) + (channels_[0] << 16) + (channels_[1] << 8) + channels_[2]; } unsigned int Color::abgr() const { return (channels_[3] << 24) + (channels_[2] << 16) + (channels_[1] << 8) + channels_[0]; } unsigned int Color::bgra() const { return (channels_[2] << 24) + (channels_[1] << 16) + (channels_[0] << 8) + channels_[3]; } void Color::set(unsigned int red, unsigned int green, unsigned int blue, unsigned int alpha) { channels_[0] = static_cast<unsigned char>(red); channels_[1] = static_cast<unsigned char>(green); channels_[2] = static_cast<unsigned char>(blue); channels_[3] = static_cast<unsigned char>(alpha); } void Color::set(unsigned int red, unsigned int green, unsigned int blue) { channels_[0] = static_cast<unsigned char>(red); channels_[1] = static_cast<unsigned char>(green); channels_[2] = static_cast<unsigned char>(blue); } void Color::set(unsigned int hex) { channels_[0] = static_cast<unsigned char>((hex & 0xFF0000) >> 16); channels_[1] = static_cast<unsigned char>((hex & 0xFF00) >> 8); channels_[2] = static_cast<unsigned char>(hex & 0xFF); if (hex > 0xFFFFFF) channels_[3] = static_cast<unsigned char>((hex & 0xFF000000) >> 24); } void Color::setVec(const unsigned int channels[NumChannels]) { set(channels[0], channels[1], channels[2], channels[3]); } void Color::setAlpha(unsigned int alpha) { channels_[3] = static_cast<unsigned char>(alpha); } Color &Color::operator=(const Colorf &color) { channels_[0] = static_cast<unsigned char>(color.r() * 255.0f); channels_[1] = static_cast<unsigned char>(color.g() * 255.0f); channels_[2] = static_cast<unsigned char>(color.b() * 255.0f); channels_[3] = static_cast<unsigned char>(color.a() * 255.0f); return *this; } bool Color::operator==(const Color &color) const { return (r() == color.r() && g() == color.g() && b() == color.b() && a() == color.a()); } Color &Color::operator+=(const Color &color) { for (unsigned int i = 0; i < NumChannels; i++) { unsigned int channelValue = channels_[i] + color.channels_[i]; channelValue = nctl::clamp(channelValue, 0U, 255U); channels_[i] = static_cast<unsigned char>(channelValue); } return *this; } Color &Color::operator-=(const Color &color) { for (unsigned int i = 0; i < NumChannels; i++) { unsigned int channelValue = channels_[i] - color.channels_[i]; channelValue = nctl::clamp(channelValue, 0U, 255U); channels_[i] = static_cast<unsigned char>(channelValue); } return *this; } Color &Color::operator*=(const Color &color) { for (unsigned int i = 0; i < NumChannels; i++) { float channelValue = channels_[i] * (color.channels_[i] / 255.0f); channelValue = nctl::clamp(channelValue, 0.0f, 255.0f); channels_[i] = static_cast<unsigned char>(channelValue); } return *this; } Color &Color::operator*=(float scalar) { for (unsigned int i = 0; i < NumChannels; i++) { float channelValue = channels_[i] * scalar; channelValue = nctl::clamp(channelValue, 0.0f, 255.0f); channels_[i] = static_cast<unsigned char>(channelValue); } return *this; } Color Color::operator+(const Color &color) const { Color result; for (unsigned int i = 0; i < NumChannels; i++) { unsigned int channelValue = channels_[i] + color.channels_[i]; channelValue = nctl::clamp(channelValue, 0U, 255U); result.channels_[i] = static_cast<unsigned char>(channelValue); } return result; } Color Color::operator-(const Color &color) const { Color result; for (unsigned int i = 0; i < NumChannels; i++) { unsigned int channelValue = channels_[i] - color.channels_[i]; channelValue = nctl::clamp(channelValue, 0U, 255U); result.channels_[i] = static_cast<unsigned char>(channelValue); } return result; } Color Color::operator*(const Color &color) const { Color result; for (unsigned int i = 0; i < NumChannels; i++) { float channelValue = channels_[i] * (color.channels_[i] / 255.0f); channelValue = nctl::clamp(channelValue, 0.0f, 255.0f); result.channels_[i] = static_cast<unsigned char>(channelValue); } return result; } Color Color::operator*(float scalar) const { Color result; for (unsigned int i = 0; i < NumChannels; i++) { float channelValue = channels_[i] * scalar; channelValue = nctl::clamp(channelValue, 0.0f, 255.0f); result.channels_[i] = static_cast<unsigned char>(channelValue); } return result; } }
6,368
2,478
#include "stdafx.h" //HINTERNET int WINAPI winhttpopenrequesthook (DWORD RetAddr, pfnwinhttpopenrequest fnwinhttpopenrequest, HINTERNET hConnect, LPCWSTR pwszVerb, LPCWSTR pwszObjectName, LPCWSTR pwszVersion, LPCWSTR pwszReferrer, LPCWSTR* ppwszAcceptTypes, DWORD dwFlags) { //"spclient.wg.spotify.com" //POST //L"/ad-logic/state/config" //L"/ad-logic/flashpoint" /* this is ad between song/popup */ //L"/playlist-publish/v1/subscription/playlist/xxxxx" /* sent when change playlist */ //GET /* payload are base64 */ //L"/ads/v2/config?payload=xxxxx" //L"/ads/v1/ads/hpto?payload=xxxxx" //L"/ads/v1/ads/leaderboard?payload=xxxxx //L"/pagead/conversion/?ai=xxxxx" //L"/monitoring?pload=xxxxx" //L"/pcs/view?xai=xxxxx" //HEADER /* add into every request */ //L"User-Agent: Spotify/111500448 Win32/0 (PC laptop)" //L"Authorization: Bearer xxxxx" if (wcsstr (pwszObjectName, L"/playlist-publish/") != 0) { return fnwinhttpopenrequest (hConnect, pwszVerb, pwszObjectName, pwszVersion, pwszReferrer, ppwszAcceptTypes, dwFlags); } else { // the failed will retry.. not good. return 0; } } int WINAPI getaddrinfohook (DWORD RetAddr, pfngetaddrinfo fngetaddrinfo, const char* nodename, const char* servname, const struct addrinfo* hints, struct addrinfo** res) { for (size_t i = 0; i < sizeof (blockhost) / sizeof (blockhost[0]); i++) { if (strstr (nodename, blockhost[i]) != 0) return WSANO_RECOVERY; } return fngetaddrinfo (nodename, servname, hints, res); } int WINAPI winhttpsendrequesthook (DWORD RetAddr, pfnwinhttpsendrequest fnwinhttpsendrequest, HINTERNET hRequest, LPCWSTR pwszHeaders, DWORD dwHeadersLength, LPVOID lpOptional, DWORD dwOptionalLength, DWORD dwTotalLength, DWORD_PTR dwContext) { return 1; // return success but nothing sent } int WINAPI winhttpwritedatahook (DWORD RetAddr, pfnwinhttpwritedata fnwinhttpwritedata, HINTERNET hRequest, LPCVOID lpBuffer, DWORD dwNumberOfBytesToWrite, LPDWORD lpdwNumberOfBytesWritten) { return 1; // return success but nothing write } int WINAPI winhttpreceiveresponsehook (DWORD RetAddr, pfnwinhttpreceiveresponse fnwinhttpreceiveresponse, HINTERNET hRequest, LPVOID lpReserved) { return 1; // return success but nothing receive } int WINAPI winhttpquerydataavailablehook (DWORD RetAddr, pfnwinhttpquerydataavailable fnwinhttpquerydataavailable, HINTERNET hRequest, LPDWORD lpdwNumberOfBytesAvailable) { //lpdwNumberOfBytesAvailable = 0; return 1; // return success with 0 byte to read } int WINAPI winhttpsetstatuscallbackhook (DWORD RetAddr, pfnwinhttpsetstatuscallback fnwinhttpsetstatuscallback, HINTERNET hInternet, WINHTTP_STATUS_CALLBACK lpfnInternetCallback, DWORD dwNotificationFlags, DWORD_PTR dwReserved) { // lpfnInternetCallback - Set this to NULL to remove the existing callback function. return fnwinhttpsetstatuscallback (hInternet, NULL, dwNotificationFlags, NULL); }
2,940
1,158
/* Copyright (c) 2013, Richard Martin 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 Richard Martin 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 RICHARD MARTIN 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 DEQUE_EVENT_LIST_HPP_ #define DEQUE_EVENT_LIST_HPP_ #include <deque> #include <algorithm> #include <utility> #include <type_traits> #include "BaseEvent.hpp" #include "EventList.hpp" using std::deque; using std::move; using std::enable_if; using std::is_base_of; namespace libsim { //Template metaprogramming baby template<class T, class U, class Enable = void> class DequeEventList; template <class T, class U> class DequeEventList<T, U, typename enable_if<is_base_of<BaseEvent<U>, T>::value>::type > : public EventList<T,U> { private: deque<T> data; public: DequeEventList() = default; DequeEventList(DequeEventList<T, U> const & cpy) : data(cpy.data) {} DequeEventList(DequeEventList<T, U> && mv) : data(move(mv.data)) {} DequeEventList<T, U>& operator =(const DequeEventList<T, U>& cpy) { data = cpy.data; } DequeEventList<T, U>& operator =(DequeEventList<T, U> && mv) { data = move(mv.data); } ~DequeEventList() { if( ! data.empty() ) { cout << "Danger, William Robinson. Event_List Destructor called while Events scheduled" << endl; } } void add(T evnt) override { if(data.empty()) { data.push_back(evnt); } else { //try to add it at the end auto riter = data.rbegin(); auto iter = data.begin(); if(evnt >= (*riter)) { //aka, the event being added is further off than the //oldest event currently in the queue. data.push_back(evnt); } else if (evnt <= (*iter)) { //aka, the event being added is younger than the next event in the queue. data.push_front(evnt); } else { //gutted. Now have to find the place for it to go. iter = upper_bound(data.begin(), data.end(), evnt); data.insert(iter, evnt); } } } void tick(U _time) override { if(data.empty()) { return; } auto evnt = data.front(); if(evnt.get_time() > _time) { return; } while(1) { if( evnt.get_time() > _time) { return; } else { data.pop_front(); evnt.dispatch(); if(data.empty()) { return; } evnt = data.front(); } } } void run() override { while(!data.empty()) { T evnt = data.front(); data.pop_front(); evnt.dispatch(); } } }; } #endif /* DEQUE_EVENT_LIST_HPP_ */
3,811
1,480
#include <Alerter/Alerter.h>
33
19
/** * @Author: Tian Qiao <qiaotian> * @Date: 2016-07-03T11:17:52+08:00 * @Email: qiaotian@me.com * @Last modified by: qiaotian * @Last modified time: 2016-07-03T11:19:50+08:00 * @License: Free License * @Inc: Google, Uber * @Easy */ Given a string, determine if a permutation of the string could form a palindrome. For example, "code" -> False, "aab" -> True, "carerac" -> True. Hint: 1. Consider the palindromes of odd vs even length. What difference do you notice? 2. Count the frequency of each character. 3. If each character occurs even number of times, then it must be a palindrome. How about character which occurs odd number of times? ________________________________________________________________________________ class Solution { public: /* bool canPermutePalindrome(string s) { int xnor = 0; for(auto i:s) { xnor^=i; } if(xnor==0) return true; int count = 0; // the times s occurs for(auto i:s) count+=(i==xnor); return count!=0; } */ bool canPermutePalindrome(string s) { vector<int> dict(256, 0); for(auto i:s) dict[i]++; int odd = 0; // the count of odd letter for(auto i:dict) { if(i%2) odd++; } return odd<=1; // 出现奇数次的字符不存在或者仅有一个 } };
1,315
479
// 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/sync/test/integration/passwords_helper.h" #include <sstream> #include <utility> #include "base/compiler_specific.h" #include "base/macros.h" #include "base/message_loop/message_loop.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/synchronization/waitable_event.h" #include "base/time/time.h" #include "chrome/browser/password_manager/password_store_factory.h" #include "chrome/browser/sync/profile_sync_service_factory.h" #include "chrome/browser/sync/test/integration/profile_sync_service_harness.h" #include "chrome/browser/sync/test/integration/sync_datatype_helper.h" #include "components/password_manager/core/browser/password_manager_test_utils.h" #include "components/password_manager/core/browser/password_store.h" #include "components/password_manager/core/browser/password_store_consumer.h" #include "content/public/test/test_utils.h" using autofill::PasswordForm; using password_manager::PasswordStore; using sync_datatype_helper::test; namespace { const char kFakeSignonRealm[] = "http://fake-signon-realm.google.com/"; const char kIndexedFakeOrigin[] = "http://fake-signon-realm.google.com/%d"; // We use a WaitableEvent to wait when logins are added, removed, or updated // instead of running the UI message loop because of a restriction that // prevents a DB thread from initiating a quit of the UI message loop. void PasswordStoreCallback(base::WaitableEvent* wait_event) { // Wake up passwords_helper::AddLogin. wait_event->Signal(); } class PasswordStoreConsumerHelper : public password_manager::PasswordStoreConsumer { public: PasswordStoreConsumerHelper() {} void OnGetPasswordStoreResults( std::vector<std::unique_ptr<PasswordForm>> results) override { result_.swap(results); // Quit the message loop to wake up passwords_helper::GetLogins. base::MessageLoopForUI::current()->QuitWhenIdle(); } std::vector<std::unique_ptr<PasswordForm>> result() { return std::move(result_); } private: std::vector<std::unique_ptr<PasswordForm>> result_; DISALLOW_COPY_AND_ASSIGN(PasswordStoreConsumerHelper); }; // PasswordForm::date_synced is a local field. Therefore it may be different // across clients. void ClearSyncDateField(std::vector<std::unique_ptr<PasswordForm>>* forms) { for (auto& form : *forms) { form->date_synced = base::Time(); } } } // namespace namespace passwords_helper { void AddLogin(PasswordStore* store, const PasswordForm& form) { ASSERT_TRUE(store); base::WaitableEvent wait_event( base::WaitableEvent::ResetPolicy::MANUAL, base::WaitableEvent::InitialState::NOT_SIGNALED); store->AddLogin(form); store->ScheduleTask(base::Bind(&PasswordStoreCallback, &wait_event)); wait_event.Wait(); } void UpdateLogin(PasswordStore* store, const PasswordForm& form) { ASSERT_TRUE(store); base::WaitableEvent wait_event( base::WaitableEvent::ResetPolicy::MANUAL, base::WaitableEvent::InitialState::NOT_SIGNALED); store->UpdateLogin(form); store->ScheduleTask(base::Bind(&PasswordStoreCallback, &wait_event)); wait_event.Wait(); } std::vector<std::unique_ptr<PasswordForm>> GetLogins(PasswordStore* store) { EXPECT_TRUE(store); password_manager::PasswordStore::FormDigest matcher_form = { PasswordForm::SCHEME_HTML, kFakeSignonRealm, GURL()}; PasswordStoreConsumerHelper consumer; store->GetLogins(matcher_form, &consumer); content::RunMessageLoop(); return consumer.result(); } void RemoveLogin(PasswordStore* store, const PasswordForm& form) { ASSERT_TRUE(store); base::WaitableEvent wait_event( base::WaitableEvent::ResetPolicy::MANUAL, base::WaitableEvent::InitialState::NOT_SIGNALED); store->RemoveLogin(form); store->ScheduleTask(base::Bind(&PasswordStoreCallback, &wait_event)); wait_event.Wait(); } void RemoveLogins(PasswordStore* store) { std::vector<std::unique_ptr<PasswordForm>> forms = GetLogins(store); for (const auto& form : forms) { RemoveLogin(store, *form); } } PasswordStore* GetPasswordStore(int index) { return PasswordStoreFactory::GetForProfile(test()->GetProfile(index), ServiceAccessType::IMPLICIT_ACCESS) .get(); } PasswordStore* GetVerifierPasswordStore() { return PasswordStoreFactory::GetForProfile( test()->verifier(), ServiceAccessType::IMPLICIT_ACCESS).get(); } bool ProfileContainsSamePasswordFormsAsVerifier(int index) { std::vector<std::unique_ptr<PasswordForm>> verifier_forms = GetLogins(GetVerifierPasswordStore()); std::vector<std::unique_ptr<PasswordForm>> forms = GetLogins(GetPasswordStore(index)); ClearSyncDateField(&forms); std::ostringstream mismatch_details_stream; bool is_matching = password_manager::ContainsEqualPasswordFormsUnordered( verifier_forms, forms, &mismatch_details_stream); if (!is_matching) { VLOG(1) << "Profile " << index << " does not contain the same Password forms as Verifier Profile."; VLOG(1) << mismatch_details_stream.str(); } return is_matching; } bool ProfilesContainSamePasswordForms(int index_a, int index_b) { std::vector<std::unique_ptr<PasswordForm>> forms_a = GetLogins(GetPasswordStore(index_a)); std::vector<std::unique_ptr<PasswordForm>> forms_b = GetLogins(GetPasswordStore(index_b)); ClearSyncDateField(&forms_a); ClearSyncDateField(&forms_b); std::ostringstream mismatch_details_stream; bool is_matching = password_manager::ContainsEqualPasswordFormsUnordered( forms_a, forms_b, &mismatch_details_stream); if (!is_matching) { VLOG(1) << "Password forms in Profile " << index_a << " (listed as 'expected forms' below)" << " do not match those in Profile " << index_b << " (listed as 'actual forms' below)"; VLOG(1) << mismatch_details_stream.str(); } return is_matching; } bool AllProfilesContainSamePasswordFormsAsVerifier() { for (int i = 0; i < test()->num_clients(); ++i) { if (!ProfileContainsSamePasswordFormsAsVerifier(i)) { DVLOG(1) << "Profile " << i << " does not contain the same password" " forms as the verifier."; return false; } } return true; } bool AllProfilesContainSamePasswordForms() { for (int i = 1; i < test()->num_clients(); ++i) { if (!ProfilesContainSamePasswordForms(0, i)) { DVLOG(1) << "Profile " << i << " does not contain the same password" " forms as Profile 0."; return false; } } return true; } int GetPasswordCount(int index) { return GetLogins(GetPasswordStore(index)).size(); } int GetVerifierPasswordCount() { return GetLogins(GetVerifierPasswordStore()).size(); } PasswordForm CreateTestPasswordForm(int index) { PasswordForm form; form.signon_realm = kFakeSignonRealm; form.origin = GURL(base::StringPrintf(kIndexedFakeOrigin, index)); form.username_value = base::ASCIIToUTF16(base::StringPrintf("username%d", index)); form.password_value = base::ASCIIToUTF16(base::StringPrintf("password%d", index)); form.date_created = base::Time::Now(); return form; } } // namespace passwords_helper SamePasswordFormsChecker::SamePasswordFormsChecker() : MultiClientStatusChangeChecker( sync_datatype_helper::test()->GetSyncServices()), in_progress_(false), needs_recheck_(false) {} // This method needs protection against re-entrancy. // // This function indirectly calls GetLogins(), which starts a RunLoop on the UI // thread. This can be a problem, since the next task to execute could very // well contain a ProfileSyncService::OnStateChanged() event, which would // trigger another call to this here function, and start another layer of // nested RunLoops. That makes the StatusChangeChecker's Quit() method // ineffective. // // The work-around is to not allow re-entrancy. But we can't just drop // IsExitConditionSatisifed() calls if one is already in progress. Instead, we // set a flag to ask the current execution of IsExitConditionSatisfied() to be // re-run. This ensures that the return value is always based on the most // up-to-date state. bool SamePasswordFormsChecker::IsExitConditionSatisfied() { if (in_progress_) { LOG(WARNING) << "Setting flag and returning early to prevent nesting."; needs_recheck_ = true; return false; } // Keep retrying until we get a good reading. bool result = false; in_progress_ = true; do { needs_recheck_ = false; result = passwords_helper::AllProfilesContainSamePasswordForms(); } while (needs_recheck_); in_progress_ = false; return result; } std::string SamePasswordFormsChecker::GetDebugMessage() const { return "Waiting for matching passwords"; } SamePasswordFormsAsVerifierChecker::SamePasswordFormsAsVerifierChecker(int i) : SingleClientStatusChangeChecker( sync_datatype_helper::test()->GetSyncService(i)), index_(i), in_progress_(false), needs_recheck_(false) { } // This method uses the same re-entrancy prevention trick as // the SamePasswordFormsChecker. bool SamePasswordFormsAsVerifierChecker::IsExitConditionSatisfied() { if (in_progress_) { LOG(WARNING) << "Setting flag and returning early to prevent nesting."; needs_recheck_ = true; return false; } // Keep retrying until we get a good reading. bool result = false; in_progress_ = true; do { needs_recheck_ = false; result = passwords_helper::ProfileContainsSamePasswordFormsAsVerifier(index_); } while (needs_recheck_); in_progress_ = false; return result; } std::string SamePasswordFormsAsVerifierChecker::GetDebugMessage() const { return "Waiting for passwords to match verifier"; }
9,991
3,095
#define HL_NAME(n) hlimgui_##n #include <hl.h> #include "imgui/imgui.h" #include "utils.h" #include <string> typedef struct { float x; float y; float u; float v; float r; float g; float b; float a; } HeapVertex; static vclosure* s_render_function = nullptr; void renderDrawLists(ImDrawData* draw_data) { if (s_render_function == nullptr) { return; } // create the hl array passed to the hl render function varray* hl_cmd_list = hl_alloc_array(&hlt_dynobj, draw_data->CmdListsCount); vdynobj** hl_cmd_list_ptr = hl_aptr(hl_cmd_list, vdynobj*); for (int n = 0; n < draw_data->CmdListsCount; n++) { const ImDrawList* cmd_list = draw_data->CmdLists[n]; const ImDrawIdx* idx_buffer = &cmd_list->IdxBuffer.front(); // create the hl dynamic vdynobj* hl_cmd_list = hl_alloc_dynobj(); hl_cmd_list_ptr[n] = hl_cmd_list; // create vertex buffer int nb_vertex = cmd_list->VtxBuffer.size(); int vertex_buffer_size = sizeof(HeapVertex) * nb_vertex; HeapVertex* vertex_buffer = (HeapVertex*)hl_alloc_bytes(vertex_buffer_size); for (int v = 0; v < nb_vertex; v++) { auto& hl_vertex = vertex_buffer[v]; const auto& imgui_vertex = cmd_list->VtxBuffer[v]; hl_vertex.x = imgui_vertex.pos.x - draw_data->DisplayPos.x; hl_vertex.y = imgui_vertex.pos.y - draw_data->DisplayPos.y; hl_vertex.u = imgui_vertex.uv.x; hl_vertex.v = imgui_vertex.uv.y; convertColor(imgui_vertex.col, hl_vertex.r, hl_vertex.g, hl_vertex.b, hl_vertex.a); } // store the vertex buffer in the dynamic hl_dyn_setp((vdynamic*)hl_cmd_list, hl_hash_utf8("vertex_buffer"), &hlt_bytes, vertex_buffer); // store the vertex buffer size hl_dyn_seti((vdynamic*)hl_cmd_list, hl_hash_utf8("vertex_buffer_size"), &hlt_i32, vertex_buffer_size); // create the array for command buffer varray* hl_cmd_buffers = hl_alloc_array(&hlt_dynobj, cmd_list->CmdBuffer.size()); vdynobj** hl_cmd_buffers_ptr = hl_aptr(hl_cmd_buffers, vdynobj*); for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.size(); cmd_i++) { const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i]; // create the hl dynamic to store the cmd buffer vdynobj* hl_cmd_buffer = hl_alloc_dynobj(); hl_cmd_buffers_ptr[cmd_i] = hl_cmd_buffer; // store the texture id vobj* tex_id = (vobj*)pcmd->TextureId; if (tex_id == NULL) hl_dyn_setp((vdynamic*)hl_cmd_buffer, hl_hash_utf8("texture_id"), &hlt_dyn, NULL); else hl_dyn_setp((vdynamic*)hl_cmd_buffer, hl_hash_utf8("texture_id"), tex_id->t, pcmd->TextureId); // create the index buffer int index_buffer_size = sizeof(ImDrawIdx) * pcmd->ElemCount; vbyte* index_buffer = hl_copy_bytes((vbyte*)idx_buffer, index_buffer_size); // store the index buffer hl_dyn_setp((vdynamic*)hl_cmd_buffer, hl_hash_utf8("index_buffer"), &hlt_bytes, index_buffer); // store the index buffer size hl_dyn_seti((vdynamic*)hl_cmd_buffer, hl_hash_utf8("index_buffer_size"), &hlt_i32, index_buffer_size); // store the clipping rect hl_dyn_seti((vdynamic*)hl_cmd_buffer, hl_hash_utf8("clip_left"), &hlt_i32, int(pcmd->ClipRect.x - draw_data->DisplayPos.x)); hl_dyn_seti((vdynamic*)hl_cmd_buffer, hl_hash_utf8("clip_top"), &hlt_i32, int(pcmd->ClipRect.y - draw_data->DisplayPos.y)); hl_dyn_seti((vdynamic*)hl_cmd_buffer, hl_hash_utf8("clip_width"), &hlt_i32, int(pcmd->ClipRect.z - pcmd->ClipRect.x)); hl_dyn_seti((vdynamic*)hl_cmd_buffer, hl_hash_utf8("clip_height"), &hlt_i32, int(pcmd->ClipRect.w - pcmd->ClipRect.y)); idx_buffer += pcmd->ElemCount; } // store the command buffer array hl_dyn_setp((vdynamic*)hl_cmd_list, hl_hash_utf8("draw_objects"), &hlt_array, hl_cmd_buffers); } vdynamic* param = (vdynamic*)hl_alloc_dynobj(); hl_dyn_setp(param, hl_hash_utf8("cmd_list"), &hlt_array, hl_cmd_list); vdynamic* args[1]; args[0] = param; hl_dyn_call(s_render_function, args, 1); } HL_PRIM vdynamic* HL_NAME(initialize)(vclosure* render_fn) { ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); // set render draw function s_render_function = render_fn; hl_add_root(&s_render_function); // create default font texture buffer io.Fonts->AddFontDefault(); unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); vbyte* buffer = hl_copy_bytes(pixels, width*height*4); vdynamic* font_info = (vdynamic*)hl_alloc_dynobj(); hl_dyn_setp(font_info, hl_hash_utf8("buffer"), &hlt_bytes, buffer); hl_dyn_seti(font_info, hl_hash_utf8("width"), &hlt_i32, width); hl_dyn_seti(font_info, hl_hash_utf8("height"), &hlt_i32, height); io.Fonts->ClearTexData(); for (int key = 0; key < ImGuiKey_COUNT; key++) { io.KeyMap[key] = key; } return font_info; } HL_PRIM void HL_NAME(set_font_texture)(ImTextureID texture_id) { ImGuiIO& io = ImGui::GetIO(); io.Fonts->SetTexID(texture_id); } HL_PRIM void HL_NAME(set_key_state)(int key, bool down) { ImGuiIO& io = ImGui::GetIO(); io.KeysDown[key] = down; } HL_PRIM void HL_NAME(set_special_key_state)(bool shift, bool ctrl, bool alt, bool super) { ImGuiIO& io = ImGui::GetIO(); io.KeyShift = shift; io.KeyCtrl = ctrl; io.KeyAlt = alt; io.KeySuper = super; } HL_PRIM void HL_NAME(add_key_char)(int c) { ImGuiIO& io = ImGui::GetIO(); io.AddInputCharacter(c); } HL_PRIM void HL_NAME(set_events)(float dt, float mouse_x, float mouse_y, float wheel, bool left_click, bool right_click) { ImGuiIO& io = ImGui::GetIO(); io.MousePos = ImVec2(mouse_x,mouse_y); io.MouseWheel = wheel; io.MouseDown[0] = left_click; io.MouseDown[1] = right_click; } HL_PRIM void HL_NAME(set_display_size)(int display_width, int display_height) { ImGuiIO& io = ImGui::GetIO(); io.DisplaySize = ImVec2(float(display_width), float(display_height)); } HL_PRIM vdynamic* HL_NAME(get_style)() { return getHLFromImGuiStyle(ImGui::GetStyle()); } HL_PRIM void HL_NAME(set_style)(vdynamic* hl_style) { if (hl_style != nullptr) { ImGui::GetStyle() = getImGuiStyleFromHL(hl_style); } } HL_PRIM void HL_NAME(new_frame)() { ImGui::NewFrame(); } HL_PRIM void HL_NAME(end_frame)() { ImGui::EndFrame(); } HL_PRIM void HL_NAME(render)() { ImGui::Render(); ImDrawData* draw_data = ImGui::GetDrawData(); renderDrawLists(draw_data); } DEFINE_PRIM(_DYN, initialize, _FUN(_VOID, _DYN)); DEFINE_PRIM(_VOID, set_font_texture, _DYN); DEFINE_PRIM(_VOID, set_key_state, _I32 _BOOL); DEFINE_PRIM(_VOID, add_key_char, _I32); DEFINE_PRIM(_VOID, set_events, _F32 _F32 _F32 _F32 _BOOL _BOOL); DEFINE_PRIM(_VOID, set_special_key_state, _BOOL _BOOL _BOOL _BOOL); DEFINE_PRIM(_VOID, set_display_size, _I32 _I32); DEFINE_PRIM(_DYN, get_style, _NO_ARG); DEFINE_PRIM(_VOID, set_style, _DYN); DEFINE_PRIM(_VOID, new_frame, _NO_ARG); DEFINE_PRIM(_VOID, end_frame, _NO_ARG); DEFINE_PRIM(_VOID, render, _NO_ARG);
6,770
3,032
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: System.ValueType #include "System/ValueType.hpp" // Including type: System.IntPtr #include "System/IntPtr.hpp" // Completed includes // Type namespace: UnityEngine.Animations namespace UnityEngine::Animations { // Forward declaring type: AnimationHumanStream struct AnimationHumanStream; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE(::UnityEngine::Animations::AnimationHumanStream, "UnityEngine.Animations", "AnimationHumanStream"); // Type namespace: UnityEngine.Animations namespace UnityEngine::Animations { // Size: 0x8 #pragma pack(push, 1) // WARNING Layout: Sequential may not be correctly taken into account! // Autogenerated type: UnityEngine.Animations.AnimationHumanStream // [TokenAttribute] Offset: FFFFFFFF // [MovedFromAttribute] Offset: 5A6440 // [NativeHeaderAttribute] Offset: 5A6440 // [NativeHeaderAttribute] Offset: 5A6440 // [RequiredByNativeCodeAttribute] Offset: 5A6440 struct AnimationHumanStream/*, public ::System::ValueType*/ { public: public: // private System.IntPtr stream // Size: 0x8 // Offset: 0x0 ::System::IntPtr stream; // Field size check static_assert(sizeof(::System::IntPtr) == 0x8); public: // Creating value type constructor for type: AnimationHumanStream constexpr AnimationHumanStream(::System::IntPtr stream_ = {}) noexcept : stream{stream_} {} // Creating interface conversion operator: operator ::System::ValueType operator ::System::ValueType() noexcept { return *reinterpret_cast<::System::ValueType*>(this); } // Creating conversion operator: operator ::System::IntPtr constexpr operator ::System::IntPtr() const noexcept { return stream; } // Get instance field reference: private System.IntPtr stream ::System::IntPtr& dyn_stream(); }; // UnityEngine.Animations.AnimationHumanStream #pragma pack(pop) static check_size<sizeof(AnimationHumanStream), 0 + sizeof(::System::IntPtr)> __UnityEngine_Animations_AnimationHumanStreamSizeCheck; static_assert(sizeof(AnimationHumanStream) == 0x8); } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
2,402
733
/******************************************************************************* * Copyright (C) 2019-2021 Intel Corporation * * SPDX-License-Identifier: MIT ******************************************************************************/ #include "vaapi_context.h" #include "inference_backend/logger.h" #include "utils.h" #include <cassert> #include <vector> #include <fcntl.h> #include <unistd.h> using namespace InferenceBackend; VaApiContext::VaApiContext(VADisplay va_display) : _display(va_display) { create_config_and_contexts(); create_supported_pixel_formats(); assert(_va_config_id != VA_INVALID_ID && "Failed to initalize VaApiContext. Expected valid VAConfigID."); assert(_va_context_id != VA_INVALID_ID && "Failed to initalize VaApiContext. Expected valid VAContextID."); } VaApiContext::VaApiContext(VaApiDisplayPtr va_display_ptr) : _display_storage(va_display_ptr), _display(va_display_ptr.get()) { create_config_and_contexts(); create_supported_pixel_formats(); assert(_va_config_id != VA_INVALID_ID && "Failed to initalize VaApiContext. Expected valid VAConfigID."); assert(_va_context_id != VA_INVALID_ID && "Failed to initalize VaApiContext. Expected valid VAContextID."); } VaApiContext::VaApiContext(const std::string &device) { _display_storage = vaApiCreateVaDisplay(Utils::getRelativeGpuDeviceIndex(device)); _display = VaDpyWrapper::fromHandle(_display_storage.get()); create_config_and_contexts(); create_supported_pixel_formats(); assert(_va_config_id != VA_INVALID_ID && "Failed to initalize VaApiContext. Expected valid VAConfigID."); assert(_va_context_id != VA_INVALID_ID && "Failed to initalize VaApiContext. Expected valid VAContextID."); } VaApiContext::~VaApiContext() { auto vtable = _display.drvVtable(); auto ctx = _display.drvCtx(); if (_va_context_id != VA_INVALID_ID) { vtable.vaDestroyContext(ctx, _va_context_id); } if (_va_config_id != VA_INVALID_ID) { vtable.vaDestroyConfig(ctx, _va_config_id); } } VAContextID VaApiContext::Id() const { return _va_context_id; } VaDpyWrapper VaApiContext::Display() const { return _display; } VADisplay VaApiContext::DisplayRaw() const { return _display.raw(); } int VaApiContext::RTFormat() const { return _rt_format; } bool VaApiContext::IsPixelFormatSupported(int format) const { return _supported_pixel_formats.count(format); } /** * Creates config, va context, and sets the driver context using the internal VADisplay. * Setting the VADriverContextP, VAConfigID, and VAContextID to the corresponding variables. * * @pre _display must be set and initialized. * @post _va_config_id is set. * @post _va_context_id is set. * * @throw std::invalid_argument if the VaDpyWrapper is not created, runtime format not supported, unable to get config * attributes, unable to create config, or unable to create context. */ void VaApiContext::create_config_and_contexts() { assert(_display); auto ctx = _display.drvCtx(); auto vtable = _display.drvVtable(); VAConfigAttrib format_attrib; format_attrib.type = VAConfigAttribRTFormat; VA_CALL(vtable.vaGetConfigAttributes(ctx, VAProfileNone, VAEntrypointVideoProc, &format_attrib, 1)); if (not(format_attrib.value & _rt_format)) throw std::invalid_argument("Could not create context. Runtime format is not supported."); VAConfigAttrib attrib; attrib.type = VAConfigAttribRTFormat; attrib.value = _rt_format; VA_CALL(vtable.vaCreateConfig(ctx, VAProfileNone, VAEntrypointVideoProc, &attrib, 1, &_va_config_id)); if (_va_config_id == 0) { throw std::invalid_argument("Could not create VA config. Cannot initialize VaApiContext without VA config."); } VA_CALL(vtable.vaCreateContext(ctx, _va_config_id, 0, 0, VA_PROGRESSIVE, nullptr, 0, &_va_context_id)); if (_va_context_id == 0) { throw std::invalid_argument("Could not create VA context. Cannot initialize VaApiContext without VA context."); } } /** * Creates a set of formats supported by image. * * @pre _display must be set and initialized. * @post _supported_pixel_formats is set. * * @throw std::runtime_error if vaQueryImageFormats return non success code */ void VaApiContext::create_supported_pixel_formats() { assert(_display); auto ctx = _display.drvCtx(); auto vtable = _display.drvVtable(); std::vector<VAImageFormat> image_formats(ctx->max_image_formats); int size = 0; VA_CALL(vtable.vaQueryImageFormats(ctx, image_formats.data(), &size)); for (int i = 0; i < size; i++) _supported_pixel_formats.insert(image_formats[i].fourcc); }
4,709
1,567
/** * This file has been modified from its orginal sources. * * Copyright (c) 2012 Software in the Public Interest Inc (SPI) * Copyright (c) 2012 David Pratt * * 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. * *** * Copyright (c) 2008-2012 Appcelerator Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ #include "environment_binding.h" #include <tideutils/environment_utils.h> namespace tide { ValueRef EnvironmentBinding::Get(const char *name) { return Value::NewString(EnvironmentUtils::Get(name)); } SharedStringList EnvironmentBinding::GetPropertyNames() { std::map<std::string, std::string> env = EnvironmentUtils::GetEnvironment(); SharedStringList keys = new StringList(); std::map<std::string, std::string>::iterator iter = env.begin(); for (; iter != env.end(); iter++) { keys->push_back(new std::string(iter->first)); } return keys; } void EnvironmentBinding::Set(const char *name, ValueRef value) { if (value->IsString()) { EnvironmentUtils::Set(name, value->ToString()); } } SharedString EnvironmentBinding::DisplayString(int levels) { std::map<std::string, std::string> env = EnvironmentUtils::GetEnvironment(); std::map<std::string, std::string>::iterator iter = env.begin(); SharedString str = new std::string(); for (; iter != env.end(); iter++) { (*str) += iter->first + "=" + iter->second + ","; } return str; } }
2,594
756
/* * Copyright 2009, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // collada_edge.cpp : Defines the entry point for the console application. #include "precompile.h" #include "conditioner.h" #include <cstdio> static const char *usage = "\nUsage: ColladaEdgeConditioner <infile.dae> <outifle.dae> [ options ]\n\n\ Options:\n\ -sharpEdgeThreshold t : sharp edge threshold defined by dihedral \n\ angle. Edges with a angle smaller than t\n\ will be defined as a sharp edge.\n\ -sharpEdgeColor r,g,b : color of addtional edges.\n\ default value is 1,0,0 .(no space)\n\n\ ColladaEdgeConditioner checks all polygon edges in <infile.dae> and add\n\ addtional edges to the model if normal angle of certain edge is larger\n\ than the pre-defined threshold.\n"; int wmain(int argc, wchar_t **argv) { wchar_t* input_file = NULL; wchar_t* output_file = NULL; Options options; if (argc < 3) { printf("%s", usage); return -1; } int file_count = 0; for (int i = 1; i < argc; i++) { if (wcscmp(argv[i], L"-sharpEdgeThreshold") == 0) { if (++i < argc) { options.enable_soften_edge = true; options.soften_edge_threshold = static_cast<float>(_wtof(argv[i])); } } else if (wcscmp(argv[i], L"-sharpEdgeColor") == 0) { if (++i < argc) { int r, g, b; if (swscanf_s(argv[i], L"%d,%d,%d", &r, &g, &b) != 3) { printf("Invalid -sharpEdgeColor. Should be -sharpEdgeColor=x,y,z\n"); return -1; } options.sharp_edge_color = Vector3(static_cast<float>(r), static_cast<float>(g), static_cast<float>(b)); } } else if (file_count < 2) { ++file_count; if (file_count == 1) input_file = argv[i]; else output_file = argv[i]; } } bool result = Condition(input_file, output_file, options); return 0; }
3,508
1,209
// Generated by Haxe 4.0.5 #include <hxcpp.h> #ifndef INCLUDED_kha_graphics4_ConstantLocation #include <hxinc/kha/graphics4/ConstantLocation.h> #endif #ifndef INCLUDED_kha_kore_graphics4_ConstantLocation #include <hxinc/kha/kore/graphics4/ConstantLocation.h> #endif HX_DEFINE_STACK_FRAME(_hx_pos_8a98049bf91d5975_10_new,"kha.kore.graphics4.ConstantLocation","new",0x99ddedbd,"kha.kore.graphics4.ConstantLocation.new","kha/kore/graphics4/ConstantLocation.hx",10,0x6d842492) namespace kha{ namespace kore{ namespace graphics4{ void ConstantLocation_obj::__construct(){ HX_STACKFRAME(&_hx_pos_8a98049bf91d5975_10_new) } Dynamic ConstantLocation_obj::__CreateEmpty() { return new ConstantLocation_obj; } void *ConstantLocation_obj::_hx_vtable = 0; Dynamic ConstantLocation_obj::__Create(hx::DynamicArray inArgs) { hx::ObjectPtr< ConstantLocation_obj > _hx_result = new ConstantLocation_obj(); _hx_result->__construct(); return _hx_result; } bool ConstantLocation_obj::_hx_isInstanceOf(int inClassId) { return inClassId==(int)0x00000001 || inClassId==(int)0x3f26b36b; } static ::kha::graphics4::ConstantLocation_obj _hx_kha_kore_graphics4_ConstantLocation__hx_kha_graphics4_ConstantLocation= { }; void *ConstantLocation_obj::_hx_getInterface(int inHash) { switch(inHash) { case (int)0x9aec187e: return &_hx_kha_kore_graphics4_ConstantLocation__hx_kha_graphics4_ConstantLocation; } #ifdef HXCPP_SCRIPTABLE return super::_hx_getInterface(inHash); #else return 0; #endif } hx::ObjectPtr< ConstantLocation_obj > ConstantLocation_obj::__new() { hx::ObjectPtr< ConstantLocation_obj > __this = new ConstantLocation_obj(); __this->__construct(); return __this; } hx::ObjectPtr< ConstantLocation_obj > ConstantLocation_obj::__alloc(hx::Ctx *_hx_ctx) { ConstantLocation_obj *__this = (ConstantLocation_obj*)(hx::Ctx::alloc(_hx_ctx, sizeof(ConstantLocation_obj), false, "kha.kore.graphics4.ConstantLocation")); *(void **)__this = ConstantLocation_obj::_hx_vtable; __this->__construct(); return __this; } ConstantLocation_obj::ConstantLocation_obj() { } #ifdef HXCPP_SCRIPTABLE static hx::StorageInfo *ConstantLocation_obj_sMemberStorageInfo = 0; static hx::StaticInfo *ConstantLocation_obj_sStaticStorageInfo = 0; #endif hx::Class ConstantLocation_obj::__mClass; void ConstantLocation_obj::__register() { ConstantLocation_obj _hx_dummy; ConstantLocation_obj::_hx_vtable = *(void **)&_hx_dummy; hx::Static(__mClass) = new hx::Class_obj(); __mClass->mName = HX_("kha.kore.graphics4.ConstantLocation",4b,4b,13,b9); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &hx::Class_obj::GetNoStaticField; __mClass->mSetStaticField = &hx::Class_obj::SetNoStaticField; __mClass->mStatics = hx::Class_obj::dupFunctions(0 /* sStaticFields */); __mClass->mMembers = hx::Class_obj::dupFunctions(0 /* sMemberFields */); __mClass->mCanCast = hx::TCanCast< ConstantLocation_obj >; #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = ConstantLocation_obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = ConstantLocation_obj_sStaticStorageInfo; #endif hx::_hx_RegisterClass(__mClass->mName, __mClass); } } // end namespace kha } // end namespace kore } // end namespace graphics4
3,361
1,327
/* * Copyright (C) 2005, 2006 Apple Inc. All rights reserved. * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies) * Copyright (C) 2010 Igalia S.L. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of Apple Inc. ("Apple") 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 APPLE AND ITS 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 APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "ActivateFonts.h" #include "InjectedBundleUtilities.h" #include <fontconfig/fontconfig.h> #include <gtk/gtk.h> #include <wtf/glib/GLibUtilities.h> #include <wtf/glib/GUniquePtr.h> namespace WTR { void initializeGtkSettings() { GtkSettings* settings = gtk_settings_get_default(); if (!settings) return; g_object_set(settings, "gtk-xft-dpi", 98304, "gtk-xft-antialias", 1, "gtk-xft-hinting", 0, "gtk-font-name", "Liberation Sans 12", "gtk-xft-rgba", "none", nullptr); } CString getOutputDir() { const char* webkitOutputDir = g_getenv("WEBKIT_OUTPUTDIR"); if (webkitOutputDir) return webkitOutputDir; CString topLevelPath = WTR::topLevelPath(); GUniquePtr<char> outputDir(g_build_filename(topLevelPath.data(), "WebKitBuild", nullptr)); return outputDir.get(); } static CString getFontsPath() { // Try flatpak sandbox path. GUniquePtr<char>fontsPath(g_build_filename("/usr", "share", "webkitgtk-test-fonts", NULL)); if (g_file_test(fontsPath.get(), static_cast<GFileTest>(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR))) return fontsPath.get(); CString webkitOutputDir = getOutputDir(); fontsPath.reset(g_build_filename(webkitOutputDir.data(), "DependenciesGTK", "Root", "webkitgtk-test-fonts", nullptr)); if (g_file_test(fontsPath.get(), static_cast<GFileTest>(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR))) return fontsPath.get(); // Try alternative fonts path. fontsPath.reset(g_build_filename(webkitOutputDir.data(), "webkitgtk-test-fonts", NULL)); if (g_file_test(fontsPath.get(), static_cast<GFileTest>(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR))) return fontsPath.get(); return CString(); } void initializeFontConfigSetting() { if (g_getenv("WEBKIT_SKIP_WEBKITTESTRUNNER_FONTCONFIG_INITIALIZATION")) return; FcInit(); // If a test resulted a font being added or removed via the @font-face rule, then // we want to reset the FontConfig configuration to prevent it from affecting other tests. static int numFonts = 0; FcFontSet* appFontSet = FcConfigGetFonts(0, FcSetApplication); if (appFontSet && numFonts && appFontSet->nfont == numFonts) return; // Load our configuration file, which sets up proper aliases for family // names like sans, serif and monospace. FcConfig* config = FcConfigCreate(); GUniquePtr<gchar> fontConfigFilename(g_build_filename(FONTS_CONF_DIR, "fonts.conf", nullptr)); if (!g_file_test(fontConfigFilename.get(), G_FILE_TEST_IS_REGULAR)) g_error("Cannot find fonts.conf at %s\n", fontConfigFilename.get()); if (!FcConfigParseAndLoad(config, reinterpret_cast<FcChar8*>(fontConfigFilename.get()), true)) g_error("Couldn't load font configuration file from: %s", fontConfigFilename.get()); CString fontsPath = getFontsPath(); if (fontsPath.isNull()) g_error("Could not locate test fonts at %s. Is WEBKIT_TOP_LEVEL set?", fontsPath.data()); GUniquePtr<GDir> fontsDirectory(g_dir_open(fontsPath.data(), 0, nullptr)); while (const char* directoryEntry = g_dir_read_name(fontsDirectory.get())) { if (!g_str_has_suffix(directoryEntry, ".ttf") && !g_str_has_suffix(directoryEntry, ".otf")) continue; GUniquePtr<gchar> fontPath(g_build_filename(fontsPath.data(), directoryEntry, nullptr)); if (!FcConfigAppFontAddFile(config, reinterpret_cast<const FcChar8*>(fontPath.get()))) g_error("Could not load font at %s!", fontPath.get()); } // Ahem is used by many layout tests. GUniquePtr<gchar> ahemFontFilename(g_build_filename(FONTS_CONF_DIR, "AHEM____.TTF", nullptr)); if (!FcConfigAppFontAddFile(config, reinterpret_cast<FcChar8*>(ahemFontFilename.get()))) g_error("Could not load font at %s!", ahemFontFilename.get()); static const char* fontFilenames[] = { "WebKitWeightWatcher100.ttf", "WebKitWeightWatcher200.ttf", "WebKitWeightWatcher300.ttf", "WebKitWeightWatcher400.ttf", "WebKitWeightWatcher500.ttf", "WebKitWeightWatcher600.ttf", "WebKitWeightWatcher700.ttf", "WebKitWeightWatcher800.ttf", "WebKitWeightWatcher900.ttf", 0 }; for (size_t i = 0; fontFilenames[i]; ++i) { GUniquePtr<gchar> fontFilename(g_build_filename(FONTS_CONF_DIR, "..", "..", "fonts", fontFilenames[i], nullptr)); if (!FcConfigAppFontAddFile(config, reinterpret_cast<FcChar8*>(fontFilename.get()))) g_error("Could not load font at %s!", fontFilename.get()); } // A font with no valid Fontconfig encoding to test https://bugs.webkit.org/show_bug.cgi?id=47452 GUniquePtr<gchar> fontWithNoValidEncodingFilename(g_build_filename(FONTS_CONF_DIR, "FontWithNoValidEncoding.fon", nullptr)); if (!FcConfigAppFontAddFile(config, reinterpret_cast<FcChar8*>(fontWithNoValidEncodingFilename.get()))) g_error("Could not load font at %s!", fontWithNoValidEncodingFilename.get()); if (!FcConfigSetCurrent(config)) g_error("Could not set the current font configuration!"); numFonts = FcConfigGetFonts(config, FcSetApplication)->nfont; } void activateFonts() { initializeGtkSettings(); initializeFontConfigSetting(); } void installFakeHelvetica(WKStringRef) { } void uninstallFakeHelvetica() { } }
7,086
2,494
// Problem Code: 1333A #include <iostream> #include <string> #include <vector> using namespace std; void little_artem(int n, int m) { vector<string> grid(n, string(m, 'B')); grid[0][0] = 'W'; for (int i = 0; i < n; i++) cout << grid[i] << endl; } int main() { int t; cin >> t; while (t--) { int n, m; cin >> n >> m; little_artem(n, m); } return 0; }
369
176
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // // Copyright (c) Microsoft Corporation. All rights reserved #include "pch.h" #include "ThumbnailGenerator.h" #include "ExceptionPolicy.h" using namespace concurrency; using namespace std; using namespace Platform; using namespace Platform::Collections; using namespace Windows::Foundation::Collections; using namespace Windows::Graphics::Imaging; using namespace Windows::Storage; using namespace Windows::Storage::Streams; using namespace Windows::Storage::FileProperties; using namespace Hilo; // See http://go.microsoft.com/fwlink/?LinkId=267275 for info about Hilo's implementation of tiles. const unsigned int ThumbnailSize = 270; const wstring ThumbnailImagePrefix = L"thumbImage_"; ThumbnailGenerator::ThumbnailGenerator(std::shared_ptr<ExceptionPolicy> policy) : m_exceptionPolicy(policy) { } task<Vector<StorageFile^>^> ThumbnailGenerator::Generate( IVector<StorageFile^>^ files, StorageFolder^ thumbnailsFolder) { vector<task<StorageFile^>> thumbnailTasks; unsigned int imageCounter = 0; for (auto imageFile : files) { wstringstream localFileName; localFileName << ThumbnailImagePrefix << imageCounter++ << ".jpg"; thumbnailTasks.push_back( CreateLocalThumbnailAsync( thumbnailsFolder, imageFile, ref new String(localFileName.str().c_str()), ThumbnailSize, m_exceptionPolicy)); } return when_all(begin(thumbnailTasks), end(thumbnailTasks)).then( [](vector<StorageFile^> files) { auto result = ref new Vector<StorageFile^>(); for (auto file : files) { if (file != nullptr) { result->Append(file); } } return result; }); } task<StorageFile^> ThumbnailGenerator::CreateLocalThumbnailAsync( StorageFolder^ folder, StorageFile^ imageFile, String^ localFileName, unsigned int thumbSize, std::shared_ptr<ExceptionPolicy> exceptionPolicy) { auto createThumbnail = create_task( CreateThumbnailFromPictureFileAsync(imageFile, thumbSize)); return createThumbnail.then([exceptionPolicy, folder, localFileName]( task<InMemoryRandomAccessStream^> createdThumbnailTask) { InMemoryRandomAccessStream^ createdThumbnail; try { createdThumbnail = createdThumbnailTask.get(); } catch(Exception^ ex) { exceptionPolicy->HandleException(ex); // If we have any exceptions we won't return the results // of this task, but instead nullptr. Downstream // tasks will need to account for this. return create_task_from_result<StorageFile^>(nullptr); } return InternalSaveToFile(folder, createdThumbnail, localFileName); }); } task<StorageFile^> ThumbnailGenerator::InternalSaveToFile( StorageFolder^ thumbnailsFolder, InMemoryRandomAccessStream^ stream, Platform::String^ filename) { auto imageFile = make_shared<StorageFile^>(nullptr); auto streamReader = ref new DataReader(stream); auto loadStreamTask = create_task( streamReader->LoadAsync(static_cast<unsigned int>(stream->Size))); return loadStreamTask.then( [thumbnailsFolder, filename](unsigned int loadedBytes) { (void)loadedBytes; // Unused parameter return thumbnailsFolder->CreateFileAsync( filename, CreationCollisionOption::ReplaceExisting); }).then([streamReader, imageFile](StorageFile^ thumbnailDestinationFile) { (*imageFile) = thumbnailDestinationFile; auto buffer = streamReader->ReadBuffer( streamReader->UnconsumedBufferLength); return FileIO::WriteBufferAsync(thumbnailDestinationFile, buffer); }).then([imageFile]() { return (*imageFile); }); } task<InMemoryRandomAccessStream^> ThumbnailGenerator::CreateThumbnailFromPictureFileAsync( StorageFile^ sourceFile, unsigned int thumbSize) { (void)thumbSize; // Unused parameter auto decoder = make_shared<BitmapDecoder^>(nullptr); auto pixelProvider = make_shared<PixelDataProvider^>(nullptr); auto resizedImageStream = ref new InMemoryRandomAccessStream(); auto createThumbnail = create_task( sourceFile->GetThumbnailAsync( ThumbnailMode::PicturesView, ThumbnailSize)); return createThumbnail.then([](StorageItemThumbnail^ thumbnail) { IRandomAccessStream^ imageFileStream = static_cast<IRandomAccessStream^>(thumbnail); return BitmapDecoder::CreateAsync(imageFileStream); }).then([decoder](BitmapDecoder^ createdDecoder) { (*decoder) = createdDecoder; return createdDecoder->GetPixelDataAsync( BitmapPixelFormat::Rgba8, BitmapAlphaMode::Straight, ref new BitmapTransform(), ExifOrientationMode::IgnoreExifOrientation, ColorManagementMode::ColorManageToSRgb); }).then([pixelProvider, resizedImageStream](PixelDataProvider^ provider) { (*pixelProvider) = provider; return BitmapEncoder::CreateAsync( BitmapEncoder::JpegEncoderId, resizedImageStream); }).then([pixelProvider, decoder](BitmapEncoder^ createdEncoder) { createdEncoder->SetPixelData(BitmapPixelFormat::Rgba8, BitmapAlphaMode::Straight, (*decoder)->PixelWidth, (*decoder)->PixelHeight, (*decoder)->DpiX, (*decoder)->DpiY, (*pixelProvider)->DetachPixelData()); return createdEncoder->FlushAsync(); }).then([resizedImageStream] { resizedImageStream->Seek(0); return resizedImageStream; }); }
6,046
1,667
/* * Stopwatch.cpp * * Created on: Jul 14, 2014 * Author: Pimenta */ // this #include "metallicar_time.hpp" namespace metallicar { Stopwatch::Stopwatch() : started(false), paused(false), initialTime(0), pauseTime(0) { } void Stopwatch::start() { started = true; paused = false; initialTime = Time::get(); } void Stopwatch::pause() { if (!paused) { paused = true; pauseTime = Time::get(); } } void Stopwatch::resume() { if (paused) { paused = false; initialTime += Time::get() - pauseTime; } } void Stopwatch::reset() { started = false; } uint32_t Stopwatch::time() { if (!started) return 0; if (paused) return pauseTime - initialTime; return Time::get() - initialTime; } } // namespace metallicar
817
309
#include <stdio.h> #include "ResourceFormatter/ResourceFormatterText.hpp" ResourceFormatterText::ResourceFormatterText() { } int ResourceFormatterText::decode(const std::vector<uint8_t> &data, std::ostream &out) { for(size_t i = 0; i < data.size(); i++) { out << static_cast<char>(data[i]); } return 0; }
330
113
/************************************************************************** * Copyright 2017-2018 NextCash, LLC * * Contributors : * * Curtis Ellis <curtis@nextcash.tech> * * Distributed under the MIT software license, see the accompanying * * file license.txt or http://www.opensource.org/licenses/mit-license.php * **************************************************************************/ #include "digest.hpp" #include "endian.hpp" #include "math.hpp" #include "log.hpp" #include "stream.hpp" #include "buffer.hpp" #include <cstdint> #include <cstring> #include <vector> #define NEXTCASH_DIGEST_LOG_NAME "Digest" namespace NextCash { namespace CRC32 { static const uint32_t table[256] = { 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d }; } void Digest::crc32(InputStream *pInput, stream_size pInputLength, OutputStream *pOutput) { uint32_t result = 0xffffffff; stream_size remaining = pInputLength; while(remaining--) result = (result >> 8) ^ CRC32::table[(result & 0xFF) ^ pInput->readByte()]; result ^= 0xffffffff; pOutput->writeUnsignedInt(Endian::convert(result, Endian::BIG)); } uint32_t Digest::crc32(const char *pText) { uint32_t result = 0xffffffff; unsigned int offset = 0; while(pText[offset]) result = (result >> 8) ^ CRC32::table[(result & 0xFF) ^ pText[offset++]]; return result ^ 0xffffffff; } uint32_t Digest::crc32(const uint8_t *pData, stream_size pSize) { uint32_t result = 0xffffffff; stream_size offset = 0; while(offset < pSize) result = (result >> 8) ^ CRC32::table[(result & 0xFF) ^ pData[offset++]]; return result ^ 0xffffffff; } namespace MD5 { inline int f(int pX, int pY, int pZ) { // XY v not(X) Z return (pX & pY) | (~pX & pZ); } inline int g(int pX, int pY, int pZ) { // XZ v Y not(Z) return (pX & pZ) |(pY & ~pZ); } inline int h(int pX, int pY, int pZ) { // X xor Y xor Z return (pX ^ pY) ^ pZ; } inline int i(int pX, int pY, int pZ) { // Y xor(X v not(Z)) return pY ^ (pX | ~pZ); } inline void round1(int &pA, int pB, int pC, int pD, int pXK, int pS, int pTI) { int step1 = (pA + f(pB, pC, pD) + pXK + pTI); pA = pB + Math::rotateLeft(step1, pS); } inline void round2(int &pA, int pB, int pC, int pD, int pXK, int pS, int pTI) { int step1 = (pA + g(pB, pC, pD) + pXK + pTI); pA = pB + Math::rotateLeft(step1, pS); } inline void round3(int &pA, int pB, int pC, int pD, int pXK, int pS, int pTI) { int step1 = (pA + h(pB, pC, pD) + pXK + pTI); pA = pB + Math::rotateLeft(step1, pS); } inline void round4(int &pA, int pB, int pC, int pD, int pXK, int pS, int pTI) { int step1 = (pA + i(pB, pC, pD) + pXK + pTI); pA = pB + Math::rotateLeft(step1, pS); } // Encodes raw bytes into the 16 integer block inline void encode(uint8_t *pData, int *pBlock) { int i, j; for(i=0,j=0;j<64;i++,j+=4) pBlock[i] = ((int)pData[j]) | (((int)pData[j+1]) << 8) | (((int)pData[j+2]) << 16) | (((int)pData[j+3]) << 24); } // Decodes 16 integer block into raw bytes inline void decode(int *pBlock, uint8_t *pData) { int i, j; for(i=0,j=0;j<64;i++,j+=4) { pData[j] = (uint8_t)(pBlock[i] & 0xff); pData[j+1] = (uint8_t)((pBlock[i] >> 8) & 0xff); pData[j+2] = (uint8_t)((pBlock[i] >> 16) & 0xff); pData[j+3] = (uint8_t)((pBlock[i] >> 24) & 0xff); } } } void Digest::md5(InputStream *pInput, stream_size pInputLength, OutputStream *pOutput) // 128 bit(16 byte) result { uint8_t *data; stream_size dataSize = pInputLength + 9; // Make the data size is congruent to 448, modulo 512 bits(56, 64 modulo bytes) dataSize += (64 - (dataSize % 64)); data = new uint8_t[dataSize]; stream_size offset = pInputLength; pInput->read(data, pInputLength); data[offset++] = 128; // 10000000 - append a one bit and the rest zero bits // Append the rest zero bits if(offset <(dataSize - 1)) std::memset(data + offset, 0, dataSize - offset); // Append the data length as a 64 bit number low order word first int bitLength = pInputLength * 8; data[dataSize - 8] = (uint8_t)(bitLength & 0xff); data[dataSize - 7] = (uint8_t)((bitLength >> 8) & 0xff); data[dataSize - 6] = (uint8_t)((bitLength >> 16) & 0xff); data[dataSize - 5] = (uint8_t)((bitLength >> 24) & 0xff); std::memset((data + dataSize) - 4, 0, 4); // Setup buffers int state[4], a, b, c, d; state[0] = 0x67452301; // A state[1] = 0xEFCDAB89; // B state[2] = 0x98BADCFE; // C state[3] = 0x10325476; // D // Process 16 word(64 byte) blocks of data int blockIndex, blockCount = dataSize / 64; int blockX[16]; for(blockIndex=0;blockIndex<blockCount;blockIndex++) { // Copy current block into blockX MD5::encode(data + (blockIndex * 64), blockX); a = state[0]; b = state[1]; c = state[2]; d = state[3]; // Round 1 - a = b +((a + F(b,c,d) + X[k] + T[i]) <<< s) MD5::round1(a, b, c, d, blockX[ 0], 7, 0xD76AA478); MD5::round1(d, a, b, c, blockX[ 1], 12, 0xE8C7B756); MD5::round1(c, d, a, b, blockX[ 2], 17, 0x242070DB); MD5::round1(b, c, d, a, blockX[ 3], 22, 0xC1BDCEEE); MD5::round1(a, b, c, d, blockX[ 4], 7, 0xF57C0FAF); MD5::round1(d, a, b, c, blockX[ 5], 12, 0x4787C62A); MD5::round1(c, d, a, b, blockX[ 6], 17, 0xA8304613); MD5::round1(b, c, d, a, blockX[ 7], 22, 0xFD469501); MD5::round1(a, b, c, d, blockX[ 8], 7, 0x698098D8); MD5::round1(d, a, b, c, blockX[ 9], 12, 0x8B44F7AF); MD5::round1(c, d, a, b, blockX[10], 17, 0xFFFF5BB1); MD5::round1(b, c, d, a, blockX[11], 22, 0x895CD7BE); MD5::round1(a, b, c, d, blockX[12], 7, 0x6B901122); MD5::round1(d, a, b, c, blockX[13], 12, 0xFD987193); MD5::round1(c, d, a, b, blockX[14], 17, 0xA679438E); MD5::round1(b, c, d, a, blockX[15], 22, 0x49B40821); // Round 2 - a = b +((a + G(b,,d) + X[k] + T[i]) <<< s) MD5::round2(a, b, c, d, blockX[ 1], 5, 0xF61E2562); MD5::round2(d, a, b, c, blockX[ 6], 9, 0xC040B340); MD5::round2(c, d, a, b, blockX[11], 14, 0x265E5A51); MD5::round2(b, c, d, a, blockX[ 0], 20, 0xE9B6C7AA); MD5::round2(a, b, c, d, blockX[ 5], 5, 0xD62F105D); MD5::round2(d, a, b, c, blockX[10], 9, 0x02441453); MD5::round2(c, d, a, b, blockX[15], 14, 0xD8A1E681); MD5::round2(b, c, d, a, blockX[ 4], 20, 0xE7D3FBC8); MD5::round2(a, b, c, d, blockX[ 9], 5, 0x21E1CDE6); MD5::round2(d, a, b, c, blockX[14], 9, 0xC33707D6); MD5::round2(c, d, a, b, blockX[ 3], 14, 0xF4D50D87); MD5::round2(b, c, d, a, blockX[ 8], 20, 0x455A14ED); MD5::round2(a, b, c, d, blockX[13], 5, 0xA9E3E905); MD5::round2(d, a, b, c, blockX[ 2], 9, 0xFCEFA3F8); MD5::round2(c, d, a, b, blockX[ 7], 14, 0x676F02D9); MD5::round2(b, c, d, a, blockX[12], 20, 0x8D2A4C8A); // Round 3 - a = b +((a + H(b,,d) + X[k] + T[i]) <<< s) MD5::round3(a, b, c, d, blockX[ 5], 4, 0xFFFA3942); MD5::round3(d, a, b, c, blockX[ 8], 11, 0x8771F681); MD5::round3(c, d, a, b, blockX[11], 16, 0x6D9D6122); MD5::round3(b, c, d, a, blockX[14], 23, 0xFDE5380C); MD5::round3(a, b, c, d, blockX[ 1], 4, 0xA4BEEA44); MD5::round3(d, a, b, c, blockX[ 4], 11, 0x4BDECFA9); MD5::round3(c, d, a, b, blockX[ 7], 16, 0xF6BB4B60); MD5::round3(b, c, d, a, blockX[10], 23, 0xBEBFBC70); MD5::round3(a, b, c, d, blockX[13], 4, 0x289B7EC6); MD5::round3(d, a, b, c, blockX[ 0], 11, 0xEAA127FA); MD5::round3(c, d, a, b, blockX[ 3], 16, 0xD4EF3085); MD5::round3(b, c, d, a, blockX[ 6], 23, 0x04881D05); MD5::round3(a, b, c, d, blockX[ 9], 4, 0xD9D4D039); MD5::round3(d, a, b, c, blockX[12], 11, 0xE6DB99E5); MD5::round3(c, d, a, b, blockX[15], 16, 0x1FA27CF8); MD5::round3(b, c, d, a, blockX[ 2], 23, 0xC4AC5665); // Round 4 - a = b +((a + I(b,,d) + X[k] + T[i]) <<< s) MD5::round4(a, b, c, d, blockX[ 0], 6, 0xF4292244); MD5::round4(d, a, b, c, blockX[ 7], 10, 0x432AFF97); MD5::round4(c, d, a, b, blockX[14], 15, 0xAB9423A7); MD5::round4(b, c, d, a, blockX[ 5], 21, 0xFC93A039); MD5::round4(a, b, c, d, blockX[12], 6, 0x655B59C3); MD5::round4(d, a, b, c, blockX[ 3], 10, 0x8F0CCC92); MD5::round4(c, d, a, b, blockX[10], 15, 0xFFEFF47D); MD5::round4(b, c, d, a, blockX[ 1], 21, 0x85845DD1); MD5::round4(a, b, c, d, blockX[ 8], 6, 0x6FA87E4F); MD5::round4(d, a, b, c, blockX[15], 10, 0xFE2CE6E0); MD5::round4(c, d, a, b, blockX[ 6], 15, 0xA3014314); MD5::round4(b, c, d, a, blockX[13], 21, 0x4E0811A1); MD5::round4(a, b, c, d, blockX[ 4], 6, 0xF7537E82); MD5::round4(d, a, b, c, blockX[11], 10, 0xBD3AF235); MD5::round4(c, d, a, b, blockX[ 2], 15, 0x2AD7D2BB); MD5::round4(b, c, d, a, blockX[ 9], 21, 0xEB86D391); // Increment each state by it's previous value state[0] += a; state[1] += b; state[2] += c; state[3] += d; } pOutput->write((const uint8_t *)state, 16); // Zeroize sensitive information std::memset(blockX, 0, sizeof(blockX)); std::memset(data, 0, dataSize); delete[] data; } namespace SHA1 { void initialize(uint32_t *pResult) { pResult[0] = 0x67452301; pResult[1] = 0xEFCDAB89; pResult[2] = 0x98BADCFE; pResult[3] = 0x10325476; pResult[4] = 0xC3D2E1F0; } void process(uint32_t *pResult, uint32_t *pBlock) { unsigned int i; uint32_t a, b, c, d, e, f, k, step; uint32_t extendedBlock[80]; std::memcpy(extendedBlock, pBlock, 64); // Adjust for big endian if(Endian::sSystemType != Endian::BIG) for(i=0;i<16;i++) extendedBlock[i] = Endian::convert(extendedBlock[i], Endian::BIG); // Extend the sixteen 32-bit words into eighty 32-bit words: for(i=16;i<80;i++) extendedBlock[i] = Math::rotateLeft(extendedBlock[i-3] ^ extendedBlock[i-8] ^ extendedBlock[i-14] ^ extendedBlock[i-16], 1); // Initialize hash value for this chunk: a = pResult[0]; b = pResult[1]; c = pResult[2]; d = pResult[3]; e = pResult[4]; // Main loop: for(i=0;i<80;i++) { if(i < 20) { f = (b & c) |((~b) & d); k = 0x5A827999; } else if(i < 40) { f = b ^ c ^ d; k = 0x6ED9EBA1; } else if(i < 60) { f = (b & c) |(b & d) |(c & d); k = 0x8F1BBCDC; } else // if(i < 80) { f = b ^ c ^ d; k = 0xCA62C1D6; } step = Math::rotateLeft(a, 5) + f + e + k + extendedBlock[i]; e = d; d = c; c = Math::rotateLeft(b, 30); b = a; a = step; } // Add this chunk's hash to result so far: pResult[0] += a; pResult[1] += b; pResult[2] += c; pResult[3] += d; pResult[4] += e; } void finish(uint32_t *pResult, uint32_t *pBlock, unsigned int pBlockLength, uint64_t pTotalLength) { // Zeroize the end of the block std::memset(((uint8_t *)pBlock) + pBlockLength, 0, 64 - pBlockLength); // Add 0x80 byte (basically a 1 bit at the end of the data) ((uint8_t *)pBlock)[pBlockLength] = 0x80; // Check if there is enough room for the total length in this block if(pBlockLength > 55) // 55 because of the 0x80 byte already added { process(pResult, pBlock); // Process this block std::memset(pBlock, 0, 64); // Clear the block } // Put bit length in last 8 bytes of block (Big Endian) pTotalLength *= 8; uint32_t lower = pTotalLength & 0xffffffff; pBlock[15] = Endian::convert(lower, Endian::BIG); uint32_t upper = (pTotalLength >> 32) & 0xffffffff; pBlock[14] = Endian::convert(upper, Endian::BIG); // Process last block process(pResult, pBlock); // Adjust for big endian if(Endian::sSystemType != Endian::BIG) for(unsigned int i=0;i<5;i++) pResult[i] = Endian::convert(pResult[i], Endian::BIG); } } void Digest::sha1(InputStream *pInput, stream_size pInputLength, OutputStream *pOutput) // 160 bit(20 byte) result { // Note 1: All variables are unsigned 32 bits and wrap modulo 232 when calculating // Note 2: All constants in this pseudo code are in big endian. // Within each word, the most significant bit is stored in the leftmost bit position stream_size dataSize = pInputLength + (64 - (pInputLength % 64)); uint64_t bitLength = (uint64_t)pInputLength * 8; Buffer message; message.setEndian(Endian::BIG); message.writeStream(pInput, pInputLength); // Pre-processing: // append the bit '1' to the message message.writeByte(0x80); // append k bits '0', where k is the minimum number ? 0 such that the resulting message // length(in bits) is congruent to 448(mod 512) // Append the rest zero bits while(message.length() < dataSize - 8) message.writeByte(0); // append length of message(before pre-processing), in bits, as 64-bit big-endian integer // Append the data length as a 64 bit number low order word first message.writeUnsignedLong(bitLength); uint32_t state[5] = { 0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0 }; uint32_t a, b, c, d, e; // Process the message in successive 512-bit chunks: // break message into 512-bit chunks // for each chunk unsigned int i, blockIndex, blockCount = dataSize / 64; uint32_t extended[80]; uint32_t f, k, step; for(blockIndex=0;blockIndex<blockCount;blockIndex++) { // break chunk into sixteen 32-bit big-endian words w[i], 0 ? i ? 15 for(i=0;i<16;i++) extended[i] = message.readUnsignedInt(); // Extend the sixteen 32-bit words into eighty 32-bit words: for(i=16;i<80;i++) extended[i] = Math::rotateLeft(extended[i-3] ^ extended[i-8] ^ extended[i-14] ^ extended[i-16], 1); // Initialize hash value for this chunk: a = state[0]; b = state[1]; c = state[2]; d = state[3]; e = state[4]; // Main loop: for(i=0;i<80;i++) { if(i < 20) { f = (b & c) |((~b) & d); k = 0x5A827999; } else if(i < 40) { f = b ^ c ^ d; k = 0x6ED9EBA1; } else if(i < 60) { f = (b & c) |(b & d) |(c & d); k = 0x8F1BBCDC; } else // if(i < 80) { f = b ^ c ^ d; k = 0xCA62C1D6; } step = Math::rotateLeft(a, 5) + f + e + k + extended[i]; e = d; d = c; c = Math::rotateLeft(b, 30); b = a; a = step; } // Add this chunk's hash to result so far: state[0] += a; state[1] += b; state[2] += c; state[3] += d; state[4] += e; } for(unsigned int i=0;i<5;i++) pOutput->writeUnsignedInt(Endian::convert(state[i], Endian::BIG)); // Zeroize possible sensitive data message.zeroize(); std::memset(extended, 0, sizeof(int) * 80); std::memset(state, 0, sizeof(int) * 5); } namespace RIPEMD160 { inline uint32_t f(uint32_t pX, uint32_t pY, uint32_t pZ) { return pX ^ pY ^ pZ; } inline uint32_t g(uint32_t pX, uint32_t pY, uint32_t pZ) { return (pX & pY) | (~pX & pZ); } inline uint32_t h(uint32_t pX, uint32_t pY, uint32_t pZ) { return (pX | ~pY) ^ pZ; } inline uint32_t i(uint32_t pX, uint32_t pY, uint32_t pZ) { return (pX & pZ) | (pY & ~pZ); } inline uint32_t j(uint32_t pX, uint32_t pY, uint32_t pZ) { return pX ^ (pY | ~pZ); } inline void ff(uint32_t &pA, uint32_t &pB, uint32_t &pC, uint32_t &pD, uint32_t &pE, uint32_t &pX, uint32_t pS) { pA += f(pB, pC, pD) + pX; pA = Math::rotateLeft(pA, pS) + pE; pC = Math::rotateLeft(pC, 10); } inline void gg(uint32_t &pA, uint32_t &pB, uint32_t &pC, uint32_t &pD, uint32_t &pE, uint32_t &pX, uint32_t pS) { pA += g(pB, pC, pD) + pX + 0x5a827999; pA = Math::rotateLeft(pA, pS) + pE; pC = Math::rotateLeft(pC, 10); } inline void hh(uint32_t &pA, uint32_t &pB, uint32_t &pC, uint32_t &pD, uint32_t &pE, uint32_t &pX, uint32_t pS) { pA += h(pB, pC, pD) + pX + 0x6ed9eba1; pA = Math::rotateLeft(pA, pS) + pE; pC = Math::rotateLeft(pC, 10); } inline void ii(uint32_t &pA, uint32_t &pB, uint32_t &pC, uint32_t &pD, uint32_t &pE, uint32_t &pX, uint32_t pS) { pA += i(pB, pC, pD) + pX + 0x8f1bbcdc; pA = Math::rotateLeft(pA, pS) + pE; pC = Math::rotateLeft(pC, 10); } inline void jj(uint32_t &pA, uint32_t &pB, uint32_t &pC, uint32_t &pD, uint32_t &pE, uint32_t &pX, uint32_t pS) { pA += j(pB, pC, pD) + pX + 0xa953fd4e; pA = Math::rotateLeft(pA, pS) + pE; pC = Math::rotateLeft(pC, 10); } inline void fff(uint32_t &pA, uint32_t &pB, uint32_t &pC, uint32_t &pD, uint32_t &pE, uint32_t &pX, uint32_t pS) { pA += f(pB, pC, pD) + pX; pA = Math::rotateLeft(pA, pS) + pE; pC = Math::rotateLeft(pC, 10); } inline void ggg(uint32_t &pA, uint32_t &pB, uint32_t &pC, uint32_t &pD, uint32_t &pE, uint32_t &pX, uint32_t pS) { pA += g(pB, pC, pD) + pX + 0x7a6d76e9; pA = Math::rotateLeft(pA, pS) + pE; pC = Math::rotateLeft(pC, 10); } inline void hhh(uint32_t &pA, uint32_t &pB, uint32_t &pC, uint32_t &pD, uint32_t &pE, uint32_t &pX, uint32_t pS) { pA += h(pB, pC, pD) + pX + 0x6d703ef3; pA = Math::rotateLeft(pA, pS) + pE; pC = Math::rotateLeft(pC, 10); } inline void iii(uint32_t &pA, uint32_t &pB, uint32_t &pC, uint32_t &pD, uint32_t &pE, uint32_t &pX, uint32_t pS) { pA += i(pB, pC, pD) + pX + 0x5c4dd124; pA = Math::rotateLeft(pA, pS) + pE; pC = Math::rotateLeft(pC, 10); } inline void jjj(uint32_t &pA, uint32_t &pB, uint32_t &pC, uint32_t &pD, uint32_t &pE, uint32_t &pX, uint32_t pS) { pA += j(pB, pC, pD) + pX + 0x50a28be6; pA = Math::rotateLeft(pA, pS) + pE; pC = Math::rotateLeft(pC, 10); } void initialize(uint32_t *pResult) { pResult[0] = 0x67452301; pResult[1] = 0xefcdab89; pResult[2] = 0x98badcfe; pResult[3] = 0x10325476; pResult[4] = 0xc3d2e1f0; } void process(uint32_t *pResult, uint32_t *pBlock) { uint32_t aa = pResult[0], bb = pResult[1], cc = pResult[2], dd = pResult[3], ee = pResult[4]; uint32_t aaa = pResult[0], bbb = pResult[1], ccc = pResult[2], ddd = pResult[3], eee = pResult[4]; // Round 1 ff(aa, bb, cc, dd, ee, pBlock[ 0], 11); ff(ee, aa, bb, cc, dd, pBlock[ 1], 14); ff(dd, ee, aa, bb, cc, pBlock[ 2], 15); ff(cc, dd, ee, aa, bb, pBlock[ 3], 12); ff(bb, cc, dd, ee, aa, pBlock[ 4], 5); ff(aa, bb, cc, dd, ee, pBlock[ 5], 8); ff(ee, aa, bb, cc, dd, pBlock[ 6], 7); ff(dd, ee, aa, bb, cc, pBlock[ 7], 9); ff(cc, dd, ee, aa, bb, pBlock[ 8], 11); ff(bb, cc, dd, ee, aa, pBlock[ 9], 13); ff(aa, bb, cc, dd, ee, pBlock[10], 14); ff(ee, aa, bb, cc, dd, pBlock[11], 15); ff(dd, ee, aa, bb, cc, pBlock[12], 6); ff(cc, dd, ee, aa, bb, pBlock[13], 7); ff(bb, cc, dd, ee, aa, pBlock[14], 9); ff(aa, bb, cc, dd, ee, pBlock[15], 8); // Round 2 gg(ee, aa, bb, cc, dd, pBlock[ 7], 7); gg(dd, ee, aa, bb, cc, pBlock[ 4], 6); gg(cc, dd, ee, aa, bb, pBlock[13], 8); gg(bb, cc, dd, ee, aa, pBlock[ 1], 13); gg(aa, bb, cc, dd, ee, pBlock[10], 11); gg(ee, aa, bb, cc, dd, pBlock[ 6], 9); gg(dd, ee, aa, bb, cc, pBlock[15], 7); gg(cc, dd, ee, aa, bb, pBlock[ 3], 15); gg(bb, cc, dd, ee, aa, pBlock[12], 7); gg(aa, bb, cc, dd, ee, pBlock[ 0], 12); gg(ee, aa, bb, cc, dd, pBlock[ 9], 15); gg(dd, ee, aa, bb, cc, pBlock[ 5], 9); gg(cc, dd, ee, aa, bb, pBlock[ 2], 11); gg(bb, cc, dd, ee, aa, pBlock[14], 7); gg(aa, bb, cc, dd, ee, pBlock[11], 13); gg(ee, aa, bb, cc, dd, pBlock[ 8], 12); // Round 3 hh(dd, ee, aa, bb, cc, pBlock[ 3], 11); hh(cc, dd, ee, aa, bb, pBlock[10], 13); hh(bb, cc, dd, ee, aa, pBlock[14], 6); hh(aa, bb, cc, dd, ee, pBlock[ 4], 7); hh(ee, aa, bb, cc, dd, pBlock[ 9], 14); hh(dd, ee, aa, bb, cc, pBlock[15], 9); hh(cc, dd, ee, aa, bb, pBlock[ 8], 13); hh(bb, cc, dd, ee, aa, pBlock[ 1], 15); hh(aa, bb, cc, dd, ee, pBlock[ 2], 14); hh(ee, aa, bb, cc, dd, pBlock[ 7], 8); hh(dd, ee, aa, bb, cc, pBlock[ 0], 13); hh(cc, dd, ee, aa, bb, pBlock[ 6], 6); hh(bb, cc, dd, ee, aa, pBlock[13], 5); hh(aa, bb, cc, dd, ee, pBlock[11], 12); hh(ee, aa, bb, cc, dd, pBlock[ 5], 7); hh(dd, ee, aa, bb, cc, pBlock[12], 5); // Round 4 ii(cc, dd, ee, aa, bb, pBlock[ 1], 11); ii(bb, cc, dd, ee, aa, pBlock[ 9], 12); ii(aa, bb, cc, dd, ee, pBlock[11], 14); ii(ee, aa, bb, cc, dd, pBlock[10], 15); ii(dd, ee, aa, bb, cc, pBlock[ 0], 14); ii(cc, dd, ee, aa, bb, pBlock[ 8], 15); ii(bb, cc, dd, ee, aa, pBlock[12], 9); ii(aa, bb, cc, dd, ee, pBlock[ 4], 8); ii(ee, aa, bb, cc, dd, pBlock[13], 9); ii(dd, ee, aa, bb, cc, pBlock[ 3], 14); ii(cc, dd, ee, aa, bb, pBlock[ 7], 5); ii(bb, cc, dd, ee, aa, pBlock[15], 6); ii(aa, bb, cc, dd, ee, pBlock[14], 8); ii(ee, aa, bb, cc, dd, pBlock[ 5], 6); ii(dd, ee, aa, bb, cc, pBlock[ 6], 5); ii(cc, dd, ee, aa, bb, pBlock[ 2], 12); // Round 5 jj(bb, cc, dd, ee, aa, pBlock[ 4], 9); jj(aa, bb, cc, dd, ee, pBlock[ 0], 15); jj(ee, aa, bb, cc, dd, pBlock[ 5], 5); jj(dd, ee, aa, bb, cc, pBlock[ 9], 11); jj(cc, dd, ee, aa, bb, pBlock[ 7], 6); jj(bb, cc, dd, ee, aa, pBlock[12], 8); jj(aa, bb, cc, dd, ee, pBlock[ 2], 13); jj(ee, aa, bb, cc, dd, pBlock[10], 12); jj(dd, ee, aa, bb, cc, pBlock[14], 5); jj(cc, dd, ee, aa, bb, pBlock[ 1], 12); jj(bb, cc, dd, ee, aa, pBlock[ 3], 13); jj(aa, bb, cc, dd, ee, pBlock[ 8], 14); jj(ee, aa, bb, cc, dd, pBlock[11], 11); jj(dd, ee, aa, bb, cc, pBlock[ 6], 8); jj(cc, dd, ee, aa, bb, pBlock[15], 5); jj(bb, cc, dd, ee, aa, pBlock[13], 6); // Parallel round 1 jjj(aaa, bbb, ccc, ddd, eee, pBlock[ 5], 8); jjj(eee, aaa, bbb, ccc, ddd, pBlock[14], 9); jjj(ddd, eee, aaa, bbb, ccc, pBlock[ 7], 9); jjj(ccc, ddd, eee, aaa, bbb, pBlock[ 0], 11); jjj(bbb, ccc, ddd, eee, aaa, pBlock[ 9], 13); jjj(aaa, bbb, ccc, ddd, eee, pBlock[ 2], 15); jjj(eee, aaa, bbb, ccc, ddd, pBlock[11], 15); jjj(ddd, eee, aaa, bbb, ccc, pBlock[ 4], 5); jjj(ccc, ddd, eee, aaa, bbb, pBlock[13], 7); jjj(bbb, ccc, ddd, eee, aaa, pBlock[ 6], 7); jjj(aaa, bbb, ccc, ddd, eee, pBlock[15], 8); jjj(eee, aaa, bbb, ccc, ddd, pBlock[ 8], 11); jjj(ddd, eee, aaa, bbb, ccc, pBlock[ 1], 14); jjj(ccc, ddd, eee, aaa, bbb, pBlock[10], 14); jjj(bbb, ccc, ddd, eee, aaa, pBlock[ 3], 12); jjj(aaa, bbb, ccc, ddd, eee, pBlock[12], 6); // Parallel round 2 iii(eee, aaa, bbb, ccc, ddd, pBlock[ 6], 9); iii(ddd, eee, aaa, bbb, ccc, pBlock[11], 13); iii(ccc, ddd, eee, aaa, bbb, pBlock[ 3], 15); iii(bbb, ccc, ddd, eee, aaa, pBlock[ 7], 7); iii(aaa, bbb, ccc, ddd, eee, pBlock[ 0], 12); iii(eee, aaa, bbb, ccc, ddd, pBlock[13], 8); iii(ddd, eee, aaa, bbb, ccc, pBlock[ 5], 9); iii(ccc, ddd, eee, aaa, bbb, pBlock[10], 11); iii(bbb, ccc, ddd, eee, aaa, pBlock[14], 7); iii(aaa, bbb, ccc, ddd, eee, pBlock[15], 7); iii(eee, aaa, bbb, ccc, ddd, pBlock[ 8], 12); iii(ddd, eee, aaa, bbb, ccc, pBlock[12], 7); iii(ccc, ddd, eee, aaa, bbb, pBlock[ 4], 6); iii(bbb, ccc, ddd, eee, aaa, pBlock[ 9], 15); iii(aaa, bbb, ccc, ddd, eee, pBlock[ 1], 13); iii(eee, aaa, bbb, ccc, ddd, pBlock[ 2], 11); // Parallel round 3 hhh(ddd, eee, aaa, bbb, ccc, pBlock[15], 9); hhh(ccc, ddd, eee, aaa, bbb, pBlock[ 5], 7); hhh(bbb, ccc, ddd, eee, aaa, pBlock[ 1], 15); hhh(aaa, bbb, ccc, ddd, eee, pBlock[ 3], 11); hhh(eee, aaa, bbb, ccc, ddd, pBlock[ 7], 8); hhh(ddd, eee, aaa, bbb, ccc, pBlock[14], 6); hhh(ccc, ddd, eee, aaa, bbb, pBlock[ 6], 6); hhh(bbb, ccc, ddd, eee, aaa, pBlock[ 9], 14); hhh(aaa, bbb, ccc, ddd, eee, pBlock[11], 12); hhh(eee, aaa, bbb, ccc, ddd, pBlock[ 8], 13); hhh(ddd, eee, aaa, bbb, ccc, pBlock[12], 5); hhh(ccc, ddd, eee, aaa, bbb, pBlock[ 2], 14); hhh(bbb, ccc, ddd, eee, aaa, pBlock[10], 13); hhh(aaa, bbb, ccc, ddd, eee, pBlock[ 0], 13); hhh(eee, aaa, bbb, ccc, ddd, pBlock[ 4], 7); hhh(ddd, eee, aaa, bbb, ccc, pBlock[13], 5); // Parallel round 4 ggg(ccc, ddd, eee, aaa, bbb, pBlock[ 8], 15); ggg(bbb, ccc, ddd, eee, aaa, pBlock[ 6], 5); ggg(aaa, bbb, ccc, ddd, eee, pBlock[ 4], 8); ggg(eee, aaa, bbb, ccc, ddd, pBlock[ 1], 11); ggg(ddd, eee, aaa, bbb, ccc, pBlock[ 3], 14); ggg(ccc, ddd, eee, aaa, bbb, pBlock[11], 14); ggg(bbb, ccc, ddd, eee, aaa, pBlock[15], 6); ggg(aaa, bbb, ccc, ddd, eee, pBlock[ 0], 14); ggg(eee, aaa, bbb, ccc, ddd, pBlock[ 5], 6); ggg(ddd, eee, aaa, bbb, ccc, pBlock[12], 9); ggg(ccc, ddd, eee, aaa, bbb, pBlock[ 2], 12); ggg(bbb, ccc, ddd, eee, aaa, pBlock[13], 9); ggg(aaa, bbb, ccc, ddd, eee, pBlock[ 9], 12); ggg(eee, aaa, bbb, ccc, ddd, pBlock[ 7], 5); ggg(ddd, eee, aaa, bbb, ccc, pBlock[10], 15); ggg(ccc, ddd, eee, aaa, bbb, pBlock[14], 8); // Parallel round 5 fff(bbb, ccc, ddd, eee, aaa, pBlock[12] , 8); fff(aaa, bbb, ccc, ddd, eee, pBlock[15] , 5); fff(eee, aaa, bbb, ccc, ddd, pBlock[10] , 12); fff(ddd, eee, aaa, bbb, ccc, pBlock[ 4] , 9); fff(ccc, ddd, eee, aaa, bbb, pBlock[ 1] , 12); fff(bbb, ccc, ddd, eee, aaa, pBlock[ 5] , 5); fff(aaa, bbb, ccc, ddd, eee, pBlock[ 8] , 14); fff(eee, aaa, bbb, ccc, ddd, pBlock[ 7] , 6); fff(ddd, eee, aaa, bbb, ccc, pBlock[ 6] , 8); fff(ccc, ddd, eee, aaa, bbb, pBlock[ 2] , 13); fff(bbb, ccc, ddd, eee, aaa, pBlock[13] , 6); fff(aaa, bbb, ccc, ddd, eee, pBlock[14] , 5); fff(eee, aaa, bbb, ccc, ddd, pBlock[ 0] , 15); fff(ddd, eee, aaa, bbb, ccc, pBlock[ 3] , 13); fff(ccc, ddd, eee, aaa, bbb, pBlock[ 9] , 11); fff(bbb, ccc, ddd, eee, aaa, pBlock[11] , 11); // Combine results ddd += cc + pResult[1]; pResult[1] = pResult[2] + dd + eee; pResult[2] = pResult[3] + ee + aaa; pResult[3] = pResult[4] + aa + bbb; pResult[4] = pResult[0] + bb + ccc; pResult[0] = ddd; } // BlockLength must be less than 64 void finish(uint32_t *pResult, uint32_t *pBlock, unsigned int pBlockLength, uint64_t pTotalLength) { // Zeroize the end of the block std::memset(((uint8_t *)pBlock) + pBlockLength, 0, 64 - pBlockLength); // Add 0x80 byte (basically a 1 bit at the end of the data) ((uint8_t *)pBlock)[pBlockLength] = 0x80; // Check if there is enough room for the total length in this block if(pBlockLength > 55) // 55 because of the 0x80 byte { process(pResult, pBlock); // Process this block std::memset(pBlock, 0, 64); // Clear the block } // Put bit length in last 8 bytes of block pTotalLength *= 8; ((uint64_t *)pBlock)[7] = Endian::convert(pTotalLength, Endian::LITTLE); // Process last block process(pResult, pBlock); } } void Digest::ripEMD160(InputStream *pInput, stream_size pInputLength, OutputStream *pOutput) { uint32_t result[5]; uint32_t block[16]; stream_size remaining = pInputLength; RIPEMD160::initialize(result); // Process all full (64 byte) blocks while(remaining >= 64) { pInput->read(block, 64); remaining -= 64; RIPEMD160::process(result, block); } // Get last partial block (must be less than 64 bytes) pInput->read(block, remaining); // Process last block RIPEMD160::finish(result, block, remaining, pInputLength); // Write output pOutput->write(result, 20); } namespace SHA256 { static const uint32_t table[64] = { 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 }; void initialize(uint32_t *pResult) { pResult[0] = 0x6a09e667; pResult[1] = 0xbb67ae85; pResult[2] = 0x3c6ef372; pResult[3] = 0xa54ff53a; pResult[4] = 0x510e527f; pResult[5] = 0x9b05688c; pResult[6] = 0x1f83d9ab; pResult[7] = 0x5be0cd19; } void process(uint32_t *pResult, uint32_t *pBlock) { unsigned int i; uint32_t s0, s1, t1, t2; uint32_t extendedBlock[64]; std::memcpy(extendedBlock, pBlock, 64); // Adjust for big endian if(Endian::sSystemType != Endian::BIG) for(i=0;i<16;i++) extendedBlock[i] = Endian::convert(extendedBlock[i], Endian::BIG); // Extend the block to 64 32-bit words: for(i=16;i<64;i++) { s0 = extendedBlock[i-15]; s0 = Math::rotateRight(s0, 7) ^ Math::rotateRight(s0, 18) ^ (s0 >> 3); s1 = extendedBlock[i-2]; s1 = Math::rotateRight(s1, 17) ^ Math::rotateRight(s1, 19) ^ (s1 >> 10); extendedBlock[i] = extendedBlock[i-16] + extendedBlock[i-7] + s0 + s1; } uint32_t state[8]; std::memcpy(state, pResult, 32); for(i=0;i<64;i++) { s0 = Math::rotateRight(state[0], 2) ^ Math::rotateRight(state[0], 13) ^ Math::rotateRight(state[0], 22); t2 = s0 +((state[0] & state[1]) ^(state [0] & state[2]) ^(state[1] & state[2])); s1 = Math::rotateRight(state[4], 6) ^ Math::rotateRight(state[4], 11) ^ Math::rotateRight(state[4], 25); t1 = state[7] + s1 +((state[4] & state[5]) ^(~state[4] & state[6])) + table[i] + extendedBlock[i]; state[7] = state[6]; state[6] = state[5]; state[5] = state[4]; state[4] = state[3] + t1; state[3] = state[2]; state[2] = state[1]; state[1] = state[0]; state[0] = t1 + t2; } for(i=0;i<8;i++) pResult[i] += state[i]; } void finish(uint32_t *pResult, uint32_t *pBlock, unsigned int pBlockLength, uint64_t pTotalLength) { // Zeroize the end of the block std::memset(((uint8_t *)pBlock) + pBlockLength, 0, 64 - pBlockLength); // Add 0x80 byte (basically a 1 bit at the end of the data) ((uint8_t *)pBlock)[pBlockLength] = 0x80; // Check if there is enough room for the total length in this block if(pBlockLength > 55) // 56 - 1 because of the 0x80 byte already added { process(pResult, pBlock); // Process this block std::memset(pBlock, 0, 64); // Clear the block } // Put bit length in last 8 bytes of block (Big Endian) pTotalLength *= 8; ((uint64_t *)pBlock)[7] = Endian::convert(pTotalLength, Endian::BIG); // Process last block process(pResult, pBlock); // Adjust for big endian if(Endian::sSystemType != Endian::BIG) for(unsigned int i=0;i<8;i++) pResult[i] = Endian::convert(pResult[i], Endian::BIG); } } void Digest::sha256(InputStream *pInput, stream_size pInputLength, OutputStream *pOutput) // 256 bit(32 byte) result { stream_size remaining = pInputLength; uint32_t result[8]; uint32_t block[16]; SHA256::initialize(result); while(remaining >= 64) { pInput->read(block, 64); remaining -= 64; SHA256::process(result, block); } pInput->read(block, remaining); SHA256::finish(result, block, remaining, pInputLength); pOutput->write(result, 32); return; } namespace SHA512 { static const uint64_t table[80] = { 0x428a2f98d728ae22, 0x7137449123ef65cd, 0xb5c0fbcfec4d3b2f, 0xe9b5dba58189dbbc, 0x3956c25bf348b538, 0x59f111f1b605d019, 0x923f82a4af194f9b, 0xab1c5ed5da6d8118, 0xd807aa98a3030242, 0x12835b0145706fbe, 0x243185be4ee4b28c, 0x550c7dc3d5ffb4e2, 0x72be5d74f27b896f, 0x80deb1fe3b1696b1, 0x9bdc06a725c71235, 0xc19bf174cf692694, 0xe49b69c19ef14ad2, 0xefbe4786384f25e3, 0x0fc19dc68b8cd5b5, 0x240ca1cc77ac9c65, 0x2de92c6f592b0275, 0x4a7484aa6ea6e483, 0x5cb0a9dcbd41fbd4, 0x76f988da831153b5, 0x983e5152ee66dfab, 0xa831c66d2db43210, 0xb00327c898fb213f, 0xbf597fc7beef0ee4, 0xc6e00bf33da88fc2, 0xd5a79147930aa725, 0x06ca6351e003826f, 0x142929670a0e6e70, 0x27b70a8546d22ffc, 0x2e1b21385c26c926, 0x4d2c6dfc5ac42aed, 0x53380d139d95b3df, 0x650a73548baf63de, 0x766a0abb3c77b2a8, 0x81c2c92e47edaee6, 0x92722c851482353b, 0xa2bfe8a14cf10364, 0xa81a664bbc423001, 0xc24b8b70d0f89791, 0xc76c51a30654be30, 0xd192e819d6ef5218, 0xd69906245565a910, 0xf40e35855771202a, 0x106aa07032bbd1b8, 0x19a4c116b8d2d0c8, 0x1e376c085141ab53, 0x2748774cdf8eeb99, 0x34b0bcb5e19b48a8, 0x391c0cb3c5c95a63, 0x4ed8aa4ae3418acb, 0x5b9cca4f7763e373, 0x682e6ff3d6b2b8a3, 0x748f82ee5defb2fc, 0x78a5636f43172f60, 0x84c87814a1f0ab72, 0x8cc702081a6439ec, 0x90befffa23631e28, 0xa4506cebde82bde9, 0xbef9a3f7b2c67915, 0xc67178f2e372532b, 0xca273eceea26619c, 0xd186b8c721c0c207, 0xeada7dd6cde0eb1e, 0xf57d4f7fee6ed178, 0x06f067aa72176fba, 0x0a637dc5a2c898a6, 0x113f9804bef90dae, 0x1b710b35131c471b, 0x28db77f523047d84, 0x32caab7b40c72493, 0x3c9ebe0a15c9bebc, 0x431d67c49c100d4c, 0x4cc5d4becb3e42b6, 0x597f299cfc657e2a, 0x5fcb6fab3ad6faec, 0x6c44198c4a475817 }; void initialize(uint32_t *pResult) { ((uint64_t *)pResult)[0] = 0x6a09e667f3bcc908; ((uint64_t *)pResult)[1] = 0xbb67ae8584caa73b; ((uint64_t *)pResult)[2] = 0x3c6ef372fe94f82b; ((uint64_t *)pResult)[3] = 0xa54ff53a5f1d36f1; ((uint64_t *)pResult)[4] = 0x510e527fade682d1; ((uint64_t *)pResult)[5] = 0x9b05688c2b3e6c1f; ((uint64_t *)pResult)[6] = 0x1f83d9abfb41bd6b; ((uint64_t *)pResult)[7] = 0x5be0cd19137e2179; } void process(uint32_t *pResult, uint32_t *pBlock) { unsigned int i; uint64_t s0, s1, t1, t2; uint64_t extendedBlock[80]; std::memcpy(extendedBlock, pBlock, 128); // Adjust for big endian if(Endian::sSystemType != Endian::BIG) for(i=0;i<16;++i) extendedBlock[i] = Endian::convert(extendedBlock[i], Endian::BIG); // Extend the block to 80 64-bit words: for(i=16;i<80;++i) { s0 = extendedBlock[i-15]; s0 = Math::rotateRight64(s0, 1) ^ Math::rotateRight64(s0, 8) ^ (s0 >> 7); s1 = extendedBlock[i-2]; s1 = Math::rotateRight64(s1, 19) ^ Math::rotateRight64(s1, 61) ^ (s1 >> 6); extendedBlock[i] = extendedBlock[i-16] + extendedBlock[i-7] + s0 + s1; } uint64_t state[8]; std::memcpy(state, pResult, 64); for(i=0;i<80;++i) { s0 = Math::rotateRight64(state[0], 28) ^ Math::rotateRight64(state[0], 34) ^ Math::rotateRight64(state[0], 39); t2 = s0 +((state[0] & state[1]) ^ (state [0] & state[2]) ^ (state[1] & state[2])); s1 = Math::rotateRight64(state[4], 14) ^ Math::rotateRight64(state[4], 18) ^ Math::rotateRight64(state[4], 41); t1 = state[7] + s1 + ((state[4] & state[5]) ^ (~state[4] & state[6])) + table[i] + extendedBlock[i]; state[7] = state[6]; state[6] = state[5]; state[5] = state[4]; state[4] = state[3] + t1; state[3] = state[2]; state[2] = state[1]; state[1] = state[0]; state[0] = t1 + t2; } for(i=0;i<8;++i) ((uint64_t *)pResult)[i] += state[i]; } void finish(uint32_t *pResult, uint32_t *pBlock, unsigned int pBlockLength, uint64_t pTotalLength) { // Zeroize the end of the block if(pBlockLength < 128) std::memset(((uint8_t *)pBlock) + pBlockLength, 0, 128 - pBlockLength); // Add 0x80 byte (basically a 1 bit at the end of the data) ((uint8_t *)pBlock)[pBlockLength] = 0x80; // Check if there is enough room for the total length in this block if(pBlockLength > 111) // 112 - 1 because of the 0x80 byte already added { process(pResult, pBlock); // Process this block std::memset(pBlock, 0, 128); // Clear the block } // Put bit length in last 16 bytes of block (Big Endian) pTotalLength *= 8; ((uint64_t *)pBlock)[15] = Endian::convert(pTotalLength, Endian::BIG); // Process last block process(pResult, pBlock); // Adjust for big endian if(Endian::sSystemType != Endian::BIG) for(unsigned int i=0;i<8;++i) ((uint64_t *)pResult)[i] = Endian::convert(((uint64_t *)pResult)[i], Endian::BIG); } } void Digest::sha512(InputStream *pInput, stream_size pInputLength, OutputStream *pOutput) // 512 bit(64 byte) result { stream_size remaining = pInputLength; uint32_t result[16]; uint32_t block[32]; SHA512::initialize(result); while(remaining >= 128) { pInput->read(block, 128); remaining -= 128; SHA512::process(result, block); } pInput->read(block, remaining); SHA512::finish(result, block, remaining, pInputLength); pOutput->write(result, 64); return; } namespace SipHash24 { void round(uint64_t *pResult, unsigned int pRounds) { for(unsigned i=0;i<pRounds;i++) { pResult[0] += pResult[1]; pResult[1] = Math::rotateLeft64(pResult[1], 13); pResult[1] ^= pResult[0]; pResult[0] = Math::rotateLeft64(pResult[0], 32); pResult[2] += pResult[3]; pResult[3] = Math::rotateLeft64(pResult[3], 16); pResult[3] ^= pResult[2]; pResult[0] += pResult[3]; pResult[3] = Math::rotateLeft64(pResult[3], 21); pResult[3] ^= pResult[0]; pResult[2] += pResult[1]; pResult[1] = Math::rotateLeft64(pResult[1], 17); pResult[1] ^= pResult[2]; pResult[2] = Math::rotateLeft64(pResult[2], 32); } } void initialize(uint64_t *pResult, uint64_t pKey0, uint64_t pKey1) { pResult[0] = 0x736f6d6570736575 ^ pKey0; pResult[1] = 0x646f72616e646f6d ^ pKey1; pResult[2] = 0x6c7967656e657261 ^ pKey0; pResult[3] = 0x7465646279746573 ^ pKey1; } // Process 8 bytes void process(uint64_t *pResult, const uint8_t *pBlock) { // Grab 8 bytes from pBlock and convert to uint64_t uint64_t block = 0; const uint8_t *byte = pBlock; for(unsigned int i=0;i<8;++i) block |= (uint64_t)*byte++ << (i * 8); pResult[3] ^= block; round(pResult, 2); // The 2 from SipHash-2-4 pResult[0] ^= block; } // Process less than 8 bytes and length uint64_t finish(uint64_t *pResult, const uint8_t *pBlock, unsigned int pBlockLength, uint64_t pTotalLength) { // Create last block uint8_t lastBlock[8]; std::memset(lastBlock, 0, 8); // Copy partial block into last block std::memcpy(lastBlock, pBlock, pBlockLength); // Put least significant byte of total length into most significant byte of // last "block" lastBlock[7] = pTotalLength & 0xff; // Process last block process(pResult, lastBlock); pResult[2] ^= 0xff; round(pResult, 4); // The 4 from SipHash-2-4 return pResult[0] ^ pResult[1] ^ pResult[2] ^ pResult[3]; } } uint64_t Digest::sipHash24(const uint8_t *pData, stream_size pLength, uint64_t pKey0, uint64_t pKey1) { uint64_t result[4]; SipHash24::initialize(result, pKey0, pKey1); stream_size offset = 0; while(pLength - offset >= 8) { SipHash24::process(result, pData); pData += 8; offset += 8; } return SipHash24::finish(result, pData, pLength - offset, pLength); } namespace MURMUR3 { // Only 32 bit implemented void initialize(uint32_t &pResult, uint32_t pSeed) { pResult = pSeed; } // Process 4 bytes void process(uint32_t &pResult, uint32_t pBlock) { uint32_t block = pBlock; block *= 0xcc9e2d51; block = (block << 15) | (block >> 17); block *= 0x1b873593; pResult ^= block; pResult = (pResult << 13) | (pResult >> 19); pResult = (pResult * 5) + 0xe6546b64; } // Process less than 4 bytes and length void finish(uint32_t &pResult, const uint8_t *pBlockData, unsigned int pBlockLength, uint64_t pTotalLength) { if(pBlockLength > 0) { uint32_t block = 0; const uint8_t *byte = pBlockData; for(unsigned int i=0;i<pBlockLength;++i) block |= (uint32_t)*byte++ << (i * 8); block *= 0xcc9e2d51; block = (block << 15) | (block >> 17); block *= 0x1b873593; pResult ^= block; } pResult ^= pTotalLength; pResult ^= pResult >> 16; pResult *= 0x85ebca6b; pResult ^= pResult >> 13; pResult *= 0xc2b2ae35; pResult ^= pResult >> 16; } } uint32_t Digest::murMur3(const uint8_t *pData, stream_size pLength, uint32_t pSeed) { uint32_t result; MURMUR3::initialize(result, pSeed); stream_size offset = 0; while(pLength - offset >= 4) { MURMUR3::process(result, Endian::convert(*(uint32_t *)pData, Endian::LITTLE)); pData += 4; offset += 4; } MURMUR3::finish(result, pData, pLength - offset, pLength); return result; } Digest::Digest(Type pType) { mType = pType; mByteCount = 0; setOutputEndian(Endian::BIG); switch(mType) { case CRC32: mBlockSize = 1; mResultData = new uint32_t[1]; mBlockData = NULL; break; //case MD5: // mBlockSize = 64; // break; case SHA1: case RIPEMD160: mBlockSize = 64; mResultData = new uint32_t[5]; mBlockData = new uint32_t[mBlockSize / 4]; break; case SHA256: case SHA256_SHA256: case SHA256_RIPEMD160: mBlockSize = 64; mResultData = new uint32_t[8]; mBlockData = new uint32_t[mBlockSize / 4]; break; case MURMUR3: mBlockSize = 4; mResultData = new uint32_t[1]; mBlockData = new uint32_t[mBlockSize / 4]; break; case SHA512: mBlockSize = 128; mResultData = new uint32_t[16]; mBlockData = new uint32_t[mBlockSize / 4]; break; default: mBlockSize = 0; mResultData = NULL; mBlockData = NULL; break; } initialize(); } Digest::~Digest() { if(mBlockData != NULL) delete[] mBlockData; if(mResultData != NULL) delete[] mResultData; } HMACDigest::HMACDigest(Type pType, InputStream *pKey) : Digest(pType) { initialize(pKey); } void HMACDigest::initialize(InputStream *pKey) { Digest::initialize(); Buffer key; key.writeStream(pKey, pKey->remaining()); if(key.length() > mBlockSize) { // Hash key writeStream(&key, key.length()); key.clear(); // Clear key data Digest::getResult(&key); // Read key hash into key Digest::initialize(); // Reinitialize digest } // Pad key to block size while(key.length() < mBlockSize) key.writeByte(0); // Create outer padded key key.setReadOffset(0); mOuterPaddedKey.setWriteOffset(0); while(key.remaining()) mOuterPaddedKey.writeByte(0x5c ^ key.readByte()); // Create inner padded key Buffer innerPaddedKey; key.setReadOffset(0); while(key.remaining()) innerPaddedKey.writeByte(0x36 ^ key.readByte()); // Write inner padded key into digest innerPaddedKey.setReadOffset(0); writeStream(&innerPaddedKey, innerPaddedKey.length()); } void HMACDigest::getResult(RawOutputStream *pOutput) { // Get digest result Buffer firstResult; Digest::getResult(&firstResult); // Reinitialize digest Digest::initialize(); // Write outer padded key into digest mOuterPaddedKey.setReadOffset(0); writeStream(&mOuterPaddedKey, mOuterPaddedKey.length()); // Write previous digest result into digest writeStream(&firstResult, firstResult.length()); // Get the final result Digest::getResult(pOutput); } void Digest::write(const void *pInput, stream_size pSize) { mInput.write(pInput, pSize); mByteCount += pSize; process(); } void Digest::initialize(uint32_t pSeed) { mByteCount = 0; mInput.clear(); switch(mType) { case CRC32: mResultData[0] = 0xffffffff; break; //case MD5: // break; case SHA1: SHA1::initialize(mResultData); break; case RIPEMD160: RIPEMD160::initialize(mResultData); break; case SHA256: case SHA256_SHA256: case SHA256_RIPEMD160: SHA256::initialize(mResultData); break; case MURMUR3: MURMUR3::initialize(*mResultData, pSeed); break; case SHA512: SHA512::initialize(mResultData); break; } } void Digest::process() { switch(mType) { case CRC32: while(mInput.remaining() >= mBlockSize) *mResultData = (*mResultData >> 8) ^ CRC32::table[(*mResultData & 0xFF) ^ mInput.readByte()]; break; //case MD5: // break; case SHA1: while(mInput.remaining() >= mBlockSize) { mInput.read(mBlockData, mBlockSize); SHA1::process(mResultData, mBlockData); } break; case RIPEMD160: while(mInput.remaining() >= mBlockSize) { mInput.read(mBlockData, mBlockSize); RIPEMD160::process(mResultData, mBlockData); } break; case SHA256: case SHA256_SHA256: case SHA256_RIPEMD160: while(mInput.remaining() >= mBlockSize) { mInput.read(mBlockData, mBlockSize); SHA256::process(mResultData, mBlockData); } break; case MURMUR3: while(mInput.remaining() >= mBlockSize) { mInput.read(mBlockData, mBlockSize); MURMUR3::process(*mResultData, *mBlockData); } break; case SHA512: while(mInput.remaining() >= mBlockSize) { mInput.read(mBlockData, mBlockSize); SHA512::process(mResultData, mBlockData); } break; } mInput.flush(); } unsigned int Digest::getResult() { switch(mType) { case CRC32: // Finalize result *mResultData ^= 0xffffffff; *mResultData = Endian::convert(*mResultData, Endian::BIG); return *mResultData; case MURMUR3: { // Get last partial block (must be less than 4 bytes) unsigned int lastBlockSize = mInput.remaining(); mInput.read(mBlockData, lastBlockSize); MURMUR3::finish(*mResultData, (uint8_t *)mBlockData, lastBlockSize, mByteCount); return *mResultData; } default: return 0; } } void Digest::getResult(RawOutputStream *pOutput) { switch(mType) { case CRC32: // Finalize result *mResultData ^= 0xffffffff; *mResultData = Endian::convert(*mResultData, Endian::BIG); // Output result pOutput->write(mResultData, 4); // Zeroize *mResultData = 0; break; //case MD5: // break; case SHA1: { // Get last partial block (must be less than 64 bytes) unsigned int lastBlockSize = mInput.remaining(); mInput.read(mBlockData, lastBlockSize); SHA1::finish(mResultData, mBlockData, lastBlockSize, mByteCount); // Output result pOutput->write(mResultData, 20); // Zeroize std::memset(mResultData, 0, 20); std::memset(mBlockData, 0, mBlockSize); break; } case RIPEMD160: { // Get last partial block (must be less than 64 bytes) unsigned int lastBlockSize = mInput.remaining(); mInput.read(mBlockData, lastBlockSize); RIPEMD160::finish(mResultData, mBlockData, lastBlockSize, mByteCount); // Output result pOutput->write(mResultData, 20); // Zeroize std::memset(mResultData, 0, 20); std::memset(mBlockData, 0, mBlockSize); break; } case SHA256: { // Get last partial block (must be less than 64 bytes) unsigned int lastBlockSize = mInput.remaining(); mInput.read(mBlockData, lastBlockSize); SHA256::finish(mResultData, mBlockData, lastBlockSize, mByteCount); // Output result pOutput->write(mResultData, 32); // Zeroize std::memset(mResultData, 0, 32); std::memset(mBlockData, 0, mBlockSize); break; } case SHA256_SHA256: { // Get last partial block (must be less than 64 bytes) unsigned int lastBlockSize = mInput.remaining(); mInput.read(mBlockData, lastBlockSize); SHA256::finish(mResultData, mBlockData, lastBlockSize, mByteCount); // Compute SHA256 of result Digest secondSHA256(SHA256); secondSHA256.write(mResultData, 32); Buffer secondSHA256Data(32); secondSHA256.getResult(&secondSHA256Data); // Output result pOutput->writeStream(&secondSHA256Data, 32); // Zeroize std::memset(mResultData, 0, 32); std::memset(mBlockData, 0, mBlockSize); break; } case SHA256_RIPEMD160: { // Get last partial block (must be less than 64 bytes) unsigned int lastBlockSize = mInput.remaining(); mInput.read(mBlockData, lastBlockSize); SHA256::finish(mResultData, mBlockData, lastBlockSize, mByteCount); // Compute SHA256 of result Digest ripEMD160(RIPEMD160); ripEMD160.write(mResultData, 32); Buffer ripEMD160Data(20); ripEMD160.getResult(&ripEMD160Data); // Output result pOutput->writeStream(&ripEMD160Data, 20); // Zeroize std::memset(mResultData, 0, 20); std::memset(mBlockData, 0, mBlockSize); break; } case MURMUR3: { // Get last partial block (must be less than 4 bytes) unsigned int lastBlockSize = mInput.remaining(); mInput.read(mBlockData, lastBlockSize); MURMUR3::finish(*mResultData, (uint8_t *)mBlockData, lastBlockSize, mByteCount); // Output result pOutput->write(mResultData, 4); // Zeroize std::memset(mResultData, 0, 4); std::memset(mBlockData, 0, mBlockSize); break; } case SHA512: { // Get last partial block (must be less than 64 bytes) unsigned int lastBlockSize = mInput.remaining(); mInput.read(mBlockData, lastBlockSize); SHA512::finish(mResultData, mBlockData, lastBlockSize, mByteCount); // Output result pOutput->write(mResultData, 64); // Zeroize std::memset(mResultData, 0, 64); std::memset(mBlockData, 0, mBlockSize); break; } } } bool buffersMatch(Buffer &pLeft, Buffer &pRight) { if(pLeft.length() != pRight.length()) return false; while(pLeft.remaining()) if(pLeft.readByte() != pRight.readByte()) return false; return true; } void logResults(const char *pDescription, Buffer &pBuffer) { Buffer hex; pBuffer.setReadOffset(0); hex.writeAsHex(&pBuffer, pBuffer.length(), true); char *hexText = new char[hex.length()]; hex.read((uint8_t *)hexText, hex.length()); Log::addFormatted(Log::VERBOSE, NEXTCASH_DIGEST_LOG_NAME, "%s : %s", pDescription, hexText); delete[] hexText; } bool Digest::test() { Log::add(NextCash::Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "------------- Starting Digest Tests -------------"); bool result = true; Buffer input, correctDigest, resultDigest, hmacKey; /****************************************************************************************** * Test empty (All confirmed from outside sources) ******************************************************************************************/ input.clear(); /***************************************************************************************** * CRC32 empty *****************************************************************************************/ input.setReadOffset(0); crc32(&input, input.length(), &resultDigest); correctDigest.writeHex("00000000"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed CRC32 empty"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed CRC32 empty"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * MD5 empty *****************************************************************************************/ input.setReadOffset(0); md5(&input, input.length(), &resultDigest); correctDigest.writeHex("d41d8cd98f00b204e9800998ecf8427e"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MD5 empty"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MD5 empty"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * SHA1 empty *****************************************************************************************/ input.setReadOffset(0); sha1(&input, input.length(), &resultDigest); correctDigest.writeHex("da39a3ee5e6b4b0d3255bfef95601890afd80709"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed SHA1 empty"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed SHA1 empty"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * SHA1 digest empty *****************************************************************************************/ input.setReadOffset(0); Digest sha1EmptyDigest(SHA1); sha1EmptyDigest.writeStream(&input, input.length()); sha1EmptyDigest.getResult(&resultDigest); correctDigest.writeHex("da39a3ee5e6b4b0d3255bfef95601890afd80709"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed SHA1 digest empty"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed SHA1 digest empty"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * RIPEMD160 empty *****************************************************************************************/ input.setReadOffset(0); ripEMD160(&input, input.length(), &resultDigest); correctDigest.writeHex("9c1185a5c5e9fc54612808977ee8f548b2258d31"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed RIPEMD160 empty"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed RIPEMD160 empty"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * RIPEMD160 digest empty *****************************************************************************************/ input.setReadOffset(0); Digest ripemd160EmptyDigest(RIPEMD160); ripemd160EmptyDigest.writeStream(&input, input.length()); ripemd160EmptyDigest.getResult(&resultDigest); correctDigest.writeHex("9c1185a5c5e9fc54612808977ee8f548b2258d31"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed RIPEMD160 digest empty"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed RIPEMD160 digest empty"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * SHA256 empty *****************************************************************************************/ input.setReadOffset(0); sha256(&input, input.length(), &resultDigest); correctDigest.writeHex("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed SHA256 empty"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed SHA256 empty"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * SHA256 digest empty *****************************************************************************************/ input.setReadOffset(0); Digest sha256EmptyDigest(SHA256); sha256EmptyDigest.writeStream(&input, input.length()); sha256EmptyDigest.getResult(&resultDigest); correctDigest.writeHex("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed SHA256 digest empty"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed SHA256 digest empty"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * SHA512 empty *****************************************************************************************/ input.setReadOffset(0); sha512(&input, input.length(), &resultDigest); correctDigest.writeHex("cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed SHA512 empty"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed SHA512 empty"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * HMAC SHA256 digest empty *****************************************************************************************/ input.setReadOffset(0); HMACDigest hmacSHA256EmptyDigest(SHA256, &hmacKey); hmacSHA256EmptyDigest.writeStream(&input, input.length()); hmacSHA256EmptyDigest.getResult(&resultDigest); correctDigest.writeHex("b613679a0814d9ec772f95d778c35fc5ff1697c493715653c6c712144292c5ad"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed HMAC SHA256 digest empty"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed HMAC SHA256 digest empty"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * SHA512 digest empty *****************************************************************************************/ input.setReadOffset(0); Digest sha512EmptyDigest(SHA512); sha512EmptyDigest.writeStream(&input, input.length()); sha512EmptyDigest.getResult(&resultDigest); correctDigest.writeHex("cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed SHA512 digest empty"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed SHA512 digest empty"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * HMAC SHA512 digest empty *****************************************************************************************/ input.setReadOffset(0); HMACDigest hmacSHA512EmptyDigest(SHA512, &hmacKey); hmacSHA512EmptyDigest.writeStream(&input, input.length()); hmacSHA512EmptyDigest.getResult(&resultDigest); correctDigest.writeHex("b936cee86c9f87aa5d3c6f2e84cb5a4239a5fe50480a6ec66b70ab5b1f4ac6730c6c515421b327ec1d69402e53dfb49ad7381eb067b338fd7b0cb22247225d47"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed HMAC SHA512 digest empty"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed HMAC SHA512 digest empty"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /****************************************************************************************** * Test febooti.com (All confirmed from outside sources) ******************************************************************************************/ input.clear(); input.writeString("Test vector from febooti.com"); /***************************************************************************************** * CRC32 febooti.com *****************************************************************************************/ input.setReadOffset(0); crc32(&input, input.length(), &resultDigest); correctDigest.writeHex("0c877f61"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed CRC32 febooti.com"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed CRC32 febooti.com"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * CRC32 text febooti.com *****************************************************************************************/ unsigned int crc32Text = crc32("Test vector from febooti.com"); unsigned int crc32Result = Endian::convert(0x0c877f61, Endian::BIG); if(crc32Text != crc32Result) Log::addFormatted(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed CRC32 text febooti.com"); else { Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed CRC32 text febooti.com : 0x0c877f61 != 0x%08x", crc32Text); result = false; } /***************************************************************************************** * CRC32 binary febooti.com *****************************************************************************************/ unsigned int crc32Binary = crc32((uint8_t *)"Test vector from febooti.com", 28); if(crc32Binary != crc32Result) Log::addFormatted(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed CRC32 binary febooti.com"); else { Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed CRC32 binary febooti.com : 0x0c877f61 != 0x%08x", crc32Binary); result = false; } /***************************************************************************************** * MD5 febooti.com *****************************************************************************************/ input.setReadOffset(0); md5(&input, input.length(), &resultDigest); correctDigest.writeHex("500ab6613c6db7fbd30c62f5ff573d0f"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MD5 febooti.com"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MD5 febooti.com"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * SHA1 febooti.com *****************************************************************************************/ input.setReadOffset(0); sha1(&input, input.length(), &resultDigest); correctDigest.writeHex("a7631795f6d59cd6d14ebd0058a6394a4b93d868"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed SHA1 febooti.com"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed SHA1 febooti.com"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * RIPEMD160 febooti.com *****************************************************************************************/ input.setReadOffset(0); ripEMD160(&input, input.length(), &resultDigest); correctDigest.writeHex("4e1ff644ca9f6e86167ccb30ff27e0d84ceb2a61"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed RIPEMD160 febooti.com"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed RIPEMD160 febooti.com"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * SHA256 febooti.com *****************************************************************************************/ input.setReadOffset(0); sha256(&input, input.length(), &resultDigest); correctDigest.writeHex("077b18fe29036ada4890bdec192186e10678597a67880290521df70df4bac9ab"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed SHA256 febooti.com"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed SHA256 febooti.com"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * SHA512 febooti.com *****************************************************************************************/ input.setReadOffset(0); sha512(&input, input.length(), &resultDigest); correctDigest.writeHex("09fb898bc97319a243a63f6971747f8e102481fb8d5346c55cb44855adc2e0e98f304e552b0db1d4eeba8a5c8779f6a3010f0e1a2beb5b9547a13b6edca11e8a"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed SHA512 febooti.com"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed SHA512 febooti.com"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * SHA512 digest febooti.com *****************************************************************************************/ input.setReadOffset(0); Digest sha512febootiDigest(SHA512); sha512febootiDigest.writeStream(&input, input.length()); sha512febootiDigest.getResult(&resultDigest); correctDigest.writeHex("09fb898bc97319a243a63f6971747f8e102481fb8d5346c55cb44855adc2e0e98f304e552b0db1d4eeba8a5c8779f6a3010f0e1a2beb5b9547a13b6edca11e8a"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed SHA512 digest febooti.com"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed SHA512 digest febooti.com"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /****************************************************************************************** * Test quick brown fox (All confirmed from outside sources) ******************************************************************************************/ input.clear(); input.writeString("The quick brown fox jumps over the lazy dog"); /***************************************************************************************** * CRC32 quick brown fox *****************************************************************************************/ input.setReadOffset(0); crc32(&input, input.length(), &resultDigest); correctDigest.writeHex("414FA339"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed CRC32 quick brown fox"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed CRC32 quick brown fox"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * MD5 quick brown fox *****************************************************************************************/ input.setReadOffset(0); md5(&input, input.length(), &resultDigest); correctDigest.writeHex("9e107d9d372bb6826bd81d3542a419d6"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MD5 quick brown fox"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MD5 quick brown fox"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * SHA1 quick brown fox *****************************************************************************************/ input.setReadOffset(0); sha1(&input, input.length(), &resultDigest); correctDigest.writeHex("2fd4e1c67a2d28fced849ee1bb76e7391b93eb12"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed SHA1 quick brown fox"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed SHA1 quick brown fox"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * RIPEMD160 quick brown fox *****************************************************************************************/ input.setReadOffset(0); ripEMD160(&input, input.length(), &resultDigest); correctDigest.writeHex("37f332f68db77bd9d7edd4969571ad671cf9dd3b"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed RIPEMD160 quick brown fox"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed RIPEMD160 quick brown fox"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * SHA256 quick brown fox *****************************************************************************************/ input.setReadOffset(0); sha256(&input, input.length(), &resultDigest); correctDigest.writeHex("d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed SHA256 quick brown fox"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed SHA256 quick brown fox"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * HMAC SHA256 digest quick brown fox *****************************************************************************************/ input.setReadOffset(0); hmacKey.clear(); hmacKey.writeString("key"); HMACDigest hmacSHA256QBFDigest(SHA256, &hmacKey); hmacSHA256QBFDigest.writeStream(&input, input.length()); hmacSHA256QBFDigest.getResult(&resultDigest); correctDigest.writeHex("f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed HMAC SHA256 digest quick brown fox"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed HMAC SHA256 digest quick brown fox"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * SHA512 quick brown fox *****************************************************************************************/ input.setReadOffset(0); sha512(&input, input.length(), &resultDigest); correctDigest.writeHex("07e547d9586f6a73f73fbac0435ed76951218fb7d0c8d788a309d785436bbb642e93a252a954f23912547d1e8a3b5ed6e1bfd7097821233fa0538f3db854fee6"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed SHA512 quick brown fox"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed SHA512 quick brown fox"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * HMAC SHA512 digest quick brown fox *****************************************************************************************/ input.setReadOffset(0); hmacKey.clear(); hmacKey.writeString("key"); HMACDigest hmacSHA512QBFDigest(SHA512, &hmacKey); hmacSHA512QBFDigest.writeStream(&input, input.length()); hmacSHA512QBFDigest.getResult(&resultDigest); correctDigest.writeHex("b42af09057bac1e2d41708e48a902e09b5ff7f12ab428a4fe86653c73dd248fb82f948a549f7b791a5b41915ee4d1ec3935357e4e2317250d0372afa2ebeeb3a"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed HMAC SHA512 digest quick brown fox"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed HMAC SHA512 digest quick brown fox"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /****************************************************************************************** * Test random data 1024 (All confirmed from outside sources) ******************************************************************************************/ input.clear(); input.writeHex("9cd248ed860b10bbc7cd5f0ef18f81291a90307c91296dc67d3a1759f02e2a34db020eb9c1f401c1"); input.writeHex("1820349dc9401246bab85810989136420a49830fb96a28e22247ec1073536862e6c2ce82adb93b1d"); input.writeHex("b3193a938dfefe8db8aef7eefb784e6af35191b7bf79dd96da777d7b2423fd49c255839232934344"); input.writeHex("41c94a6e2aa84e926a40ff9e640e224d0241a89565feb539791b2dcb31185b3ce463d638c99db0ed"); input.writeHex("e615dded590af0c89e093d0db3637aac61cd052c776409d992ddfc0249221121909bea8085871db2"); input.writeHex("a00011dc46d159b5ce630efff43117e379d7bb105142f4ef6e3af41ff0284624d16987b7ee6187e7"); input.writeHex("3df4761d2710414f216310b8193c530568ce423b76cc0342ad0ed86a3e7c15530c54ab4022ebaeed"); input.writeHex("df4e7996fec005e2d62b3ec1097af9b29443d45531399490cd763a78d58682fcf3bb483aa7448a44"); input.writeHex("9ac089cf695a9285954751f4c139904d10512c3e1adb00de962f4912f5fd160ade61c7e8ba45c5b9"); input.writeHex("4a763c943bf30249026f1c9eaf9be10f3f47ac2f001f633f5df3774bbcbc6cb85738a0d74778a07e"); input.writeHex("736adfd769c99509d2aad922d49b6b1c67fe886578e95988961e20c64ed6b7e4e080bbda3ce24ce6"); input.writeHex("741c51cacf401cc8b373ed6170d7b70a033f553eaef18d94065f06699d6bcd0bf5d845e09fd364e3"); input.writeHex("98e96d3ed54f78dc5d6200560001a3c0f721ccba58eaf9fde2760e937b820e0c41c161530d1f6b25"); input.writeHex("6b30463fd1dfe3e9d293afd5f278bf21e2b8bfc8860f7c86f4575cd7a922e4d9dbb8857815ede9a7"); input.writeHex("628af97c7ecadf59d385de8f2a3b3d114344fd9429f15a4aabe42c3934347bc039121dd666c6cef7"); input.writeHex("a81822889f394b82458f4016ed947fb86d8ef15b40d2a36b751f983339eeb7d4880554c5feebf6a6"); input.writeHex("59467f9716afc92ad05b41aab06e958f5874d431c836419ed2c595282c6804c600e97ce3929380d9"); input.writeHex("7f2687cc210890f95b3cf428ed66cb4e853505ba380bad5bda6c89b835c711a980ea946279051ea8"); input.writeHex("d12d002a52e40b0b162e7ff1464a9474450980ff3354a04522dc869905573ee0418adbe5938e87f2"); input.writeHex("0c3761960bf64c21de39ff305420a2127de03afdc5d117489271671219ccd538c0944ecd9ea869dc"); input.writeHex("135246b03b5ac5474b8d7c1741f68bbe616048c53ebc49814c757435a0f82c48bee85c339bbfb134"); input.writeHex("d4b64f561ca82ca1413eef619966d1e34bffb2771d069f795682e9559991d6239713fca03975d8fd"); input.writeHex("e0c2fd4cfe37daf274a3298fdfb9637191524505aa608573b819b0271b97a76328130c0ad8b60d3d"); input.writeHex("e53272e3e3b49760bfd3d20e5fc57bc5baa4b070c91f4eedd5e398405ac47a4bfa307747449ce0ad"); input.writeHex("7b9e9e6e1cc3b4bdef0be7b773af02b590626c92e3a85e97e0726ac1f7061e149c550a8d1b17360d"); input.writeHex("b22d56251b4fb0a6bb40595d1001d87d799d8544fdc54dfc"); /***************************************************************************************** * CRC32 random data 1024 *****************************************************************************************/ input.setReadOffset(0); crc32(&input, input.length(), &resultDigest); correctDigest.writeHex("1f483b3f"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed CRC32 random data 1024"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed CRC32 random data 1024"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * CRC32 digest random data 1024 *****************************************************************************************/ input.setReadOffset(0); Digest crc32Digest(CRC32); crc32Digest.writeStream(&input, input.length()); crc32Digest.getResult(&resultDigest); correctDigest.writeHex("1f483b3f"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed CRC32 digest random data 1024"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed CRC32 digest random data 1024"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * MD5 random data 1024 *****************************************************************************************/ input.setReadOffset(0); md5(&input, input.length(), &resultDigest); correctDigest.writeHex("6950a08814ee1e774314c28bce8707b0"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MD5 random data 1024"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MD5 random data 1024"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * SHA1 random data 1024 *****************************************************************************************/ input.setReadOffset(0); sha1(&input, input.length(), &resultDigest); correctDigest.writeHex("2F7A0D349F1B6ABD7354965E94800BDC3D6463AC"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed SHA1 random data 1024"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed SHA1 random data 1024"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * SHA1 digest random data 1024 *****************************************************************************************/ input.setReadOffset(0); Digest sha1RandomDigest(SHA1); sha1RandomDigest.writeStream(&input, input.length()); sha1RandomDigest.getResult(&resultDigest); correctDigest.writeHex("2F7A0D349F1B6ABD7354965E94800BDC3D6463AC"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed SHA1 digest random data 1024"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed SHA1 digest random data 1024"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * RIPEMD160 random data 1024 *****************************************************************************************/ input.setReadOffset(0); ripEMD160(&input, input.length(), &resultDigest); correctDigest.writeHex("0dae1c4a362242d2ffa49c26204ed5ac2f88c454"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed RIPEMD160 random data 1024"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed RIPEMD160 random data 1024"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * RIPEMD160 digest random data 1024 *****************************************************************************************/ input.setReadOffset(0); Digest ripemd160Digest(RIPEMD160); ripemd160Digest.writeStream(&input, input.length()); ripemd160Digest.getResult(&resultDigest); correctDigest.writeHex("0dae1c4a362242d2ffa49c26204ed5ac2f88c454"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed RIPEMD160 digest random data 1024"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed RIPEMD160 digest random data 1024"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * SHA256 random data 1024 *****************************************************************************************/ input.setReadOffset(0); sha256(&input, input.length(), &resultDigest); correctDigest.writeHex("2baef0b3638abc90b17f2895e3cb24b6bbe7ff6ba7c291345102ea4eec785730"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed SHA256 random data 1024"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed SHA256 random data 1024"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * SHA256 digest random data 1024 *****************************************************************************************/ input.setReadOffset(0); Digest sha256Digest(SHA256); sha256Digest.writeStream(&input, input.length()); sha256Digest.getResult(&resultDigest); correctDigest.writeHex("2baef0b3638abc90b17f2895e3cb24b6bbe7ff6ba7c291345102ea4eec785730"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed SHA256 digest random data 1024"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed SHA256 digest random data 1024"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * SHA512 random data 1024 *****************************************************************************************/ input.setReadOffset(0); sha512(&input, input.length(), &resultDigest); correctDigest.writeHex("8c63c499586f24f3209acad229b043f02eddfc19ec04d41c2f0aeee60b3a95e87297b2de4cfaaaca9a6691bbc5f63a0453fa98b02742da313fa9075ef633a94c"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed SHA512 random data 1024"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed SHA512 random data 1024"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * HMAC SHA512 RFC4231 Text Case 4 *****************************************************************************************/ input.clear(); input.writeHex("cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd"); hmacKey.clear(); hmacKey.writeHex("0102030405060708090a0b0c0d0e0f10111213141516171819"); HMACDigest hmacSHA512RFC4231Test4Digest(SHA512); hmacSHA512RFC4231Test4Digest.initialize(&hmacKey); hmacSHA512RFC4231Test4Digest.writeStream(&input, input.length()); hmacSHA512RFC4231Test4Digest.getResult(&resultDigest); correctDigest.writeHex("b0ba465637458c6990e5a8c5f61d4af7e576d97ff94b872de76f8050361ee3dba91ca5c11aa25eb4d679275cc5788063a5f19741120c4f2de2adebeb10a298dd"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed HMAC SHA512 RFC4231 Test Case 4"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed HMAC SHA512 RFC4231 Test Case 4"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * HMAC SHA512 RFC4231 Text Case 7 *****************************************************************************************/ input.clear(); input.writeHex("5468697320697320612074657374207573696e672061206c6172676572207468616e20626c6f636b2d73697a65206b657920616e642061206c6172676572207468616e20626c6f636b2d73697a6520646174612e20546865206b6579206e6565647320746f20626520686173686564206265666f7265206265696e6720757365642062792074686520484d414320616c676f726974686d2e"); hmacKey.clear(); hmacKey.writeHex("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); HMACDigest hmacSHA512RFC4231Test7Digest(SHA512); hmacSHA512RFC4231Test7Digest.initialize(&hmacKey); hmacSHA512RFC4231Test7Digest.writeStream(&input, input.length()); hmacSHA512RFC4231Test7Digest.getResult(&resultDigest); correctDigest.writeHex("e37b6a775dc87dbaa4dfa9f96e5e3ffddebd71f8867289865df5a32d20cdc944b6022cac3c4982b10d5eeb55c3e4de15134676fb6de0446065c97440fa8c6a58"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed HMAC SHA512 RFC4231 Test Case 7"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed HMAC SHA512 RFC4231 Test Case 7"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /****************************************************************************************** * Test 56 letters (All confirmed from outside sources) ******************************************************************************************/ input.clear(); input.writeString("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"); /***************************************************************************************** * RIPEMD160 56 letters *****************************************************************************************/ input.setReadOffset(0); ripEMD160(&input, input.length(), &resultDigest); correctDigest.writeHex("12a053384a9c0c88e405a06c27dcf49ada62eb2b"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed RIPEMD160 56 letters"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed RIPEMD160 56 letters"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /****************************************************************************************** * Test 8 times "1234567890" (All confirmed from outside sources) ******************************************************************************************/ input.clear(); input.writeString("12345678901234567890123456789012345678901234567890123456789012345678901234567890"); /***************************************************************************************** * RIPEMD160 8 times "1234567890" *****************************************************************************************/ input.setReadOffset(0); ripEMD160(&input, input.length(), &resultDigest); correctDigest.writeHex("9b752e45573d4b39f4dbd3323cab82bf63326bfb"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed RIPEMD160 8 times \"1234567890\""); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed RIPEMD160 8 times \"1234567890\""); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /****************************************************************************************** * Test million a (All confirmed from outside sources) ******************************************************************************************/ input.clear(); for(unsigned int i=0;i<1000000;i++) input.writeByte('a'); /***************************************************************************************** * RIPEMD160 million a *****************************************************************************************/ input.setReadOffset(0); ripEMD160(&input, input.length(), &resultDigest); correctDigest.writeHex("52783243c1697bdbe16d37f97f68f08325dc1528"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed RIPEMD160 million a"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed RIPEMD160 million a"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /****************************************************************************************** * Test random data 150 (All confirmed from outside sources) ******************************************************************************************/ input.clear(); input.writeHex("182d86ed47df1c1673558e3d1ed08dcc7de3a906615589084f6316e71cabd18e7c37451d514d9ede653b03d047345a522ef1c55f27ac8bff3564635116855d862bac06d21f8abb3026746b5c74dd46e9679bd30137bf6b143b67249931ff3f0a3f50426a4479871d15603aa4151ef4b9321762553df9946f5bc194ac4a44e94205d8b0854f1722ea6915770f03bc598c306cabf23878"); /***************************************************************************************** * RIPEMD160 random data 150 *****************************************************************************************/ input.setReadOffset(0); ripEMD160(&input, input.length(), &resultDigest); correctDigest.writeHex("de4c02fe629897e3a2658c042f260a96ccfccac9"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed RIPEMD160 random data 150"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed RIPEMD160 random data 150"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /****************************************************************************************** * Test hello ******************************************************************************************/ input.clear(); input.writeString("hello"); /***************************************************************************************** * SHA256_SHA256 hello *****************************************************************************************/ input.setReadOffset(0); Digest doubleSHA256(SHA256_SHA256); doubleSHA256.writeStream(&input, input.length()); doubleSHA256.getResult(&resultDigest); correctDigest.writeHex("9595c9df90075148eb06860365df33584b75bff782a510c6cd4883a419833d50"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed SHA256_SHA256 hello"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed SHA256_SHA256 hello"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * SHA256_RIPEMD160 hello *****************************************************************************************/ input.setReadOffset(0); Digest sha256RIPEMD160(SHA256_RIPEMD160); sha256RIPEMD160.writeStream(&input, input.length()); sha256RIPEMD160.getResult(&resultDigest); correctDigest.writeHex("b6a9c8c230722b7c748331a8b450f05566dc7d0f"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed SHA256_RIPEMD160 hello"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed SHA256_RIPEMD160 hello"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * SipHash24 *****************************************************************************************/ uint8_t sipHash24Vectors[64][8] = { { 0x31, 0x0e, 0x0e, 0xdd, 0x47, 0xdb, 0x6f, 0x72, }, { 0xfd, 0x67, 0xdc, 0x93, 0xc5, 0x39, 0xf8, 0x74, }, { 0x5a, 0x4f, 0xa9, 0xd9, 0x09, 0x80, 0x6c, 0x0d, }, { 0x2d, 0x7e, 0xfb, 0xd7, 0x96, 0x66, 0x67, 0x85, }, { 0xb7, 0x87, 0x71, 0x27, 0xe0, 0x94, 0x27, 0xcf, }, { 0x8d, 0xa6, 0x99, 0xcd, 0x64, 0x55, 0x76, 0x18, }, { 0xce, 0xe3, 0xfe, 0x58, 0x6e, 0x46, 0xc9, 0xcb, }, { 0x37, 0xd1, 0x01, 0x8b, 0xf5, 0x00, 0x02, 0xab, }, { 0x62, 0x24, 0x93, 0x9a, 0x79, 0xf5, 0xf5, 0x93, }, { 0xb0, 0xe4, 0xa9, 0x0b, 0xdf, 0x82, 0x00, 0x9e, }, { 0xf3, 0xb9, 0xdd, 0x94, 0xc5, 0xbb, 0x5d, 0x7a, }, { 0xa7, 0xad, 0x6b, 0x22, 0x46, 0x2f, 0xb3, 0xf4, }, { 0xfb, 0xe5, 0x0e, 0x86, 0xbc, 0x8f, 0x1e, 0x75, }, { 0x90, 0x3d, 0x84, 0xc0, 0x27, 0x56, 0xea, 0x14, }, { 0xee, 0xf2, 0x7a, 0x8e, 0x90, 0xca, 0x23, 0xf7, }, { 0xe5, 0x45, 0xbe, 0x49, 0x61, 0xca, 0x29, 0xa1, }, { 0xdb, 0x9b, 0xc2, 0x57, 0x7f, 0xcc, 0x2a, 0x3f, }, { 0x94, 0x47, 0xbe, 0x2c, 0xf5, 0xe9, 0x9a, 0x69, }, { 0x9c, 0xd3, 0x8d, 0x96, 0xf0, 0xb3, 0xc1, 0x4b, }, { 0xbd, 0x61, 0x79, 0xa7, 0x1d, 0xc9, 0x6d, 0xbb, }, { 0x98, 0xee, 0xa2, 0x1a, 0xf2, 0x5c, 0xd6, 0xbe, }, { 0xc7, 0x67, 0x3b, 0x2e, 0xb0, 0xcb, 0xf2, 0xd0, }, { 0x88, 0x3e, 0xa3, 0xe3, 0x95, 0x67, 0x53, 0x93, }, { 0xc8, 0xce, 0x5c, 0xcd, 0x8c, 0x03, 0x0c, 0xa8, }, { 0x94, 0xaf, 0x49, 0xf6, 0xc6, 0x50, 0xad, 0xb8, }, { 0xea, 0xb8, 0x85, 0x8a, 0xde, 0x92, 0xe1, 0xbc, }, { 0xf3, 0x15, 0xbb, 0x5b, 0xb8, 0x35, 0xd8, 0x17, }, { 0xad, 0xcf, 0x6b, 0x07, 0x63, 0x61, 0x2e, 0x2f, }, { 0xa5, 0xc9, 0x1d, 0xa7, 0xac, 0xaa, 0x4d, 0xde, }, { 0x71, 0x65, 0x95, 0x87, 0x66, 0x50, 0xa2, 0xa6, }, { 0x28, 0xef, 0x49, 0x5c, 0x53, 0xa3, 0x87, 0xad, }, { 0x42, 0xc3, 0x41, 0xd8, 0xfa, 0x92, 0xd8, 0x32, }, { 0xce, 0x7c, 0xf2, 0x72, 0x2f, 0x51, 0x27, 0x71, }, { 0xe3, 0x78, 0x59, 0xf9, 0x46, 0x23, 0xf3, 0xa7, }, { 0x38, 0x12, 0x05, 0xbb, 0x1a, 0xb0, 0xe0, 0x12, }, { 0xae, 0x97, 0xa1, 0x0f, 0xd4, 0x34, 0xe0, 0x15, }, { 0xb4, 0xa3, 0x15, 0x08, 0xbe, 0xff, 0x4d, 0x31, }, { 0x81, 0x39, 0x62, 0x29, 0xf0, 0x90, 0x79, 0x02, }, { 0x4d, 0x0c, 0xf4, 0x9e, 0xe5, 0xd4, 0xdc, 0xca, }, { 0x5c, 0x73, 0x33, 0x6a, 0x76, 0xd8, 0xbf, 0x9a, }, { 0xd0, 0xa7, 0x04, 0x53, 0x6b, 0xa9, 0x3e, 0x0e, }, { 0x92, 0x59, 0x58, 0xfc, 0xd6, 0x42, 0x0c, 0xad, }, { 0xa9, 0x15, 0xc2, 0x9b, 0xc8, 0x06, 0x73, 0x18, }, { 0x95, 0x2b, 0x79, 0xf3, 0xbc, 0x0a, 0xa6, 0xd4, }, { 0xf2, 0x1d, 0xf2, 0xe4, 0x1d, 0x45, 0x35, 0xf9, }, { 0x87, 0x57, 0x75, 0x19, 0x04, 0x8f, 0x53, 0xa9, }, { 0x10, 0xa5, 0x6c, 0xf5, 0xdf, 0xcd, 0x9a, 0xdb, }, { 0xeb, 0x75, 0x09, 0x5c, 0xcd, 0x98, 0x6c, 0xd0, }, { 0x51, 0xa9, 0xcb, 0x9e, 0xcb, 0xa3, 0x12, 0xe6, }, { 0x96, 0xaf, 0xad, 0xfc, 0x2c, 0xe6, 0x66, 0xc7, }, { 0x72, 0xfe, 0x52, 0x97, 0x5a, 0x43, 0x64, 0xee, }, { 0x5a, 0x16, 0x45, 0xb2, 0x76, 0xd5, 0x92, 0xa1, }, { 0xb2, 0x74, 0xcb, 0x8e, 0xbf, 0x87, 0x87, 0x0a, }, { 0x6f, 0x9b, 0xb4, 0x20, 0x3d, 0xe7, 0xb3, 0x81, }, { 0xea, 0xec, 0xb2, 0xa3, 0x0b, 0x22, 0xa8, 0x7f, }, { 0x99, 0x24, 0xa4, 0x3c, 0xc1, 0x31, 0x57, 0x24, }, { 0xbd, 0x83, 0x8d, 0x3a, 0xaf, 0xbf, 0x8d, 0xb7, }, { 0x0b, 0x1a, 0x2a, 0x32, 0x65, 0xd5, 0x1a, 0xea, }, { 0x13, 0x50, 0x79, 0xa3, 0x23, 0x1c, 0xe6, 0x60, }, { 0x93, 0x2b, 0x28, 0x46, 0xe4, 0xd7, 0x06, 0x66, }, { 0xe1, 0x91, 0x5f, 0x5c, 0xb1, 0xec, 0xa4, 0x6c, }, { 0xf3, 0x25, 0x96, 0x5c, 0xa1, 0x6d, 0x62, 0x9f, }, { 0x57, 0x5f, 0xf2, 0x8e, 0x60, 0x38, 0x1b, 0xe5, }, { 0x72, 0x45, 0x06, 0xeb, 0x4c, 0x32, 0x8a, 0x95, } }; uint64_t key0 = 0x0706050403020100; uint64_t key1 = 0x0f0e0d0c0b0a0908; //Log::addFormatted(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "SipHash-2-4 : Key0 0x%08x%08x, Key1 0x%08x%08x", // key0 >> 32, key0 & 0xffffffff, key1 >> 32, key1 & 0xffffffff); uint64_t sipResult; uint64_t check; uint8_t *byte; uint8_t sipHash24Data[64]; bool sipSuccess = true; for(unsigned int i=0;i<64;++i) { sipHash24Data[i] = i; sipResult = sipHash24(sipHash24Data, i, key0, key1); check = 0; byte = sipHash24Vectors[i]; for(unsigned int j=0;j<8;++j) check |= (uint64_t)*byte++ << (j * 8); if(sipResult != check) { Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed SipHash24 %d 0x%08x%08x == 0x%08x%08x", i, sipResult >> 32, sipResult & 0xffffffff, check >> 32, check & 0xffffffff); result = false; sipSuccess = false; } } if(sipSuccess) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed SipHash24 test set"); /***************************************************************************************** * MurMur3 empty 0 *****************************************************************************************/ input.clear(); Digest murmur3Digest(MURMUR3); murmur3Digest.initialize(0); murmur3Digest.writeStream(&input, input.length()); murmur3Digest.getResult(&resultDigest); correctDigest.writeUnsignedInt(0x00000000); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 empty 0"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 empty 0"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * MurMur3 empty 1 *****************************************************************************************/ input.clear(); murmur3Digest.initialize(1); murmur3Digest.writeStream(&input, input.length()); murmur3Digest.getResult(&resultDigest); correctDigest.writeUnsignedInt(0x514E28B7); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 empty 1"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 empty 1"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * MurMur3 empty ffffffff *****************************************************************************************/ input.clear(); murmur3Digest.initialize(0xffffffff); murmur3Digest.writeStream(&input, input.length()); murmur3Digest.getResult(&resultDigest); correctDigest.writeUnsignedInt(0x81F16F39); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 empty ffffffff"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 empty ffffffff"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * MurMur3 ffffffff 0 *****************************************************************************************/ input.clear(); input.writeUnsignedInt(0xffffffff); murmur3Digest.initialize(0); murmur3Digest.writeStream(&input, input.length()); murmur3Digest.getResult(&resultDigest); correctDigest.writeUnsignedInt(0x76293B50); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 ffffffff 0"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 ffffffff 0"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * MurMur3 87654321 0 *****************************************************************************************/ input.clear(); input.writeUnsignedInt(0x87654321); murmur3Digest.initialize(0); murmur3Digest.writeStream(&input, input.length()); murmur3Digest.getResult(&resultDigest); correctDigest.writeUnsignedInt(0xF55B516B); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 87654321 0"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 87654321 0"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * MurMur3 87654321 5082EDEE *****************************************************************************************/ input.clear(); input.writeUnsignedInt(0x87654321); murmur3Digest.initialize(0x5082EDEE); murmur3Digest.writeStream(&input, input.length()); murmur3Digest.getResult(&resultDigest); correctDigest.writeUnsignedInt(0x2362F9DE); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 87654321 5082EDEE"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 87654321 5082EDEE"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * MurMur3 214365 0 *****************************************************************************************/ input.clear(); input.writeHex("214365"); murmur3Digest.initialize(0); murmur3Digest.writeStream(&input, input.length()); murmur3Digest.getResult(&resultDigest); correctDigest.writeUnsignedInt(0x7E4A8634); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 214365 0"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 214365 0"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * MurMur3 2143 0 *****************************************************************************************/ input.clear(); input.writeHex("2143"); murmur3Digest.initialize(0); murmur3Digest.writeStream(&input, input.length()); murmur3Digest.getResult(&resultDigest); correctDigest.writeUnsignedInt(0xA0F7B07A); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 2143 0"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 2143 0"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * MurMur3 21 0 *****************************************************************************************/ input.clear(); input.writeHex("21"); murmur3Digest.initialize(0); murmur3Digest.writeStream(&input, input.length()); murmur3Digest.getResult(&resultDigest); correctDigest.writeUnsignedInt(0x72661CF4); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 21 0"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 21 0"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * MurMur3 00000000 0 *****************************************************************************************/ input.clear(); input.writeHex("00000000"); murmur3Digest.initialize(0); murmur3Digest.writeStream(&input, input.length()); murmur3Digest.getResult(&resultDigest); correctDigest.writeUnsignedInt(0x2362F9DE); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 00000000 0"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 00000000 0"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * MurMur3 000000 0 *****************************************************************************************/ input.clear(); input.writeHex("000000"); murmur3Digest.initialize(0); murmur3Digest.writeStream(&input, input.length()); murmur3Digest.getResult(&resultDigest); correctDigest.writeUnsignedInt(0x85F0B427); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 000000 0"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 000000 0"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * MurMur3 0000 0 *****************************************************************************************/ input.clear(); input.writeHex("0000"); murmur3Digest.initialize(0); murmur3Digest.writeStream(&input, input.length()); murmur3Digest.getResult(&resultDigest); correctDigest.writeUnsignedInt(0x30F4C306); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 0000 0"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 0000 0"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * MurMur3 00 0 *****************************************************************************************/ input.clear(); input.writeHex("00"); murmur3Digest.initialize(0); murmur3Digest.writeStream(&input, input.length()); murmur3Digest.getResult(&resultDigest); correctDigest.writeUnsignedInt(0x514E28B7); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 00 0"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 00 0"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * MurMur3 empty 0 direct *****************************************************************************************/ input.clear(); uint32_t murMur3Result = murMur3(input.begin(), input.length(), 0); uint32_t murMur3Correct = 0x00000000; if(murMur3Correct == murMur3Result) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 direct empty 0"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 direct empty 0"); Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Correct : 0x%08x", murMur3Correct); Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Result : 0x%08x", murMur3Result); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * MurMur3 empty 1 direct *****************************************************************************************/ input.clear(); murMur3Result = murMur3(input.begin(), input.length(), 1); murMur3Correct = 0x514E28B7; if(murMur3Correct == murMur3Result) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 direct empty 1"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 direct empty 1"); Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Correct : 0x%08x", murMur3Correct); Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Result : 0x%08x", murMur3Result); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * MurMur3 empty ffffffff direct *****************************************************************************************/ input.clear(); murMur3Result = murMur3(input.begin(), input.length(), 0xffffffff); murMur3Correct = 0x81F16F39; if(murMur3Correct == murMur3Result) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 direct empty ffffffff"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 direct empty ffffffff"); Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Correct : 0x%08x", murMur3Correct); Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Result : 0x%08x", murMur3Result); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * MurMur3 ffffffff 0 direct *****************************************************************************************/ input.clear(); input.writeUnsignedInt(0xffffffff); murMur3Result = murMur3(input.begin(), input.length(), 0); murMur3Correct = 0x76293B50; if(murMur3Correct == murMur3Result) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 direct ffffffff 0"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 direct ffffffff 0"); Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Correct : 0x%08x", murMur3Correct); Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Result : 0x%08x", murMur3Result); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * MurMur3 87654321 0 direct *****************************************************************************************/ input.clear(); input.writeUnsignedInt(0x87654321); murMur3Result = murMur3(input.begin(), input.length(), 0); murMur3Correct = 0xF55B516B; if(murMur3Correct == murMur3Result) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 direct 87654321 0"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 direct 87654321 0"); Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Correct : 0x%08x", murMur3Correct); Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Result : 0x%08x", murMur3Result); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * MurMur3 87654321 5082EDEE direct *****************************************************************************************/ input.clear(); input.writeUnsignedInt(0x87654321); murMur3Result = murMur3(input.begin(), input.length(), 0x5082EDEE); murMur3Correct = 0x2362F9DE; if(murMur3Correct == murMur3Result) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 direct 87654321 5082EDEE"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 direct 87654321 5082EDEE"); Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Correct : 0x%08x", murMur3Correct); Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Result : 0x%08x", murMur3Result); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * MurMur3 214365 0 direct *****************************************************************************************/ input.clear(); input.writeHex("214365"); murMur3Result = murMur3(input.begin(), input.length(), 0); murMur3Correct = 0x7E4A8634; if(murMur3Correct == murMur3Result) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 direct 214365 0"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 direct 214365 0"); Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Correct : 0x%08x", murMur3Correct); Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Result : 0x%08x", murMur3Result); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * MurMur3 2143 0 direct *****************************************************************************************/ input.clear(); input.writeHex("2143"); murMur3Result = murMur3(input.begin(), input.length(), 0); murMur3Correct = 0xA0F7B07A; if(murMur3Correct == murMur3Result) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 direct 2143 0"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 direct 2143 0"); Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Correct : 0x%08x", murMur3Correct); Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Result : 0x%08x", murMur3Result); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * MurMur3 21 0 direct *****************************************************************************************/ input.clear(); input.writeHex("21"); murMur3Result = murMur3(input.begin(), input.length(), 0); murMur3Correct = 0x72661CF4; if(murMur3Correct == murMur3Result) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 direct 21 0"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 direct 21 0"); Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Correct : 0x%08x", murMur3Correct); Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Result : 0x%08x", murMur3Result); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * MurMur3 00000000 0 direct *****************************************************************************************/ input.clear(); input.writeHex("00000000"); murMur3Result = murMur3(input.begin(), input.length(), 0); murMur3Correct = 0x2362F9DE; if(murMur3Correct == murMur3Result) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 direct 00000000 0"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 direct 00000000 0"); Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Correct : 0x%08x", murMur3Correct); Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Result : 0x%08x", murMur3Result); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * MurMur3 000000 0 direct *****************************************************************************************/ input.clear(); input.writeHex("000000"); murMur3Result = murMur3(input.begin(), input.length(), 0); murMur3Correct = 0x85F0B427; if(murMur3Correct == murMur3Result) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 direct 000000 0"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 direct 000000 0"); Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Correct : 0x%08x", murMur3Correct); Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Result : 0x%08x", murMur3Result); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * MurMur3 0000 0 direct *****************************************************************************************/ input.clear(); input.writeHex("0000"); murMur3Result = murMur3(input.begin(), input.length(), 0); murMur3Correct = 0x30F4C306; if(murMur3Correct == murMur3Result) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 direct 0000 0"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 direct 0000 0"); Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Correct : 0x%08x", murMur3Correct); Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Result : 0x%08x", murMur3Result); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * MurMur3 00 0 direct *****************************************************************************************/ input.clear(); input.writeHex("00"); murMur3Result = murMur3(input.begin(), input.length(), 0); murMur3Correct = 0x514E28B7; if(murMur3Correct == murMur3Result) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 direct 00 0"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 direct 00 0"); Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Correct : 0x%08x", murMur3Correct); Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Result : 0x%08x", murMur3Result); result = false; } correctDigest.clear(); resultDigest.clear(); return result; } }
145,529
56,620
#include "stdafx.h" #include "DummyTransformationSceneNode.h" #include "SceneNode.h" using namespace irr; using namespace System; namespace Irrlicht { namespace Scene { DummyTransformationSceneNode^ DummyTransformationSceneNode::Wrap(scene::IDummyTransformationSceneNode* ref) { if (ref == nullptr) return nullptr; return gcnew DummyTransformationSceneNode(ref); } DummyTransformationSceneNode::DummyTransformationSceneNode(scene::IDummyTransformationSceneNode* ref) : SceneNode(ref) { LIME_ASSERT(ref != nullptr); m_DummyTransformationSceneNode = ref; } Matrix^ DummyTransformationSceneNode::RelativeTransformationMatrix::get() { return gcnew Matrix(&m_DummyTransformationSceneNode->getRelativeTransformationMatrix()); } } // end namespace Scene } // end namespace Irrlicht
814
249
/*----------------------------------------------------------------------------*/ /* Copyright (c) 2018-2020 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ #include "frc/Watchdog.h" #include <atomic> #include <hal/Notifier.h> #include <wpi/Format.h> #include <wpi/SmallString.h> #include <wpi/priority_queue.h> #include <wpi/raw_ostream.h> #include "frc/DriverStation.h" #include "frc2/Timer.h" using namespace frc; class Watchdog::Impl { public: Impl(); ~Impl(); template <typename T> struct DerefGreater { constexpr bool operator()(const T& lhs, const T& rhs) const { return *lhs > *rhs; } }; wpi::mutex m_mutex; std::atomic<HAL_NotifierHandle> m_notifier; wpi::priority_queue<Watchdog*, std::vector<Watchdog*>, DerefGreater<Watchdog*>> m_watchdogs; void UpdateAlarm(); private: void Main(); std::thread m_thread; }; Watchdog::Impl::Impl() { int32_t status = 0; m_notifier = HAL_InitializeNotifier(&status); wpi_setGlobalHALError(status); HAL_SetNotifierName(m_notifier, "Watchdog", &status); m_thread = std::thread([=] { Main(); }); } Watchdog::Impl::~Impl() { int32_t status = 0; // atomically set handle to 0, then clean HAL_NotifierHandle handle = m_notifier.exchange(0); HAL_StopNotifier(handle, &status); wpi_setGlobalHALError(status); // Join the thread to ensure the handler has exited. if (m_thread.joinable()) m_thread.join(); HAL_CleanNotifier(handle, &status); } void Watchdog::Impl::UpdateAlarm() { int32_t status = 0; // Return if we are being destructed, or were not created successfully auto notifier = m_notifier.load(); if (notifier == 0) return; if (m_watchdogs.empty()) HAL_CancelNotifierAlarm(notifier, &status); else HAL_UpdateNotifierAlarm( notifier, static_cast<uint64_t>(m_watchdogs.top()->m_expirationTime.to<double>() * 1e6), &status); wpi_setGlobalHALError(status); } void Watchdog::Impl::Main() { for (;;) { int32_t status = 0; HAL_NotifierHandle notifier = m_notifier.load(); if (notifier == 0) break; uint64_t curTime = HAL_WaitForNotifierAlarm(notifier, &status); if (curTime == 0 || status != 0) break; std::unique_lock lock(m_mutex); if (m_watchdogs.empty()) continue; // If the condition variable timed out, that means a Watchdog timeout // has occurred, so call its timeout function. auto watchdog = m_watchdogs.pop(); units::second_t now{curTime * 1e-6}; if (now - watchdog->m_lastTimeoutPrintTime > kMinPrintPeriod) { watchdog->m_lastTimeoutPrintTime = now; if (!watchdog->m_suppressTimeoutMessage) { wpi::SmallString<128> buf; wpi::raw_svector_ostream err(buf); err << "Watchdog not fed within " << wpi::format("%.6f", watchdog->m_timeout.to<double>()) << "s\n"; frc::DriverStation::ReportWarning(err.str()); } } // Set expiration flag before calling the callback so any manipulation // of the flag in the callback (e.g., calling Disable()) isn't // clobbered. watchdog->m_isExpired = true; lock.unlock(); watchdog->m_callback(); lock.lock(); UpdateAlarm(); } } Watchdog::Watchdog(double timeout, std::function<void()> callback) : Watchdog(units::second_t{timeout}, callback) {} Watchdog::Watchdog(units::second_t timeout, std::function<void()> callback) : m_timeout(timeout), m_callback(callback), m_impl(GetImpl()) {} Watchdog::~Watchdog() { Disable(); } Watchdog::Watchdog(Watchdog&& rhs) { *this = std::move(rhs); } Watchdog& Watchdog::operator=(Watchdog&& rhs) { m_impl = rhs.m_impl; std::scoped_lock lock(m_impl->m_mutex); m_startTime = rhs.m_startTime; m_timeout = rhs.m_timeout; m_expirationTime = rhs.m_expirationTime; m_callback = std::move(rhs.m_callback); m_lastTimeoutPrintTime = rhs.m_lastTimeoutPrintTime; m_suppressTimeoutMessage = rhs.m_suppressTimeoutMessage; m_tracer = std::move(rhs.m_tracer); m_isExpired = rhs.m_isExpired; if (m_expirationTime != 0_s) { m_impl->m_watchdogs.remove(&rhs); m_impl->m_watchdogs.emplace(this); } return *this; } double Watchdog::GetTime() const { return (frc2::Timer::GetFPGATimestamp() - m_startTime).to<double>(); } void Watchdog::SetTimeout(double timeout) { SetTimeout(units::second_t{timeout}); } void Watchdog::SetTimeout(units::second_t timeout) { m_startTime = frc2::Timer::GetFPGATimestamp(); m_tracer.ClearEpochs(); std::scoped_lock lock(m_impl->m_mutex); m_timeout = timeout; m_isExpired = false; m_impl->m_watchdogs.remove(this); m_expirationTime = m_startTime + m_timeout; m_impl->m_watchdogs.emplace(this); m_impl->UpdateAlarm(); } double Watchdog::GetTimeout() const { std::scoped_lock lock(m_impl->m_mutex); return m_timeout.to<double>(); } bool Watchdog::IsExpired() const { std::scoped_lock lock(m_impl->m_mutex); return m_isExpired; } void Watchdog::AddEpoch(wpi::StringRef epochName) { m_tracer.AddEpoch(epochName); } void Watchdog::PrintEpochs() { m_tracer.PrintEpochs(); } void Watchdog::Reset() { Enable(); } void Watchdog::Enable() { m_startTime = frc2::Timer::GetFPGATimestamp(); m_tracer.ClearEpochs(); std::scoped_lock lock(m_impl->m_mutex); m_isExpired = false; m_impl->m_watchdogs.remove(this); m_expirationTime = m_startTime + m_timeout; m_impl->m_watchdogs.emplace(this); m_impl->UpdateAlarm(); } void Watchdog::Disable() { std::scoped_lock lock(m_impl->m_mutex); if (m_expirationTime != 0_s) { m_impl->m_watchdogs.remove(this); m_expirationTime = 0_s; m_impl->UpdateAlarm(); } } void Watchdog::SuppressTimeoutMessage(bool suppress) { m_suppressTimeoutMessage = suppress; } bool Watchdog::operator>(const Watchdog& rhs) const { return m_expirationTime > rhs.m_expirationTime; } Watchdog::Impl* Watchdog::GetImpl() { static Impl inst; return &inst; }
6,285
2,284
#include "pmx_utils.h" #include "ppl/nn/models/pmx/oputils/onnx/lstm.h" using namespace std; using namespace ppl::nn::onnx; using namespace ppl::nn::pmx::onnx; TEST_F(PmxTest, test_lstm) { DEFINE_ARG(LSTMParam, lstm); lstm_param1.activation_alpha = {0.23f}; lstm_param1.activation_beta = {0.33f}; lstm_param1.activations = {ppl::nn::onnx::LSTMParam::ACT_ELU}; lstm_param1.clip = 0.34; lstm_param1.direction = ppl::nn::onnx::LSTMParam::DIR_REVERSE; lstm_param1.hidden_size = 44; lstm_param1.input_forget = 23; MAKE_BUFFER(LSTMParam, lstm); std::vector<float> activation_alpha = lstm_param3.activation_alpha; std::vector<float> activation_beta = lstm_param3.activation_beta; std::vector<ppl::nn::onnx::LSTMParam::activation_t> activations = lstm_param3.activations; float clip = lstm_param3.clip; ppl::nn::onnx::LSTMParam::direction_t direction = lstm_param3.direction; int32_t hidden_size = lstm_param3.hidden_size; int32_t input_forget = lstm_param3.input_forget; EXPECT_FLOAT_EQ(0.23, activation_alpha[0]); EXPECT_FLOAT_EQ(0.33, activation_beta[0]); EXPECT_EQ(ppl::nn::onnx::LSTMParam::ACT_ELU, activations[0]); EXPECT_FLOAT_EQ(0.34, clip); EXPECT_EQ(ppl::nn::onnx::LSTMParam::DIR_REVERSE, direction); EXPECT_EQ(44, hidden_size); EXPECT_EQ(23, input_forget); }
1,356
590
/* * ModelLoader.h * * Created on: Jan 23, 2013 * Author: anton */ #ifndef MODELLOADER_H_ #define MODELLOADER_H_ #include "gdx-cpp/graphics/g3d/ModelLoaderHints.hpp" #include "gdx-cpp/graphics/g3d/model/Model.hpp" #include "gdx-cpp/files/FileHandle.hpp" namespace gdx { class ModelLoader { public: virtual Model* load(const FileHandle& file, ModelLoaderHints hints) = 0; }; } /* namespace gdx */ #endif /* MODELLOADER_H_ */
442
188
/* * Copyright (C) 2016 Open Source Robotics Foundation * * 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 "gazebo/gui/plot/VariablePill.hh" #include "gazebo/gui/plot/VariablePill_TEST.hh" ///////////////////////////////////////////////// void VariablePill_TEST::Variable() { this->resMaxPercentChange = 5.0; this->shareMaxPercentChange = 2.0; this->Load("worlds/empty.world"); // test various variable pill set/get functions gazebo::gui::VariablePill *var01 = new gazebo::gui::VariablePill(nullptr); QVERIFY(var01 != nullptr); // name std::string varName = "var01name"; var01->SetName(varName); QCOMPARE(var01->Name(), varName); // text std::string varText = "var01"; var01->SetText(varText); QCOMPARE(var01->Text(), varText); // selected state QCOMPARE(var01->IsSelected(), false); var01->SetSelected(true); QCOMPARE(var01->IsSelected(), true); var01->SetSelected(false); QCOMPARE(var01->IsSelected(), false); // parent QVERIFY(var01->Parent() == nullptr); gazebo::gui::VariablePill *var02 = new gazebo::gui::VariablePill(nullptr); QVERIFY(var02 != nullptr); var01->SetParent(var02); QCOMPARE(var01->Parent(), var02); delete var01; delete var02; } ///////////////////////////////////////////////// void VariablePill_TEST::VariableId() { this->resMaxPercentChange = 5.0; this->shareMaxPercentChange = 2.0; this->Load("worlds/empty.world"); // a set of unique variable ids std::set<unsigned int> ids; // Create new variable pills and verify they all have unique ids gazebo::gui::VariablePill *var01 = new gazebo::gui::VariablePill(nullptr); QVERIFY(var01 != nullptr); unsigned int id = var01->Id(); QVERIFY(id != gazebo::gui::VariablePill::EmptyVariable); QVERIFY(ids.count(id) == 0u); ids.insert(id); gazebo::gui::VariablePill *var02 = new gazebo::gui::VariablePill(nullptr); QVERIFY(var02 != nullptr); id = var02->Id(); QVERIFY(id != gazebo::gui::VariablePill::EmptyVariable); QVERIFY(ids.count(id) == 0u); ids.insert(id); gazebo::gui::VariablePill *var03 = new gazebo::gui::VariablePill(nullptr); QVERIFY(var03 != nullptr); id = var03->Id(); QVERIFY(id != gazebo::gui::VariablePill::EmptyVariable); QVERIFY(ids.count(id) == 0u); ids.insert(id); delete var01; delete var02; delete var03; } ///////////////////////////////////////////////// void VariablePill_TEST::MultiVariable() { // create 4 variable pills gazebo::gui::VariablePill *var01 = new gazebo::gui::VariablePill(nullptr); QVERIFY(var01 != nullptr); QCOMPARE(var01->VariablePillCount(), 0u); gazebo::gui::VariablePill *var02 = new gazebo::gui::VariablePill(nullptr); QVERIFY(var02 != nullptr); QCOMPARE(var02->VariablePillCount(), 0u); gazebo::gui::VariablePill *var03 = new gazebo::gui::VariablePill(nullptr); QVERIFY(var03 != nullptr); QCOMPARE(var03->VariablePillCount(), 0u); gazebo::gui::VariablePill *var04 = new gazebo::gui::VariablePill(nullptr); QVERIFY(var04 != nullptr); QCOMPARE(var04->VariablePillCount(), 0u); // add var02 to var01 - var01 becomes a multi-variable pill var01->AddVariablePill(var02); QCOMPARE(var01->VariablePillCount(), 1u); QVERIFY(var02->Parent() == var01); // verify we cannot add var03 to var02 because var02 already has a parent // this will implicitly add var03 to var02's parent var02->AddVariablePill(var03); QCOMPARE(var01->VariablePillCount(), 2u); QCOMPARE(var02->VariablePillCount(), 0u); QVERIFY(var02->Parent() == var01); QVERIFY(var03->Parent() == var01); // verify we can add var03 to var01 again // their the parent-child relationship should not change var01->AddVariablePill(var03); QCOMPARE(var01->VariablePillCount(), 2u); QVERIFY(var03->Parent() == var01); // move var03 from var01 to var04 var04->AddVariablePill(var03); QCOMPARE(var01->VariablePillCount(), 1u); QCOMPARE(var04->VariablePillCount(), 1u); QVERIFY(var03->Parent() == var04); // remove var02 from var01 var01->RemoveVariablePill(var02); QCOMPARE(var01->VariablePillCount(), 0u); QVERIFY(var02->Parent() == nullptr); // try remove var02 again - it should not do anything var01->RemoveVariablePill(var02); QCOMPARE(var01->VariablePillCount(), 0u); QVERIFY(var02->Parent() == nullptr); // remove var03 from var04 var04->RemoveVariablePill(var03); QCOMPARE(var04->VariablePillCount(), 0u); QVERIFY(var03->Parent() == nullptr); delete var01; delete var02; delete var03; delete var04; } // Generate a main function for the test QTEST_MAIN(VariablePill_TEST)
5,100
1,969
/** * @file <argos3/testing/experiment/test_loop_functions.cpp> * * @author Carlo Pinciroli <ilpincy@gmail.com> */ #include "test_loop_functions.h" #include <argos3/plugins/robots/foot-bot/simulator/footbot_entity.h> #include <argos3/plugins/simulator/entities/led_entity.h> /****************************************/ /****************************************/ void CTestLoopFunctions::Init(TConfigurationNode& t_tree) { LOG << "CTestLoopFunctions init running!\n"; CFootBotEntity& fb = dynamic_cast<CFootBotEntity&>(GetSpace().GetEntity("fb")); CLEDEntity& cLedA = fb.GetComponent<CLEDEntity>("leds.led[led_2]"); CLEDEntity& cLedB = fb.GetComponent<CLEDEntity>("leds.led[led_3]"); CLEDEntity& cLedC = fb.GetComponent<CLEDEntity>("leds.led[led_4]"); cLedA.SetColor(CColor::GREEN); cLedB.SetColor(CColor::BLUE); cLedC.SetColor(CColor::YELLOW); } CColor CTestLoopFunctions::GetFloorColor(const CVector2& c_pos_on_floor) { if(Sign(c_pos_on_floor.GetX()) == Sign(c_pos_on_floor.GetY())) return CColor::GRAY30; else return CColor::GRAY70; } /****************************************/ /****************************************/ REGISTER_LOOP_FUNCTIONS(CTestLoopFunctions, "test_lf");
1,234
476
/* Copyright (c) MediaArea.net SARL. All Rights Reserved. * * Use of this source code is governed by a BSD-style license that can * be found in the License.html file in the root of the source tree. */ //--------------------------------------------------------------------------- // For user: you can disable or enable it //#define __MEDIAINFO_DEBUG_AZUREBLOB__ //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- // Pre-compilation #include "MediaInfo/PreComp.h" #ifdef __BORLANDC__ #pragma hdrstop #endif //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #include "MediaInfo/Setup.h" //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #if defined(__BORLANDC__) && defined (_DEBUG) //Why? in Debug mode with release Wx Libs, wxAssert is not defined? void wxAssert (int, const wchar_t*, int, const wchar_t*, const wchar_t*){return;} void wxAssert (int, const char*, int, const char*, const char*){return;} #endif #include "MediaInfoList.h" #include "MediaInfoList_Internal.h" using namespace ZenLib; //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- //To clarify the code namespace MediaInfoList_Debug { #ifdef __MEDIAINFO_DEBUG_AZUREBLOB__ #include <stdio.h> FILE* F; std::string Debug; #undef __MEDIAINFO_DEBUG_AZUREBLOB__ #define __MEDIAINFO_DEBUG_AZUREBLOB__(_TOAPPEND) \ F=fopen("MediaInfoList_Debug.txt", "a+t"); \ Debug.clear(); \ _TOAPPEND; \ Debug+="\r\n"; \ fwrite(Debug.c_str(), Debug.size(), 1, F); \ fclose(F); #else // __MEDIAINFO_DEBUG_AZUREBLOB__ #define __MEDIAINFO_DEBUG_AZUREBLOB__(_TOAPPEND) #endif // __MEDIAINFO_DEBUG_AZUREBLOB__ #ifdef __MEDIAINFO_DEBUG_AZUREBLOB__ #define EXECUTE_VOID(_METHOD,_DEBUGB) \ ((MediaInfo_Internal*)Internal)->_METHOD; #else //__MEDIAINFO_DEBUG_AZUREBLOB__ #define EXECUTE_VOID(_METHOD,_DEBUGB) \ ((MediaInfo_Internal*)Internal)->_METHOD; \ __MEDIAINFO_DEBUG_AZUREBLOB__(_DEBUGB) #endif //__MEDIAINFO_DEBUG_AZUREBLOB__ #ifdef __MEDIAINFO_DEBUG_AZUREBLOB__ #define EXECUTE_INT(_METHOD,_DEBUGB) \ return ((MediaInfo_Internal*)Internal)->_METHOD; #else //__MEDIAINFO_DEBUG_AZUREBLOB__ #define EXECUTE_INT(_METHOD, _DEBUGB) \ int64u ToReturn=((MediaInfo_Internal*)Internal)->_METHOD; \ __MEDIAINFO_DEBUG_AZUREBLOB__(_DEBUGB) \ return ToReturn; #endif //__MEDIAINFO_DEBUG_AZUREBLOB__ #ifdef __MEDIAINFO_DEBUG_AZUREBLOB__ #define EXECUTE_STRING(_METHOD,_DEBUGB) \ return ((MediaInfo_Internal*)Internal)->_METHOD; #else //__MEDIAINFO_DEBUG_AZUREBLOB__ #define EXECUTE_STRING(_METHOD,_DEBUGB) \ Ztring ToReturn=((MediaInfo_Internal*)Internal)->_METHOD; \ __MEDIAINFO_DEBUG_AZUREBLOB__(_DEBUGB) \ return ToReturn; #endif //__MEDIAINFO_DEBUG_AZUREBLOB__ } using namespace MediaInfoList_Debug; namespace MediaInfoLib { //*************************************************************************** // Gestion de la classe //*************************************************************************** //--------------------------------------------------------------------------- //Constructeurs MediaInfoList::MediaInfoList(size_t Count_Init) { __MEDIAINFO_DEBUG_AZUREBLOB__(Debug+="Construction";) Internal=new MediaInfoList_Internal(Count_Init); } //--------------------------------------------------------------------------- //Destructeur MediaInfoList::~MediaInfoList() { __MEDIAINFO_DEBUG_AZUREBLOB__(Debug+="Destruction";) delete Internal; //Internal=NULL; } //*************************************************************************** // Files //*************************************************************************** //--------------------------------------------------------------------------- size_t MediaInfoList::Open(const String &File, const fileoptions_t Options) { __MEDIAINFO_DEBUG_AZUREBLOB__(Debug+="Open, File=";Debug+=Ztring(File).To_Local().c_str();) return Internal->Open(File, Options); } //--------------------------------------------------------------------------- size_t MediaInfoList::Open_Buffer_Init (int64u File_Size_, int64u File_Offset_) { return Internal->Open_Buffer_Init(File_Size_, File_Offset_); } //--------------------------------------------------------------------------- size_t MediaInfoList::Open_Buffer_Continue (size_t FilePos, const int8u* ToAdd, size_t ToAdd_Size) { return Internal->Open_Buffer_Continue(FilePos, ToAdd, ToAdd_Size); } //--------------------------------------------------------------------------- int64u MediaInfoList::Open_Buffer_Continue_GoTo_Get (size_t FilePos) { return Internal->Open_Buffer_Continue_GoTo_Get(FilePos); } //--------------------------------------------------------------------------- size_t MediaInfoList::Open_Buffer_Finalize (size_t FilePos) { return Internal->Open_Buffer_Finalize(FilePos); } //--------------------------------------------------------------------------- size_t MediaInfoList::Save(size_t) { return 0; //Not yet implemented } //--------------------------------------------------------------------------- void MediaInfoList::Close(size_t FilePos) { Internal->Close(FilePos); } //*************************************************************************** // Get File info //*************************************************************************** //--------------------------------------------------------------------------- String MediaInfoList::Inform(size_t FilePos, size_t) { return Internal->Inform(FilePos); } //--------------------------------------------------------------------------- String MediaInfoList::Get(size_t FilePos, stream_t KindOfStream, size_t StreamNumber, size_t Parameter, info_t KindOfInfo) { return Internal->Get(FilePos, KindOfStream, StreamNumber, Parameter, KindOfInfo); } //--------------------------------------------------------------------------- String MediaInfoList::Get(size_t FilePos, stream_t KindOfStream, size_t StreamNumber, const String &Parameter, info_t KindOfInfo, info_t KindOfSearch) { //TRACE(Trace+=__T("Get(L), CompleteName=");Trace+=Info[FilePos].Get(Stream_General, 0, __T("CompleteName")).c_str();) //TRACE(Trace+=__T("Get(L), StreamKind=");Trace+=ZenLib::Ztring::ToZtring((int8u)KindOfStream);Trace+=__T(", StreamNumber=");Trace+=ZenLib::Ztring::ToZtring((int8u)StreamNumber);Trace+=__T(", Parameter=");Trace+=ZenLib::Ztring(Parameter);Trace+=__T(", KindOfInfo=");Trace+=ZenLib::Ztring::ToZtring((int8u)KindOfInfo);Trace+=__T(", KindOfSearch=");Trace+=ZenLib::Ztring::ToZtring((int8u)KindOfSearch);) //TRACE(Trace+=__T("Get(L), will return ");Trace+=Info[FilePos].Get(KindOfStream, StreamNumber, Parameter, KindOfInfo, KindOfSearch).c_str();) return Internal->Get(FilePos, KindOfStream, StreamNumber, Parameter, KindOfInfo, KindOfSearch); } //*************************************************************************** // Set File info //*************************************************************************** //--------------------------------------------------------------------------- size_t MediaInfoList::Set(const String &ToSet, size_t FilePos, stream_t StreamKind, size_t StreamNumber, size_t Parameter, const String &OldValue) { return Internal->Set(ToSet, FilePos, StreamKind, StreamNumber, Parameter, OldValue); } //--------------------------------------------------------------------------- size_t MediaInfoList::Set(const String &ToSet, size_t FilePos, stream_t StreamKind, size_t StreamNumber, const String &Parameter, const String &OldValue) { return Internal->Set(ToSet, FilePos, StreamKind, StreamNumber, Parameter, OldValue); } //*************************************************************************** // Output buffer //*************************************************************************** /* //--------------------------------------------------------------------------- char* MediaInfoList::Output_Buffer_Get (size_t FilePos, size_t &Output_Buffer_Size) { return Internal->Output_Buffer_Get(FilePos, Output_Buffer_Size); } */ //*************************************************************************** // Information //*************************************************************************** //--------------------------------------------------------------------------- String MediaInfoList::Option (const String &Option, const String &Value) { return Internal->Option(Option, Value); } //--------------------------------------------------------------------------- String MediaInfoList::Option_Static (const String &Option, const String &Value) { return MediaInfo::Option_Static(Option, Value); } //--------------------------------------------------------------------------- size_t MediaInfoList::State_Get() { return Internal->State_Get(); } //--------------------------------------------------------------------------- size_t MediaInfoList::Count_Get (size_t FilePos, stream_t StreamKind, size_t StreamNumber) { return Internal->Count_Get(FilePos, StreamKind, StreamNumber); } //--------------------------------------------------------------------------- size_t MediaInfoList::Count_Get() { return Internal->Count_Get(); } } //NameSpace
9,875
2,790
/* FENCE.hpp * by Lut99 * * Created: * 28/06/2021, 16:57:12 * Last edited: * 28/06/2021, 16:57:12 * Auto updated? * Yes * * Description: * Contains a class that wraps a VkFence object. **/ #ifndef RENDERING_FENCE_HPP #define RENDERING_FENCE_HPP #include <vulkan/vulkan.h> #include "../gpu/GPU.hpp" namespace Makma3D::Rendering { /* The Fence class, which wraps a VkFence object and manages its memory. */ class Fence { public: /* Channel name for the Fence class. */ static constexpr const char* channel = "Fence"; /* The GPU where the semaphore lives. */ const Rendering::GPU& gpu; private: /* The VkFence object we wrap. */ VkFence vk_fence; /* The flags used to create the fence. */ VkFenceCreateFlags vk_create_flags; public: /* Constructor for the Fence class, which takes completely nothing! (except for the GPU where it lives, obviously, and optionally some flags) */ Fence(const Rendering::GPU& gpu, VkFenceCreateFlags create_flags = 0); /* Copy constructor for the Fence class. */ Fence(const Fence& other); /* Move constructor for the Fence class. */ Fence(Fence&& other); /* Destructor for the Fence class. */ ~Fence(); /* Blocks the CPU until the Fence is signalled. */ inline void wait() const { vkWaitForFences(this->gpu, 1, &this->vk_fence, true, UINT64_MAX); } /* Resets the Fence once signalled. */ inline void reset() const { vkResetFences(this->gpu, 1, &this->vk_fence); } /* Expliticly returns the internal VkFence object. */ inline const VkFence& fence() const { return this->vk_fence; } /* Implicitly returns the internal VkFence object. */ inline operator VkFence() const { return this->vk_fence; } /* Copy assignment operator for the Fence class. */ inline Fence& operator=(const Fence& other) { return *this = Fence(other); } /* Move assignment operator for the Fence class. */ inline Fence& operator=(Fence&& other) { if (this != &other) { swap(*this, other); } return *this; } /* Swap operator for the Fence class. */ friend void swap(Fence& s1, Fence& s2); }; /* Swap operator for the Fence class. */ void swap(Fence& f1, Fence& f2); } #endif
2,381
797
#include <QtGui/QApplication> #include <iostream> #include "login.h" bool hasArgument(const char* p, int argc, char* argv[]) { for (int i = 0; i < argc; i++) { int j = 0; bool areEqual = true; while (p[j] && argv[i][j] && areEqual) { if (p[j] != argv[i][j]) areEqual = false; j++; } if (areEqual) return true; } return false; } int main(int argc, char* argv[]) { netMain(); if (hasArgument("--server", argc, argv)) { srvMain(); return 0; } QApplication a(argc, argv); Login l; l.show(); return a.exec(); }
549
256
#include "solution.h" xor_linked_list::xor_linked_list() : memory_(3), size_{0} {} void xor_linked_list::add(std::int32_t value) { if (size_ == 0) { memory_[0] = {0, value}; size_++; return; } // resize internam memory if necessary if (size_ == memory_.size() - 1) { memory_.resize(2 * size_); } // find last std::size_t idx = 0; std::size_t prev = 0; std::size_t next; while ((next = memory_[idx].nxp ^ prev) != 0) { prev = idx; idx = next; } // "allocate memory" memory_[idx + 1] = {idx ^ 0, value}; memory_[idx].nxp = prev ^ (idx + 1); size_++; } std::optional<std::int32_t> xor_linked_list::get(std::size_t target) { if (target >= size_) { return {}; } if (target == 0) { return memory_[0].value; } std::size_t idx = 0; std::size_t prev = 0; std::size_t next; while ((next = memory_[idx].nxp ^ prev) != 0) { prev = idx; idx = next; if (idx == target) { return {memory_[idx].value}; } } return {}; }
1,120
437
#include "Expression.h" Expression::Expression(Expressions typeExp, Symboles type):Symbole(type) { this->typeExp=typeExp; expression = NULL; } Expression::Expression():Symbole(type) { expression = NULL; } Expressions Expression::getExprType() { return this->typeExp; } Expression::~Expression() { //dtor } void Expression::afficher() { cout << "error : call to Expression::afficher()" << endl; } Expression * Expression::getExpression() { return this->expression; } void Expression::setExpression(Expression *expr) { this->expression=expr; } string Expression::afficherExprType() { return exprTypes[this->typeExp]; }
639
210
// Created on: 1995-01-27 // Created by: Jacques GOUSSARD // Copyright (c) 1995-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _GeomInt_ParFunctionOfMyGradientOfTheComputeLineBezierOfWLApprox_HeaderFile #define _GeomInt_ParFunctionOfMyGradientOfTheComputeLineBezierOfWLApprox_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <Standard_Boolean.hxx> #include <GeomInt_TheMultiLineOfWLApprox.hxx> #include <AppParCurves_MultiCurve.hxx> #include <Standard_Integer.hxx> #include <math_Vector.hxx> #include <Standard_Real.hxx> #include <math_Matrix.hxx> #include <GeomInt_ParLeastSquareOfMyGradientOfTheComputeLineBezierOfWLApprox.hxx> #include <TColStd_HArray1OfInteger.hxx> #include <AppParCurves_HArray1OfConstraintCouple.hxx> #include <math_MultipleVarFunctionWithGradient.hxx> #include <AppParCurves_Constraint.hxx> class GeomInt_TheMultiLineOfWLApprox; class GeomInt_TheMultiLineToolOfWLApprox; class GeomInt_ParLeastSquareOfMyGradientOfTheComputeLineBezierOfWLApprox; class GeomInt_ResConstraintOfMyGradientOfTheComputeLineBezierOfWLApprox; class AppParCurves_MultiCurve; class GeomInt_ParFunctionOfMyGradientOfTheComputeLineBezierOfWLApprox : public math_MultipleVarFunctionWithGradient { public: DEFINE_STANDARD_ALLOC //! initializes the fields of the function. The approximating //! curve has the desired degree Deg. Standard_EXPORT GeomInt_ParFunctionOfMyGradientOfTheComputeLineBezierOfWLApprox(const GeomInt_TheMultiLineOfWLApprox& SSP, const Standard_Integer FirstPoint, const Standard_Integer LastPoint, const Handle(AppParCurves_HArray1OfConstraintCouple)& TheConstraints, const math_Vector& Parameters, const Standard_Integer Deg); //! returns the number of variables of the function. It //! corresponds to the number of MultiPoints. Standard_EXPORT Standard_Integer NbVariables() const; //! this method computes the new approximation of the //! MultiLine //! SSP and calculates F = sum (||Pui - Bi*Pi||2) for each //! point of the MultiLine. Standard_EXPORT Standard_Boolean Value (const math_Vector& X, Standard_Real& F); //! returns the gradient G of the sum above for the //! parameters Xi. Standard_EXPORT Standard_Boolean Gradient (const math_Vector& X, math_Vector& G); //! returns the value F=sum(||Pui - Bi*Pi||)2. //! returns the value G = grad(F) for the parameters Xi. Standard_EXPORT Standard_Boolean Values (const math_Vector& X, Standard_Real& F, math_Vector& G); //! returns the new parameters of the MultiLine. Standard_EXPORT const math_Vector& NewParameters() const; //! returns the MultiCurve approximating the set after //! computing the value F or Grad(F). Standard_EXPORT const AppParCurves_MultiCurve& CurveValue(); //! returns the distance between the MultiPoint of range //! IPoint and the curve CurveIndex. Standard_EXPORT Standard_Real Error (const Standard_Integer IPoint, const Standard_Integer CurveIndex) const; //! returns the maximum distance between the points //! and the MultiCurve. Standard_EXPORT Standard_Real MaxError3d() const; //! returns the maximum distance between the points //! and the MultiCurve. Standard_EXPORT Standard_Real MaxError2d() const; Standard_EXPORT AppParCurves_Constraint FirstConstraint (const Handle(AppParCurves_HArray1OfConstraintCouple)& TheConstraints, const Standard_Integer FirstPoint) const; Standard_EXPORT AppParCurves_Constraint LastConstraint (const Handle(AppParCurves_HArray1OfConstraintCouple)& TheConstraints, const Standard_Integer LastPoint) const; protected: //! this method is used each time Value or Gradient is //! needed. Standard_EXPORT void Perform (const math_Vector& X); private: Standard_Boolean Done; GeomInt_TheMultiLineOfWLApprox MyMultiLine; AppParCurves_MultiCurve MyMultiCurve; Standard_Integer Degre; math_Vector myParameters; Standard_Real FVal; math_Vector ValGrad_F; math_Matrix MyF; math_Matrix PTLX; math_Matrix PTLY; math_Matrix PTLZ; math_Matrix A; math_Matrix DA; GeomInt_ParLeastSquareOfMyGradientOfTheComputeLineBezierOfWLApprox MyLeastSquare; Standard_Boolean Contraintes; Standard_Integer NbP; Standard_Integer NbCu; Standard_Integer Adeb; Standard_Integer Afin; Handle(TColStd_HArray1OfInteger) tabdim; Standard_Real ERR3d; Standard_Real ERR2d; Standard_Integer FirstP; Standard_Integer LastP; Handle(AppParCurves_HArray1OfConstraintCouple) myConstraints; }; #endif // _GeomInt_ParFunctionOfMyGradientOfTheComputeLineBezierOfWLApprox_HeaderFile
5,248
1,753
// ----------------------------------------------------------------------- // // // MODULE : BodyFX.cpp // // PURPOSE : Body special FX - Implementation // // CREATED : 8/24/98 // // (c) 1998-1999 Monolith Productions, Inc. All Rights Reserved // // ----------------------------------------------------------------------- // #include "stdafx.h" #include "BodyFX.h" #include "GameClientShell.h" #include "SFXMsgIds.h" #include "ClientUtilities.h" #include "SoundMgr.h" #include "BaseScaleFX.h" #include "SurfaceFunctions.h" extern CGameClientShell* g_pGameClientShell; extern VarTrack g_vtBigHeadMode; // ----------------------------------------------------------------------- // // // ROUTINE: CBodyFX::CBodyFX() // // PURPOSE: Constructor // // ----------------------------------------------------------------------- // CBodyFX::CBodyFX() { m_fFaderTime = 3.0f; m_fFaderTimer = 3.0f; m_hMarker = LTNULL; m_bHasNodeControl = LTFALSE; } // ----------------------------------------------------------------------- // // // ROUTINE: CBodyFX::~CBodyFX() // // PURPOSE: Destructor // // ----------------------------------------------------------------------- // CBodyFX::~CBodyFX() { RemoveMarker(); if ( m_hServerObject ) { g_pModelLT->RemoveTracker(m_hServerObject, &m_TwitchTracker); } } // ----------------------------------------------------------------------- // // // ROUTINE: CBodyFX::Init // // PURPOSE: Init the Body fx // // ----------------------------------------------------------------------- // LTBOOL CBodyFX::Init(HLOCALOBJ hServObj, HMESSAGEREAD hMessage) { if (!CSpecialFX::Init(hServObj, hMessage)) return LTFALSE; if (!hMessage) return LTFALSE; BODYCREATESTRUCT bcs; bcs.hServerObj = hServObj; bcs.Read(g_pLTClient, hMessage); return Init(&bcs); } // ----------------------------------------------------------------------- // // // ROUTINE: CBodyFX::Init // // PURPOSE: Init the Body fx // // ----------------------------------------------------------------------- // LTBOOL CBodyFX::Init(SFXCREATESTRUCT* psfxCreateStruct) { if (!CSpecialFX::Init(psfxCreateStruct)) return LTFALSE; m_bs = *((BODYCREATESTRUCT*)psfxCreateStruct); g_pModelLT->AddTracker(m_bs.hServerObj, &m_TwitchTracker); return LTTRUE; } // ----------------------------------------------------------------------- // // // ROUTINE: CBodyFX::CreateObject // // PURPOSE: Create the various fx // // ----------------------------------------------------------------------- // LTBOOL CBodyFX::CreateObject(ILTClient* pClientDE) { if (!CSpecialFX::CreateObject(pClientDE) || !m_hServerObject) return LTFALSE; uint32 dwCFlags = m_pClientDE->GetObjectClientFlags(m_hServerObject); m_pClientDE->SetObjectClientFlags(m_hServerObject, dwCFlags | CF_NOTIFYMODELKEYS | CF_INSIDERADIUS); // uint32 dwCFlags = m_pClientDE->GetObjectClientFlags(m_hServerObject); // m_pClientDE->SetObjectClientFlags(m_hServerObject, dwCFlags | CF_NOTIFYMODELKEYS); return LTTRUE; } // ----------------------------------------------------------------------- // // // ROUTINE: CBodyFX::Update // // PURPOSE: Update the fx // // ----------------------------------------------------------------------- // LTBOOL CBodyFX::Update() { if (!m_pClientDE || !m_hServerObject || m_bWantRemove) return LTFALSE; // Only register/deregister once if (!m_bHasNodeControl && g_vtBigHeadMode.GetFloat()) { m_bHasNodeControl = LTTRUE; g_pLTClient->ModelNodeControl(m_hServerObject, CBodyFX::HandleBigHeadModeFn, this); } else if(m_bHasNodeControl && !g_vtBigHeadMode.GetFloat()) { m_bHasNodeControl = LTFALSE; g_pLTClient->ModelNodeControl(m_hServerObject, LTNULL, LTNULL); } switch ( m_bs.eBodyState ) { case eBodyStateFade: UpdateFade(); break; } if (g_pGameClientShell->GetGameType() != SINGLE && m_bs.nClientId != (uint8)-1) { UpdateMarker(); } return LTTRUE; } // ----------------------------------------------------------------------- // // // ROUTINE: CBodyFX::UpdateFade // // PURPOSE: Update the fx // // ----------------------------------------------------------------------- // void CBodyFX::UpdateFade() { HLOCALOBJ attachList[20]; uint32 dwListSize = 0; uint32 dwNumAttach = 0; g_pLTClient->GetAttachments(m_hServerObject, attachList, 20, &dwListSize, &dwNumAttach); int nNum = dwNumAttach <= dwListSize ? dwNumAttach : dwListSize; m_fFaderTime = Max<LTFLOAT>(0.0f, m_fFaderTime - g_pGameClientShell->GetFrameTime()); g_pLTClient->SetObjectColor(m_hServerObject, 1, 1, 1, m_fFaderTime/m_fFaderTimer); for (int i=0; i < nNum; i++) { g_pLTClient->SetObjectColor(attachList[i], 1, 1, 1, m_fFaderTime/m_fFaderTimer); } } // ----------------------------------------------------------------------- // // // ROUTINE: CBodyFX::OnServerMessage // // PURPOSE: Handle any messages from our server object... // // ----------------------------------------------------------------------- // LTBOOL CBodyFX::OnServerMessage(HMESSAGEREAD hMessage) { if (!CSpecialFX::OnServerMessage(hMessage)) return LTFALSE; uint8 nMsgId = g_pLTClient->ReadFromMessageByte(hMessage); switch(nMsgId) { case BFX_FADE_MSG: { m_bs.eBodyState = eBodyStateFade; } break; } return LTTRUE; } LTBOOL GroundFilterFn(HOBJECT hObj, void *pUserData) { return ( IsMainWorld(hObj) || (OT_WORLDMODEL == g_pLTClient->GetObjectType(hObj)) ); } void CBodyFX::OnModelKey(HLOCALOBJ hObj, ArgList *pArgs) { if (!m_hServerObject || !hObj || !pArgs || !pArgs->argv || pArgs->argc == 0) return; char* pKey = pArgs->argv[0]; if (!pKey) return; LTBOOL bSlump = !_stricmp(pKey, "NOISE"); LTBOOL bLand = !_stricmp(pKey, "LAND"); if ( bSlump || bLand ) { LTVector vPos; g_pLTClient->GetObjectPos(m_hServerObject, &vPos); IntersectQuery IQuery; IntersectInfo IInfo; IQuery.m_From = vPos; IQuery.m_To = vPos - LTVector(0,96,0); IQuery.m_Flags = INTERSECT_OBJECTS | INTERSECT_HPOLY | IGNORE_NONSOLID; IQuery.m_FilterFn = GroundFilterFn; SurfaceType eSurface; if (g_pLTClient->IntersectSegment(&IQuery, &IInfo)) { if (IInfo.m_hPoly && IInfo.m_hPoly != INVALID_HPOLY) { eSurface = (SurfaceType)GetSurfaceType(IInfo.m_hPoly); } else if (IInfo.m_hObject) // Get the texture flags from the object... { eSurface = (SurfaceType)GetSurfaceType(IInfo.m_hObject); } else { return; } } else { return; } // Play the noise SURFACE* pSurf = g_pSurfaceMgr->GetSurface(eSurface); _ASSERT(pSurf); if (!pSurf) return; if (bSlump && pSurf->szBodyFallSnd[0]) { g_pClientSoundMgr->PlaySoundFromPos(vPos, pSurf->szBodyFallSnd, pSurf->fBodyFallSndRadius, SOUNDPRIORITY_MISC_LOW); } else if (bLand && pSurf->szBodyLedgeFallSnd[0]) { g_pClientSoundMgr->PlaySoundFromPos(vPos, pSurf->szBodyLedgeFallSnd, pSurf->fBodyLedgeFallSndRadius, SOUNDPRIORITY_MISC_LOW); } } } // ----------------------------------------------------------------------- // // // ROUTINE: CBodyFX::UpdateMarker // // PURPOSE: Update the marker fx // // ----------------------------------------------------------------------- // void CBodyFX::UpdateMarker() { if (!m_pClientDE || !m_hServerObject) return; CClientInfoMgr *pClientMgr = g_pInterfaceMgr->GetClientInfoMgr(); if (!pClientMgr) return; CLIENT_INFO* pLocalInfo = pClientMgr->GetLocalClient(); CLIENT_INFO* pInfo = pClientMgr->GetClientByID(m_bs.nClientId); if (!pInfo || !pLocalInfo) return; LTBOOL bSame = (pInfo->team == pLocalInfo->team); if (bSame) { if (m_hMarker) RemoveMarker(); return; } uint32 dwFlags = g_pLTClient->GetObjectFlags(m_hServerObject); if (!(dwFlags & FLAG_VISIBLE)) { RemoveMarker(); return; } LTVector vU, vR, vF, vTemp, vDims, vPos; LTRotation rRot; ILTPhysics* pPhysics = m_pClientDE->Physics(); m_pClientDE->GetObjectPos(m_hServerObject, &vPos); pPhysics->GetObjectDims(m_hServerObject, &vDims); vPos.y += (vDims.y + 20.0f); if (!m_hMarker) { CreateMarker(vPos,bSame); } if (m_hMarker) { m_pClientDE->SetObjectPos(m_hMarker, &vPos); } } // ----------------------------------------------------------------------- // // // ROUTINE: CBodyFX::CreateMarker // // PURPOSE: Create marker special fx // // ----------------------------------------------------------------------- // void CBodyFX::CreateMarker(LTVector & vPos, LTBOOL bSame) { if (!m_pClientDE || !g_pGameClientShell || !m_hServerObject) return; if (!bSame) return; ObjectCreateStruct createStruct; INIT_OBJECTCREATESTRUCT(createStruct); CString str = g_pClientButeMgr->GetSpecialFXAttributeString("TeamSprite"); LTFLOAT fScaleMult = g_pClientButeMgr->GetSpecialFXAttributeFloat("TeamScale"); LTFLOAT fAlpha = g_pClientButeMgr->GetSpecialFXAttributeFloat("TeamAlpha"); LTVector vScale(1.0f,1.0f,1.0f); VEC_MULSCALAR(vScale, vScale, fScaleMult); SAFE_STRCPY(createStruct.m_Filename, (char *)(LPCSTR)str); createStruct.m_ObjectType = OT_SPRITE; createStruct.m_Flags = FLAG_VISIBLE | FLAG_FOGDISABLE | FLAG_NOLIGHT; createStruct.m_Pos = vPos; m_hMarker = m_pClientDE->CreateObject(&createStruct); if (!m_hMarker) return; m_pClientDE->SetObjectScale(m_hMarker, &vScale); LTFLOAT r, g, b, a; m_pClientDE->GetObjectColor(m_hServerObject, &r, &g, &b, &a); m_pClientDE->SetObjectColor(m_hObject, r, g, b, (fAlpha * a)); } // ----------------------------------------------------------------------- // // // ROUTINE: CBodyFX::RemoveMarker // // PURPOSE: Remove the marker fx // // ----------------------------------------------------------------------- // void CBodyFX::RemoveMarker() { if (!m_hMarker) return; g_pLTClient->DeleteObject(m_hMarker); m_hMarker = LTNULL; }
9,754
3,766
/* Code generated by IfcQuery EXPRESS generator, www.ifcquery.com */ #include <sstream> #include <limits> #include <map> #include "ifcpp/reader/ReaderUtil.h" #include "ifcpp/writer/WriterUtil.h" #include "ifcpp/model/BasicTypes.h" #include "ifcpp/model/BuildingException.h" #include "ifcpp/IFC4/include/IfcMeasureValue.h" #include "ifcpp/IFC4/include/IfcSizeSelect.h" #include "ifcpp/IFC4/include/IfcPositiveRatioMeasure.h" // TYPE IfcPositiveRatioMeasure = IfcRatioMeasure; shared_ptr<BuildingObject> IfcPositiveRatioMeasure::getDeepCopy( BuildingCopyOptions& options ) { shared_ptr<IfcPositiveRatioMeasure> copy_self( new IfcPositiveRatioMeasure() ); copy_self->m_value = m_value; return copy_self; } void IfcPositiveRatioMeasure::getStepParameter( std::stringstream& stream, bool is_select_type ) const { if( is_select_type ) { stream << "IFCPOSITIVERATIOMEASURE("; } stream << m_value; if( is_select_type ) { stream << ")"; } } const std::wstring IfcPositiveRatioMeasure::toString() const { std::wstringstream strs; strs << m_value; return strs.str(); } shared_ptr<IfcPositiveRatioMeasure> IfcPositiveRatioMeasure::createObjectFromSTEP( const std::wstring& arg, const std::map<int,shared_ptr<BuildingEntity> >& map ) { if( arg.compare( L"$" ) == 0 ) { return shared_ptr<IfcPositiveRatioMeasure>(); } if( arg.compare( L"*" ) == 0 ) { return shared_ptr<IfcPositiveRatioMeasure>(); } shared_ptr<IfcPositiveRatioMeasure> type_object( new IfcPositiveRatioMeasure() ); readReal( arg, type_object->m_value ); return type_object; }
1,584
590
// // FILE NAME: TestEvents_Scheduled.cpp // // AUTHOR: Dean Roddey // // CREATED: 09/21/2009 // // COPYRIGHT: Charmed Quark Systems, Ltd @ 2020 // // This software is copyrighted by 'Charmed Quark Systems, Ltd' and // the author (Dean Roddey.) It is licensed under the MIT Open Source // license: // // https://opensource.org/licenses/MIT // // DESCRIPTION: // // This file implements the tests for the scheduled events. // // CAVEATS/GOTCHAS: // // LOG: // // $Log$ // // --------------------------------------------------------------------------- // Include underlying headers // --------------------------------------------------------------------------- #include "TestEvents.hpp" // --------------------------------------------------------------------------- // Magic macros // --------------------------------------------------------------------------- RTTIDecls(TTest_Scheduled1,TTestFWTest) // --------------------------------------------------------------------------- // Local types and constants // --------------------------------------------------------------------------- namespace TestEvents_Scheduled { // Some faux lat/long values const tCIDLib::TFloat8 f8Lat = 37.3; const tCIDLib::TFloat8 f8Long = -121.88; } // --------------------------------------------------------------------------- // CLASS: TTest_BasicActVar // PREFIX: tfwt // --------------------------------------------------------------------------- // --------------------------------------------------------------------------- // TTest_Scheduled1: Constructor and Destructor // --------------------------------------------------------------------------- TTest_Scheduled1::TTest_Scheduled1() : TTestFWTest ( L"Scheduled Events 1", L"Basic tests of scheduled events", 3 ) { } TTest_Scheduled1::~TTest_Scheduled1() { } // --------------------------------------------------------------------------- // TTest_Scheduled1: Public, inherited methods // --------------------------------------------------------------------------- tTestFWLib::ETestRes TTest_Scheduled1::eRunTest( TTextStringOutStream& strmOut , tCIDLib::TBoolean& bWarning) { tTestFWLib::ETestRes eRes = tTestFWLib::ETestRes::Success; tCIDLib::TCard4 c4Hour; tCIDLib::TCard4 c4Millis; tCIDLib::TCard4 c4Min; tCIDLib::TCard4 c4Sec; tCIDLib::TCard4 c4Year; tCIDLib::EMonths eMonth; tCIDLib::TCard4 c4Day; // Do a basic one shot test { tCIDLib::TEncodedTime enctAt(TTime::enctNowPlusMins(2)); TCQCSchEvent csrcOneShot(L"Test one shot"); csrcOneShot.SetOneShot(enctAt); if (!csrcOneShot.bIsOneShot()) { strmOut << TFWCurLn << L"Event did not come back as one shot\n\n"; eRes = tTestFWLib::ETestRes::Failed; } if (!bCheckInfo(strmOut, TFWCurLn, csrcOneShot, tCQCKit::ESchTypes::Once, enctAt)) eRes = tTestFWLib::ETestRes::Failed; // Calculating the next time should do nothing CalcNext(csrcOneShot); if (!bCheckInfo(strmOut, TFWCurLn, csrcOneShot, tCQCKit::ESchTypes::Once, enctAt)) eRes = tTestFWLib::ETestRes::Failed; } // Do a daily one { // Set the start time to now tCIDLib::TEncodedTime enctStartAt = TTime::enctNow(); TCQCSchEvent csrcDaily(L"Daily event"); csrcDaily.SetScheduled ( tCQCKit::ESchTypes::Daily , 0 , 13 , 30 , 0 , enctStartAt ); // The initial starting time is now, so if the hour/minute is past // the one we set, then it should run today, else it will be tomorrow. // TTime tmNext(enctStartAt); tCIDLib::TEncodedTime enctTmp; tmNext.eExpandDetails ( c4Year , eMonth , c4Day , c4Hour , c4Min , c4Sec , c4Millis , enctTmp ); tmNext.FromDetails(c4Year, eMonth, c4Day, 13, 30); if ((c4Hour > 13) || (c4Hour == 13) && (c4Min > 30)) { // // It should run tomorrow. Note that this isn't the best way // to do this, since if we hit a day where there's a leap // minute or something, it could fail. But not too much risk // in reality. // tmNext += kCIDLib::enctOneDay; } if (!bCheckInfo(strmOut, TFWCurLn, csrcDaily, tCQCKit::ESchTypes::Daily, tmNext.enctTime())) eRes = tTestFWLib::ETestRes::Failed; } // Do a weekly one { // Set the start time to now tCIDLib::TEncodedTime enctStartAt = TTime::enctNow(); TCQCSchEvent csrcWeekly(L"Weekly event"); csrcWeekly.SetScheduled ( tCQCKit::ESchTypes::Weekly , 0 , 10 , 30 , 0x7F , enctStartAt ); } return eRes; } // --------------------------------------------------------------------------- // TTest_Scheduled1: Private, non-virtual methods // --------------------------------------------------------------------------- tCIDLib::TBoolean TTest_Scheduled1::bCheckInfo( TTextStringOutStream& strmOut , const TTFWCurLn& tfwclAt , const TCQCSchEvent& csrcToCheck , const tCQCKit::ESchTypes eType , const tCIDLib::TEncodedTime enctNext) { if (csrcToCheck.eType() != eType) { strmOut << tfwclAt << L"Wrong schedule type\n\n"; return kCIDLib::False; } // // Currently all times are rounded down to the previous minute, so // the actual value the caller set and passed in won't match. // // Probably we should just stop doing that and let them stagger out // through the minute to avoid peak activity. So, for now we just // round it here, so that it can be removed easily if we stop this // rounding. // tCIDLib::TEncodedTime enctActual = enctNext / kCIDLib::enctOneMinute; enctActual *= kCIDLib::enctOneMinute; if (csrcToCheck.enctAt() != enctActual) { strmOut << tfwclAt << L"Wrong next scheduled time\n\n"; return kCIDLib::False; } return kCIDLib::True; } // // Calculate the next time for the passed event, using the faux lat/long // positions. // tCIDLib::TVoid TTest_Scheduled1::CalcNext(TCQCSchEvent& csrcTar) { csrcTar.CalcNextTime(TestEvents_Scheduled::f8Lat, TestEvents_Scheduled::f8Long); }
6,750
2,147
// // Created by ice-phoenix on 5/27/15. // #include <llvm/Pass.h> #include "Passes/Defect/DefectManager.h" #include "Passes/PredicateStateAnalysis/PredicateStateAnalysis.h" #include "Passes/Tracker/SlotTrackerPass.h" #include "Reanimator/Reanimator.h" #include "State/Transformer/AggregateTransformer.h" #include "State/Transformer/ArrayBoundsCollector.h" #include "State/Transformer/TermCollector.h" #include "Util/passes.hpp" #include "Util/macros.h" namespace borealis { class ReanimatorPass : public llvm::ModulePass, public borealis::logging::ClassLevelLogging<ReanimatorPass> { public: static char ID; ReanimatorPass() : llvm::ModulePass(ID) {}; virtual bool runOnModule(llvm::Module&) override { auto&& DM = GetAnalysis<DefectManager>::doit(this); auto&& STP = GetAnalysis<SlotTrackerPass>::doit(this); for (auto&& di : DM.getData()) { auto&& adi = DM.getAdditionalInfo(di); if (not adi.satModel) continue; auto&& PSA = GetAnalysis<PredicateStateAnalysis>::doit(this, *adi.atFunc); auto&& ps = PSA.getInstructionState(adi.atInst); auto&& FN = FactoryNest(adi.atFunc->getDataLayout(), STP.getSlotTracker(adi.atFunc)); auto&& TC = TermCollector<>(FN); auto&& AC = ArrayBoundsCollector(FN); (TC + AC).transform(ps); auto&& reanim = Reanimator(adi.satModel.getUnsafe(), AC.getArrayBounds()); auto&& dbg = dbgs(); dbg << ps << endl; dbg << adi.satModel << endl; dbg << reanim.getArrayBoundsMap() << endl; for (auto&& v : util::viewContainer(TC.getTerms()) .filter(APPLY(llvm::is_one_of<ArgumentTerm, ValueTerm>))) { dbg << raise(reanim, v); } } return false; } virtual void getAnalysisUsage(llvm::AnalysisUsage& AU) const override { AU.setPreservesAll(); AUX<DefectManager>::addRequiredTransitive(AU); AUX<SlotTrackerPass>::addRequiredTransitive(AU); AUX<PredicateStateAnalysis>::addRequiredTransitive(AU); } virtual ~ReanimatorPass() = default; }; char ReanimatorPass::ID; static RegisterPass<ReanimatorPass> X("reanimator", "Pass that reanimates `variables` at defect sites"); } // namespace borealis #include "Util/unmacros.h"
2,406
798
#ifndef OSRM_EXTRACTOR_GUIDANCE_TURN_LANE_AUGMENTATION_HPP_ #define OSRM_EXTRACTOR_GUIDANCE_TURN_LANE_AUGMENTATION_HPP_ #include "extractor/guidance/intersection.hpp" #include "extractor/guidance/turn_lane_data.hpp" namespace osrm { namespace extractor { namespace guidance { namespace lanes { LaneDataVector handleNoneValueAtSimpleTurn(LaneDataVector lane_data, const Intersection &intersection); } // namespace lanes } // namespace guidance } // namespace extractor } // namespace osrm #endif /* OSRM_EXTRACTOR_GUIDANCE_TURN_LANE_AUGMENTATION_HPP_ */
601
216
#include <bits/stdc++.h> #define N 200020 #define ll long long using namespace std; inline int read(){ int x=0,f=1;char ch=getchar(); while(ch>'9'||ch<'0')ch=='-'&&(f=0)||(ch=getchar()); while(ch<='9'&&ch>='0')x=(x<<3)+(x<<1)+ch-'0',ch=getchar(); return f?x:-x; } int a[N]; bool b[N]; int n, sz; bool check(int x) { for (int i = 1; i <= sz; ++ i) { b[i] = a[i] <= x; } int rp = 0; for (int i = n + 1; i <= sz; ++ i) { if (b[i] == b[i - 1]) { rp = i - n; break; } } int lp = 0; for (int i = n - 1; i; -- i) { if (b[i] == b[i + 1]) { lp = n - i; break; } } if (!rp && !lp) return b[1]; if (!rp) return b[n - lp]; if (!lp) return b[n + rp]; if (rp == lp) return b[n - lp]; // printf("%d %d\n", lp, rp); if (rp < lp) { return b[n + rp]; } else { return b[n - lp]; } } int main(int argc, char const *argv[]) { n = read(); sz = 2 * n - 1; for (int i = 1; i <= sz; ++ i) { a[i] = read(); } int l = 1, r = sz; while (l <= r) { int mid = (l + r) >> 1; if (check(mid)) r = mid - 1; else l = mid + 1; } printf("%d\n", r + 1); return 0; } /* 二分答案,将每个小于等于 mid 的都看成 1,其余看成 0。 与 B 题同样的思想,有两个相邻的 0 或者相邻的 1,会一直冲到最顶上。 判断离中线最近的一根柱子即可。 1 6 3 7 4 5 2 1: 1 0 0 0 0 0 0 false 2: 1 0 0 0 0 0 1 false 3: 1 0 1 0 0 0 1 false 4: 1 0 1 0 1 0 1 true 5: 1 0 1 0 1 1 1 true 6: 1 1 1 0 1 1 1 true 7: 1 1 1 1 1 1 1 true 如果没有相邻的数字,那么答案就是第一个元素。 1 1 0 1 1 0 1 0 1 1 0 1 0 1 0 1 复杂度 O(nlogn) */
1,529
927
#include <chrono> #include "RandomGeneratorBase.hpp" namespace { long long createSeed() { auto seed = std::chrono::system_clock::now().time_since_epoch().count(); return seed; } } thread_local std::mt19937 RandomGeneratorBase::mEngine(static_cast<unsigned int>(createSeed()) ); std::mt19937 & RandomGeneratorBase::getEngine() const { return mEngine; }
363
132
// Copyright 2016 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 "third_party/blink/renderer/bindings/core/v8/generated_code_helper.h" #include "third_party/blink/renderer/bindings/core/v8/native_value_traits_impl.h" #include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h" #include "third_party/blink/renderer/bindings/core/v8/v8_css_style_declaration.h" #include "third_party/blink/renderer/bindings/core/v8/v8_element.h" #include "third_party/blink/renderer/bindings/core/v8/v8_set_return_value_for_core.h" #include "third_party/blink/renderer/core/dom/document.h" #include "third_party/blink/renderer/core/dom/range.h" #include "third_party/blink/renderer/core/execution_context/execution_context.h" #include "third_party/blink/renderer/core/frame/local_dom_window.h" #include "third_party/blink/renderer/core/html/custom/ce_reactions_scope.h" #include "third_party/blink/renderer/core/inspector/console_message.h" #include "third_party/blink/renderer/core/xml/dom_parser.h" #include "third_party/blink/renderer/platform/bindings/v8_binding.h" #include "third_party/blink/renderer/platform/bindings/v8_per_context_data.h" namespace blink { void V8ConstructorAttributeGetter( v8::Local<v8::Name> property_name, const v8::PropertyCallbackInfo<v8::Value>& info, const WrapperTypeInfo* wrapper_type_info) { RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT( info.GetIsolate(), "Blink_V8ConstructorAttributeGetter"); V8PerContextData* per_context_data = V8PerContextData::From(info.Holder()->CreationContext()); if (!per_context_data) return; V8SetReturnValue(info, per_context_data->ConstructorForType(wrapper_type_info)); } namespace { enum class IgnorePause { kDontIgnore, kIgnore }; // 'beforeunload' event listeners are runnable even when execution contexts are // paused. Use |RespectPause::kPrioritizeOverPause| in such a case. bool IsCallbackFunctionRunnableInternal( const ScriptState* callback_relevant_script_state, const ScriptState* incumbent_script_state, IgnorePause ignore_pause) { if (!callback_relevant_script_state->ContextIsValid()) return false; const ExecutionContext* relevant_execution_context = ExecutionContext::From(callback_relevant_script_state); if (!relevant_execution_context || relevant_execution_context->IsContextDestroyed()) { return false; } if (relevant_execution_context->IsContextPaused()) { if (ignore_pause == IgnorePause::kDontIgnore) return false; } // TODO(yukishiino): Callback function type value must make the incumbent // environment alive, i.e. the reference to v8::Context must be strong. v8::HandleScope handle_scope(incumbent_script_state->GetIsolate()); v8::Local<v8::Context> incumbent_context = incumbent_script_state->GetContext(); ExecutionContext* incumbent_execution_context = incumbent_context.IsEmpty() ? nullptr : ToExecutionContext(incumbent_context); // The incumbent realm schedules the currently-running callback although it // may not correspond to the currently-running function object. So we check // the incumbent context which originally schedules the currently-running // callback to see whether the script setting is disabled before invoking // the callback. // TODO(crbug.com/608641): move IsMainWorld check into // ExecutionContext::CanExecuteScripts() if (!incumbent_execution_context || incumbent_execution_context->IsContextDestroyed()) { return false; } if (incumbent_execution_context->IsContextPaused()) { if (ignore_pause == IgnorePause::kDontIgnore) return false; } return !incumbent_script_state->World().IsMainWorld() || incumbent_execution_context->CanExecuteScripts(kAboutToExecuteScript); } } // namespace bool IsCallbackFunctionRunnable( const ScriptState* callback_relevant_script_state, const ScriptState* incumbent_script_state) { return IsCallbackFunctionRunnableInternal(callback_relevant_script_state, incumbent_script_state, IgnorePause::kDontIgnore); } bool IsCallbackFunctionRunnableIgnoringPause( const ScriptState* callback_relevant_script_state, const ScriptState* incumbent_script_state) { return IsCallbackFunctionRunnableInternal(callback_relevant_script_state, incumbent_script_state, IgnorePause::kIgnore); } void V8SetReflectedBooleanAttribute( const v8::FunctionCallbackInfo<v8::Value>& info, const char* interface_name, const char* idl_attribute_name, const QualifiedName& content_attr) { v8::Isolate* isolate = info.GetIsolate(); Element* impl = V8Element::ToImpl(info.Holder()); ExceptionState exception_state(isolate, ExceptionState::kSetterContext, interface_name, idl_attribute_name); CEReactionsScope ce_reactions_scope; // Prepare the value to be set. bool cpp_value = NativeValueTraits<IDLBoolean>::NativeValue(isolate, info[0], exception_state); if (exception_state.HadException()) return; impl->SetBooleanAttribute(content_attr, cpp_value); } void V8SetReflectedDOMStringAttribute( const v8::FunctionCallbackInfo<v8::Value>& info, const QualifiedName& content_attr) { Element* impl = V8Element::ToImpl(info.Holder()); CEReactionsScope ce_reactions_scope; // Prepare the value to be set. V8StringResource<> cpp_value{info[0]}; if (!cpp_value.Prepare()) return; impl->setAttribute(content_attr, cpp_value); } void V8SetReflectedNullableDOMStringAttribute( const v8::FunctionCallbackInfo<v8::Value>& info, const QualifiedName& content_attr) { Element* impl = V8Element::ToImpl(info.Holder()); CEReactionsScope ce_reactions_scope; // Prepare the value to be set. V8StringResource<kTreatNullAndUndefinedAsNullString> cpp_value{info[0]}; if (!cpp_value.Prepare()) return; impl->setAttribute(content_attr, cpp_value); } namespace bindings { void SetupIDLInterfaceTemplate( v8::Isolate* isolate, const WrapperTypeInfo* wrapper_type_info, v8::Local<v8::ObjectTemplate> instance_template, v8::Local<v8::ObjectTemplate> prototype_template, v8::Local<v8::FunctionTemplate> interface_template, v8::Local<v8::FunctionTemplate> parent_interface_template) { v8::Local<v8::String> class_string = V8AtomicString(isolate, wrapper_type_info->interface_name); if (!parent_interface_template.IsEmpty()) interface_template->Inherit(parent_interface_template); interface_template->ReadOnlyPrototype(); interface_template->SetClassName(class_string); prototype_template->Set( v8::Symbol::GetToStringTag(isolate), class_string, static_cast<v8::PropertyAttribute>(v8::ReadOnly | v8::DontEnum)); instance_template->SetInternalFieldCount(kV8DefaultWrapperInternalFieldCount); } void SetupIDLNamespaceTemplate( v8::Isolate* isolate, const WrapperTypeInfo* wrapper_type_info, v8::Local<v8::ObjectTemplate> interface_template) { v8::Local<v8::String> class_string = V8AtomicString(isolate, wrapper_type_info->interface_name); interface_template->Set( v8::Symbol::GetToStringTag(isolate), class_string, static_cast<v8::PropertyAttribute>(v8::ReadOnly | v8::DontEnum)); } void SetupIDLCallbackInterfaceTemplate( v8::Isolate* isolate, const WrapperTypeInfo* wrapper_type_info, v8::Local<v8::FunctionTemplate> interface_template) { interface_template->RemovePrototype(); interface_template->SetClassName( V8AtomicString(isolate, wrapper_type_info->interface_name)); } base::Optional<size_t> FindIndexInEnumStringTable( v8::Isolate* isolate, v8::Local<v8::Value> value, base::span<const char* const> enum_value_table, const char* enum_type_name, ExceptionState& exception_state) { const String& str_value = NativeValueTraits<IDLStringV2>::NativeValue( isolate, value, exception_state); if (exception_state.HadException()) return base::nullopt; base::Optional<size_t> index = FindIndexInEnumStringTable(str_value, enum_value_table); if (!index.has_value()) { exception_state.ThrowTypeError("The provided value '" + str_value + "' is not a valid enum value of type " + enum_type_name + "."); } return index; } base::Optional<size_t> FindIndexInEnumStringTable( const String& str_value, base::span<const char* const> enum_value_table) { for (size_t i = 0; i < enum_value_table.size(); ++i) { if (Equal(str_value.Impl(), enum_value_table[i])) return i; } return base::nullopt; } void ReportInvalidEnumSetToAttribute(v8::Isolate* isolate, const String& value, const String& enum_type_name, ExceptionState& exception_state) { ScriptState* script_state = ScriptState::From(isolate->GetCurrentContext()); ExecutionContext* execution_context = ExecutionContext::From(script_state); exception_state.ThrowTypeError("The provided value '" + value + "' is not a valid enum value of type " + enum_type_name + "."); String message = exception_state.Message(); exception_state.ClearException(); execution_context->AddConsoleMessage(MakeGarbageCollected<ConsoleMessage>( mojom::blink::ConsoleMessageSource::kJavaScript, mojom::blink::ConsoleMessageLevel::kWarning, message, SourceLocation::Capture(execution_context))); } bool IsEsIterableObject(v8::Isolate* isolate, v8::Local<v8::Value> value, ExceptionState& exception_state) { // https://heycam.github.io/webidl/#es-overloads // step 9. Otherwise: if Type(V) is Object and ... if (!value->IsObject()) return false; // step 9.1. Let method be ? GetMethod(V, @@iterator). // https://tc39.es/ecma262/#sec-getmethod v8::TryCatch try_catch(isolate); v8::Local<v8::Value> iterator_key = v8::Symbol::GetIterator(isolate); v8::Local<v8::Value> iterator_value; if (!value.As<v8::Object>() ->Get(isolate->GetCurrentContext(), iterator_key) .ToLocal(&iterator_value)) { exception_state.RethrowV8Exception(try_catch.Exception()); return false; } if (iterator_value->IsNullOrUndefined()) return false; if (!iterator_value->IsFunction()) { exception_state.ThrowTypeError("@@iterator must be a function"); return false; } return true; } Document* ToDocumentFromExecutionContext(ExecutionContext* execution_context) { return DynamicTo<LocalDOMWindow>(execution_context)->document(); } ExecutionContext* ExecutionContextFromV8Wrappable(const Range* range) { return range->startContainer()->GetExecutionContext(); } ExecutionContext* ExecutionContextFromV8Wrappable(const DOMParser* parser) { return parser->GetWindow(); } v8::MaybeLocal<v8::Value> CreateNamedConstructorFunction( ScriptState* script_state, v8::FunctionCallback callback, const char* func_name, int func_length, const WrapperTypeInfo* wrapper_type_info) { v8::Isolate* isolate = script_state->GetIsolate(); const DOMWrapperWorld& world = script_state->World(); V8PerIsolateData* per_isolate_data = V8PerIsolateData::From(isolate); const void* callback_key = reinterpret_cast<const void*>(callback); if (!script_state->ContextIsValid()) { return v8::Undefined(isolate); } v8::Local<v8::FunctionTemplate> function_template = per_isolate_data->FindV8Template(world, callback_key) .As<v8::FunctionTemplate>(); if (function_template.IsEmpty()) { function_template = v8::FunctionTemplate::New( isolate, callback, v8::Local<v8::Value>(), v8::Local<v8::Signature>(), func_length, v8::ConstructorBehavior::kAllow, v8::SideEffectType::kHasSideEffect); v8::Local<v8::FunctionTemplate> interface_template = wrapper_type_info->GetV8ClassTemplate(isolate, world) .As<v8::FunctionTemplate>(); function_template->Inherit(interface_template); function_template->SetClassName(V8AtomicString(isolate, func_name)); function_template->InstanceTemplate()->SetInternalFieldCount( kV8DefaultWrapperInternalFieldCount); per_isolate_data->AddV8Template(world, callback_key, function_template); } v8::Local<v8::Context> context = script_state->GetContext(); V8PerContextData* per_context_data = V8PerContextData::From(context); v8::Local<v8::Function> function; if (!function_template->GetFunction(context).ToLocal(&function)) { return v8::MaybeLocal<v8::Value>(); } v8::Local<v8::Object> prototype_object = per_context_data->PrototypeForType(wrapper_type_info); bool did_define; if (!function ->DefineOwnProperty( context, V8AtomicString(isolate, "prototype"), prototype_object, static_cast<v8::PropertyAttribute>(v8::ReadOnly | v8::DontEnum | v8::DontDelete)) .To(&did_define)) { return v8::MaybeLocal<v8::Value>(); } CHECK(did_define); return function; } void InstallUnscopablePropertyNames( v8::Isolate* isolate, v8::Local<v8::Context> context, v8::Local<v8::Object> prototype_object, base::span<const char* const> property_name_table) { // 3.6.3. Interface prototype object // https://heycam.github.io/webidl/#interface-prototype-object // step 8. If interface has any member declared with the [Unscopable] // extended attribute, then: // step 8.1. Let unscopableObject be the result of performing // ! ObjectCreate(null). v8::Local<v8::Object> unscopable_object = v8::Object::New(isolate, v8::Null(isolate), nullptr, nullptr, 0); for (const char* const property_name : property_name_table) { // step 8.2.2. Perform ! CreateDataProperty(unscopableObject, id, true). unscopable_object ->CreateDataProperty(context, V8AtomicString(isolate, property_name), v8::True(isolate)) .ToChecked(); } // step 8.3. Let desc be the PropertyDescriptor{[[Value]]: unscopableObject, // [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true}. // step 8.4. Perform ! DefinePropertyOrThrow(interfaceProtoObj, // @@unscopables, desc). prototype_object ->DefineOwnProperty( context, v8::Symbol::GetUnscopables(isolate), unscopable_object, static_cast<v8::PropertyAttribute>(v8::ReadOnly | v8::DontEnum)) .ToChecked(); } v8::Local<v8::Array> EnumerateIndexedProperties(v8::Isolate* isolate, uint32_t length) { Vector<v8::Local<v8::Value>> elements; elements.ReserveCapacity(length); for (uint32_t i = 0; i < length; ++i) elements.UncheckedAppend(v8::Integer::New(isolate, i)); return v8::Array::New(isolate, elements.data(), elements.size()); } #if defined(USE_BLINK_V8_BINDING_NEW_IDL_INTERFACE) void InstallCSSPropertyAttributes( v8::Isolate* isolate, const DOMWrapperWorld& world, v8::Local<v8::Template> instance_template, v8::Local<v8::Template> prototype_template, v8::Local<v8::Template> interface_template, v8::Local<v8::Signature> signature, base::span<const char* const> css_property_names) { const String kGetPrefix = "get "; const String kSetPrefix = "set "; for (const char* const property_name : css_property_names) { v8::Local<v8::Value> v8_property_name = v8::External::New( isolate, const_cast<void*>(reinterpret_cast<const void*>(property_name))); v8::Local<v8::FunctionTemplate> get_func = v8::FunctionTemplate::New( isolate, CSSPropertyAttributeGet, v8_property_name, signature, 0, v8::ConstructorBehavior::kThrow, v8::SideEffectType::kHasNoSideEffect); v8::Local<v8::FunctionTemplate> set_func = v8::FunctionTemplate::New( isolate, CSSPropertyAttributeSet, v8_property_name, signature, 1, v8::ConstructorBehavior::kThrow, v8::SideEffectType::kHasSideEffect); get_func->SetAcceptAnyReceiver(false); set_func->SetAcceptAnyReceiver(false); get_func->SetClassName( V8AtomicString(isolate, String(kGetPrefix + property_name))); set_func->SetClassName( V8AtomicString(isolate, String(kSetPrefix + property_name))); prototype_template->SetAccessorProperty( V8AtomicString(isolate, property_name), get_func, set_func); } } void CSSPropertyAttributeGet(const v8::FunctionCallbackInfo<v8::Value>& info) { CSSStyleDeclaration* blink_receiver = V8CSSStyleDeclaration::ToWrappableUnsafe(info.This()); const char* property_name = reinterpret_cast<const char*>(info.Data().As<v8::External>()->Value()); auto&& return_value = blink_receiver->GetPropertyAttribute(property_name); bindings::V8SetReturnValue(info, return_value, info.GetIsolate(), bindings::V8ReturnValue::kNonNullable); } void CSSPropertyAttributeSet(const v8::FunctionCallbackInfo<v8::Value>& info) { v8::Isolate* isolate = info.GetIsolate(); const char* const class_like_name = "CSSStyleDeclaration"; const char* property_name = reinterpret_cast<const char*>(info.Data().As<v8::External>()->Value()); ExceptionState exception_state(isolate, ExceptionState::kSetterContext, class_like_name, property_name); // [CEReactions] CEReactionsScope ce_reactions_scope; v8::Local<v8::Object> v8_receiver = info.This(); CSSStyleDeclaration* blink_receiver = V8CSSStyleDeclaration::ToWrappableUnsafe(v8_receiver); v8::Local<v8::Value> v8_property_value = info[0]; auto&& arg1_value = NativeValueTraits<IDLStringTreatNullAsEmptyStringV2>::NativeValue( isolate, v8_property_value, exception_state); if (exception_state.HadException()) { return; } v8::Local<v8::Context> receiver_context = v8_receiver->CreationContext(); ExecutionContext* execution_context = ExecutionContext::From(receiver_context); blink_receiver->SetPropertyAttribute(execution_context, property_name, arg1_value, exception_state); } template <typename IDLType, typename ArgType, void (Element::*MemFunc)(const QualifiedName&, ArgType)> void PerformAttributeSetCEReactionsReflect( const v8::FunctionCallbackInfo<v8::Value>& info, const QualifiedName& content_attribute, const char* interface_name, const char* attribute_name) { v8::Isolate* isolate = info.GetIsolate(); ExceptionState exception_state(isolate, ExceptionState::kSetterContext, interface_name, attribute_name); if (UNLIKELY(info.Length() < 1)) { exception_state.ThrowTypeError( ExceptionMessages::NotEnoughArguments(1, info.Length())); return; } CEReactionsScope ce_reactions_scope; Element* blink_receiver = V8Element::ToWrappableUnsafe(info.This()); auto&& arg_value = NativeValueTraits<IDLType>::NativeValue(isolate, info[0], exception_state); if (exception_state.HadException()) return; (blink_receiver->*MemFunc)(content_attribute, arg_value); } void PerformAttributeSetCEReactionsReflectTypeBoolean( const v8::FunctionCallbackInfo<v8::Value>& info, const QualifiedName& content_attribute, const char* interface_name, const char* attribute_name) { PerformAttributeSetCEReactionsReflect<IDLBoolean, bool, &Element::SetBooleanAttribute>( info, content_attribute, interface_name, attribute_name); } void PerformAttributeSetCEReactionsReflectTypeString( const v8::FunctionCallbackInfo<v8::Value>& info, const QualifiedName& content_attribute, const char* interface_name, const char* attribute_name) { PerformAttributeSetCEReactionsReflect<IDLStringV2, const AtomicString&, &Element::setAttribute>( info, content_attribute, interface_name, attribute_name); } void PerformAttributeSetCEReactionsReflectTypeStringLegacyNullToEmptyString( const v8::FunctionCallbackInfo<v8::Value>& info, const QualifiedName& content_attribute, const char* interface_name, const char* attribute_name) { PerformAttributeSetCEReactionsReflect<IDLStringTreatNullAsEmptyStringV2, const AtomicString&, &Element::setAttribute>( info, content_attribute, interface_name, attribute_name); } void PerformAttributeSetCEReactionsReflectTypeStringOrNull( const v8::FunctionCallbackInfo<v8::Value>& info, const QualifiedName& content_attribute, const char* interface_name, const char* attribute_name) { PerformAttributeSetCEReactionsReflect< IDLNullable<IDLStringV2>, const AtomicString&, &Element::setAttribute>( info, content_attribute, interface_name, attribute_name); } #endif // USE_BLINK_V8_BINDING_NEW_IDL_INTERFACE } // namespace bindings } // namespace blink
21,481
6,679
// 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 "base/threading/platform_thread.h" #include <errno.h> #include <pthread.h> #include <sched.h> #include <stddef.h> #include <stdint.h> #include <sys/resource.h> #include <sys/time.h> #include <memory> // ducalpha: remove unnecessary dependency // #include "base/lazy_instance.h" #include "base/logging.h" #include "base/threading/platform_thread_internal_posix.h" // ducalpha: remove dependency on thread_id_name_manager //#include "base/threading/thread_id_name_manager.h" #include "base/threading/thread_restrictions.h" #include "build/build_config.h" #if defined(OS_LINUX) #include <sys/syscall.h> #elif defined(OS_ANDROID) #include <sys/types.h> #endif namespace base { void InitThreading(); void TerminateOnThread(); size_t GetDefaultThreadStackSize(const pthread_attr_t& attributes); namespace { struct ThreadParams { ThreadParams() : delegate(NULL), joinable(false), priority(ThreadPriority::NORMAL) {} PlatformThread::Delegate* delegate; bool joinable; ThreadPriority priority; }; void* ThreadFunc(void* params) { PlatformThread::Delegate* delegate = nullptr; { std::unique_ptr<ThreadParams> thread_params( static_cast<ThreadParams*>(params)); delegate = thread_params->delegate; if (!thread_params->joinable) base::ThreadRestrictions::SetSingletonAllowed(false); #if !defined(OS_NACL) // Threads on linux/android may inherit their priority from the thread // where they were created. This explicitly sets the priority of all new // threads. PlatformThread::SetCurrentThreadPriority(thread_params->priority); #endif } /* ducalpha: remove dependency on thread_id_name_manager ThreadIdNameManager::GetInstance()->RegisterThread( PlatformThread::CurrentHandle().platform_handle(), PlatformThread::CurrentId()); */ delegate->ThreadMain(); /* ducalpha: remove dependency on thread_id_name_manager ThreadIdNameManager::GetInstance()->RemoveName( PlatformThread::CurrentHandle().platform_handle(), PlatformThread::CurrentId()); */ base::TerminateOnThread(); return NULL; } bool CreateThread(size_t stack_size, bool joinable, PlatformThread::Delegate* delegate, PlatformThreadHandle* thread_handle, ThreadPriority priority) { DCHECK(thread_handle); base::InitThreading(); pthread_attr_t attributes; pthread_attr_init(&attributes); // Pthreads are joinable by default, so only specify the detached // attribute if the thread should be non-joinable. if (!joinable) pthread_attr_setdetachstate(&attributes, PTHREAD_CREATE_DETACHED); // Get a better default if available. if (stack_size == 0) stack_size = base::GetDefaultThreadStackSize(attributes); if (stack_size > 0) pthread_attr_setstacksize(&attributes, stack_size); std::unique_ptr<ThreadParams> params(new ThreadParams); params->delegate = delegate; params->joinable = joinable; params->priority = priority; pthread_t handle; int err = pthread_create(&handle, &attributes, ThreadFunc, params.get()); bool success = !err; if (success) { // ThreadParams should be deleted on the created thread after used. ignore_result(params.release()); } else { // Value of |handle| is undefined if pthread_create fails. handle = 0; errno = err; PLOG(ERROR) << "pthread_create"; } *thread_handle = PlatformThreadHandle(handle); pthread_attr_destroy(&attributes); return success; } } // namespace // static PlatformThreadId PlatformThread::CurrentId() { // Pthreads doesn't have the concept of a thread ID, so we have to reach down // into the kernel. #if defined(OS_MACOSX) return pthread_mach_thread_np(pthread_self()); #elif defined(OS_LINUX) return syscall(__NR_gettid); #elif defined(OS_ANDROID) return gettid(); #elif defined(OS_SOLARIS) || defined(OS_QNX) return pthread_self(); #elif defined(OS_NACL) && defined(__GLIBC__) return pthread_self(); #elif defined(OS_NACL) && !defined(__GLIBC__) // Pointers are 32-bits in NaCl. return reinterpret_cast<int32_t>(pthread_self()); #elif defined(OS_POSIX) return reinterpret_cast<int64_t>(pthread_self()); #endif } // static PlatformThreadRef PlatformThread::CurrentRef() { return PlatformThreadRef(pthread_self()); } // static PlatformThreadHandle PlatformThread::CurrentHandle() { return PlatformThreadHandle(pthread_self()); } // static void PlatformThread::YieldCurrentThread() { sched_yield(); } // static void PlatformThread::Sleep(TimeDelta duration) { struct timespec sleep_time, remaining; // Break the duration into seconds and nanoseconds. // NOTE: TimeDelta's microseconds are int64s while timespec's // nanoseconds are longs, so this unpacking must prevent overflow. sleep_time.tv_sec = duration.InSeconds(); duration -= TimeDelta::FromSeconds(sleep_time.tv_sec); sleep_time.tv_nsec = duration.InMicroseconds() * 1000; // nanoseconds while (nanosleep(&sleep_time, &remaining) == -1 && errno == EINTR) sleep_time = remaining; } // static /* ducalpha: remove dependency on thread_id_name_manager const char* PlatformThread::GetName() { return ThreadIdNameManager::GetInstance()->GetName(CurrentId()); } */ // static bool PlatformThread::CreateWithPriority(size_t stack_size, Delegate* delegate, PlatformThreadHandle* thread_handle, ThreadPriority priority) { return CreateThread(stack_size, true, // joinable thread delegate, thread_handle, priority); } // static bool PlatformThread::CreateNonJoinable(size_t stack_size, Delegate* delegate) { PlatformThreadHandle unused; bool result = CreateThread(stack_size, false /* non-joinable thread */, delegate, &unused, ThreadPriority::NORMAL); return result; } // static void PlatformThread::Join(PlatformThreadHandle thread_handle) { // Joining another thread may block the current thread for a long time, since // the thread referred to by |thread_handle| may still be running long-lived / // blocking tasks. base::ThreadRestrictions::AssertIOAllowed(); CHECK_EQ(0, pthread_join(thread_handle.platform_handle(), NULL)); } // Mac has its own Set/GetCurrentThreadPriority() implementations. #if !defined(OS_MACOSX) // static void PlatformThread::SetCurrentThreadPriority(ThreadPriority priority) { #if defined(OS_NACL) NOTIMPLEMENTED(); #else if (internal::SetCurrentThreadPriorityForPlatform(priority)) return; // setpriority(2) should change the whole thread group's (i.e. process) // priority. However, as stated in the bugs section of // http://man7.org/linux/man-pages/man2/getpriority.2.html: "under the current // Linux/NPTL implementation of POSIX threads, the nice value is a per-thread // attribute". Also, 0 is prefered to the current thread id since it is // equivalent but makes sandboxing easier (https://crbug.com/399473). const int nice_setting = internal::ThreadPriorityToNiceValue(priority); if (setpriority(PRIO_PROCESS, 0, nice_setting)) { DVPLOG(1) << "Failed to set nice value of thread (" << PlatformThread::CurrentId() << ") to " << nice_setting; } #endif // defined(OS_NACL) } // static ThreadPriority PlatformThread::GetCurrentThreadPriority() { #if defined(OS_NACL) NOTIMPLEMENTED(); return ThreadPriority::NORMAL; #else // Mirrors SetCurrentThreadPriority()'s implementation. ThreadPriority platform_specific_priority; if (internal::GetCurrentThreadPriorityForPlatform( &platform_specific_priority)) { return platform_specific_priority; } // Need to clear errno before calling getpriority(): // http://man7.org/linux/man-pages/man2/getpriority.2.html errno = 0; int nice_value = getpriority(PRIO_PROCESS, 0); if (errno != 0) { DVPLOG(1) << "Failed to get nice value of thread (" << PlatformThread::CurrentId() << ")"; return ThreadPriority::NORMAL; } return internal::NiceValueToThreadPriority(nice_value); #endif // !defined(OS_NACL) } #endif // !defined(OS_MACOSX) } // namespace base
8,344
2,613
#include <stan/math/prim/meta.hpp> #include <gtest/gtest.h> TEST(MathMetaPrim, or_type) { bool temp = stan::math::disjunction<std::true_type, std::true_type, std::true_type>::value; EXPECT_TRUE(temp); temp = stan::math::disjunction<std::false_type, std::false_type, std::false_type>::value; EXPECT_FALSE(temp); temp = stan::math::disjunction<std::false_type, std::true_type, std::true_type>::value; EXPECT_TRUE(temp); temp = stan::math::disjunction<std::true_type, std::true_type, std::false_type>::value; EXPECT_TRUE(temp); }
681
224
#include<bits/stdc++.h> #include <windows.h> #include <glut.h> #define pi (2*acos(0.0)) using namespace std; double cameraHeight; double cameraAngle; int drawgrid; int drawaxes; double angle; double cylinderHeight = 20, cylinderRadius = 30, sphereRadius = 20; double movementOnZaxes = 40, sphereZaxisMovement = 40, movementOnYaxes = 40, movementOnXaxes = 40; double distanceCoveredPerRotation, distanceCoveredPerRotationX, distanceCoveredPerRotationY; double distanceCoveredPerRotationZ, angleY, angleZ, angleChange, period = 60; struct Point { double x, y, z; Point() {} Point(double X, double Y, double Z) { x = X; y = Y; z = Z; } Point(const Point &p) : x(p.x), y(p.y), z(p.z) {} }; class Position { public: double dx, dy, dz, dtheta; Position() {} Position(double x, double y, double z, double theta) : dx(x), dy(y), dz(z), dtheta(theta) {} }; Position movement, currPos; Point crossProduct(const Point &a, const Point &b) { Point ret; ret.x = a.y * b.z - a.z * b.y; ret.y = -(a.x * b.z - a.z * b.x); ret.z = a.x * b.y - a.y * b.x; return ret; } Point cameraPos, cameraUp, cameraLook, cameraRight; double degreesToRadians(double angle_in_degrees) { return angle_in_degrees * (pi / 180.0); } void drawAxes() { if (drawaxes == 1) { glColor3f(1.0, 1.0, 1.0); glBegin(GL_LINES); { glColor3f(1, 0, 0); glVertex3f(100, 0, 0); glVertex3f(-100, 0, 0); glColor3f(0, 1, 0); glVertex3f(0, -100, 0); glVertex3f(0, 100, 0); glColor3f(0, 0, 1); glVertex3f(0, 0, 100); glVertex3f(0, 0, -100); } glEnd(); } } void drawGrid() { int i; glColor3f(0.6, 0.6, 0.6); //grey glBegin(GL_LINES); { for (i = -28; i <= 28; i++) { // if (i == 0) // continue; //SKIP the MAIN axes //lines parallel to Y-axis glVertex3f(i * 10, -300, 0); glVertex3f(i * 10, 300, 0); //lines parallel to X-axis glVertex3f(-300, i * 10, 0); glVertex3f(300, i * 10, 0); } } glEnd(); } void drawCylinder(double height, double radius, int slices) { struct point { double x, y, z; }; int i; struct point pointsUp[1000]; struct point pointsDown[1000]; glColor3f(0.7, 0.7, 0.7); //generate points for (i = 0; i <= slices; i++) { pointsUp[i].x = pointsDown[i].x = radius * cos(((double) i / (double) slices) * 2 * pi); pointsUp[i].y = pointsDown[i].y = radius * sin(((double) i / (double) slices) * 2 * pi); pointsUp[i].z = height / 2; pointsDown[i].z = -1.0 * pointsUp[i].z; } //draw segments using generated points for (i = 0; i < slices; i++) { glBegin(GL_LINES); { glVertex3f(static_cast<GLfloat>(pointsUp[i].x), static_cast<GLfloat>(pointsUp[i].y), static_cast<GLfloat>(pointsUp[i].z)); glVertex3f(static_cast<GLfloat>(pointsUp[i + 1].x), static_cast<GLfloat>(pointsUp[i + 1].y), static_cast<GLfloat>(pointsUp[i + 1].z)); glVertex3f(static_cast<GLfloat>(pointsDown[i].x), static_cast<GLfloat>(pointsDown[i].y), static_cast<GLfloat>(pointsDown[i].z)); glVertex3f(static_cast<GLfloat>(pointsDown[i + 1].x), static_cast<GLfloat>(pointsDown[i + 1].y), static_cast<GLfloat>(pointsDown[i + 1].z)); } glEnd(); // glColor3f(0, 1, 0); glColor3f(0*(double) i / (double) slices, 2*(double) i / (double) slices, 0*(double) i / (double) slices); glBegin(GL_QUADS); { glVertex3f(static_cast<GLfloat>(pointsUp[i].x), static_cast<GLfloat>(pointsUp[i].y), static_cast<GLfloat>(pointsUp[i].z)); glVertex3f(static_cast<GLfloat>(pointsDown[i].x), static_cast<GLfloat>(pointsDown[i].y), static_cast<GLfloat>(pointsDown[i].z)); glVertex3f(static_cast<GLfloat>(pointsDown[i + 1].x), static_cast<GLfloat>(pointsDown[i + 1].y), static_cast<GLfloat>(pointsDown[i + 1].z)); glVertex3f(static_cast<GLfloat>(pointsUp[i + 1].x), static_cast<GLfloat>(pointsUp[i + 1].y), static_cast<GLfloat>(pointsUp[i + 1].z)); } glEnd(); } } void drawInnerRectangle() { glBegin(GL_QUADS); { glVertex3f(-cylinderRadius, cylinderHeight / 4, 0); glVertex3f(-cylinderRadius, -cylinderHeight / 4, 0); glVertex3f(cylinderRadius, -cylinderHeight / 4, 0); glVertex3f(cylinderRadius, cylinderHeight / 4, 0); } glEnd(); } void drawWheelStructure() { glPushMatrix(); { glRotatef(90, 0, 0, 1); glRotatef(90, 0, 1, 0); drawCylinder(cylinderHeight, cylinderRadius, 30); } glPopMatrix(); glPushMatrix(); { glColor3f(1, 0, 0); drawInnerRectangle(); } glPopMatrix(); glPushMatrix(); { glRotatef(90, 0, 1, 0); glColor3f(0, 0, 1); drawInnerRectangle(); } glPopMatrix(); } void drawWheel() { glPushMatrix(); { glTranslatef(movement.dx, movement.dy, movement.dz); glTranslatef(0, 0, cylinderRadius); glRotatef(angleZ, 0, 0, 1); glRotatef(angleY, 0, 1, 0); drawWheelStructure(); } glPopMatrix(); } void keyboardListener(unsigned char key, int x, int y) { switch (key) { case 'a': angleZ += (2 * 180 / period); break; case 'd': angleZ -= (2 * 180 / period); break; case 'w': movement.dx -= distanceCoveredPerRotation * cos(degreesToRadians(angleZ)); movement.dy -= distanceCoveredPerRotation * sin(degreesToRadians(angleZ)); angleY -= (2 * 180 / period); break; case 's': movement.dx += distanceCoveredPerRotation * cos(degreesToRadians(angleZ)); movement.dy += distanceCoveredPerRotation * sin(degreesToRadians(angleZ)); angleY += (2 * 180 / period); break; default: break; } } void specialKeyListener(int key, int x, int y) { double mov = 3; switch (key) { case GLUT_KEY_RIGHT: cameraAngle += .05; break; case GLUT_KEY_LEFT: cameraAngle -= .05; break; case GLUT_KEY_UP: cameraHeight += 5; break; case GLUT_KEY_DOWN: cameraHeight -= 5; break; case GLUT_KEY_HOME: break; case GLUT_KEY_END: break; default: break; } } void mouseListener(int button, int state, int x, int y) //x, y is the x-y of the screen (2D) { switch (button) { case GLUT_LEFT_BUTTON: if (state == GLUT_DOWN) // 2 times?? in ONE click? -- solution is checking DOWN or UP { drawaxes = 1 - drawaxes; } break; case GLUT_RIGHT_BUTTON: //........ break; case GLUT_MIDDLE_BUTTON: //........ break; default: break; } } void display() { //clear the display glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glClearColor(0, 0, 0, 0); //color black glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); /********************* # set-up camera here # *********************/ //load the correct matrix -- MODEL-VIEW matrix glMatrixMode(GL_MODELVIEW); //initialize the matrix glLoadIdentity(); gluLookAt(200 * cos(cameraAngle), 200 * sin(cameraAngle), cameraHeight, 0, 0, 0, 0, 0, 1); //again select MODEL-VIEW glMatrixMode(GL_MODELVIEW); glColor3f(1, 0, 0); drawAxes(); drawGrid(); drawWheel(); glutSwapBuffers(); } void animate() { angle += 0.05; //codes for any changes in Models, Camera glutPostRedisplay(); } void init() { //codes for initialization drawgrid = 1; drawaxes = 1; cameraHeight = 150.0; cameraAngle = 1.0; angle = 0; /*** position movement initialization ***/ movement = Position(0, 0, 0, 0); currPos = Position(0, 0, 0, 0); distanceCoveredPerRotation = 2 * pi * cylinderRadius / period; angleZ = 0; angleY = 0; angleChange = 0; /** Camera initialization **/ drawgrid = 0; drawaxes = 1; cameraHeight = 80; cameraAngle = pi / 4; //clear the screen glClearColor(0, 0, 0, 0); /************************ / set-up projection here ************************/ //load the PROJECTION matrix glMatrixMode(GL_PROJECTION); //initialize the matrix glLoadIdentity(); //give PERSPECTIVE parameters gluPerspective(80, 1, 1, 1000.0); //field of view in the Y (vertically) //aspect ratio that determines the field of view in the X direction (horizontally) //near distance //far distance } int main(int argc, char **argv) { glutInit(&argc, argv); glutInitWindowSize(500, 500); glutInitWindowPosition(300, 100); glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGB); //Depth, Double buffer, RGB color glutCreateWindow("My OpenGL Program"); init(); glEnable(GL_DEPTH_TEST); //enable Depth Testing glutDisplayFunc(display); //display callback function glutIdleFunc(animate); //what you want to do in the idle time (when no drawing is occuring) glutKeyboardFunc(keyboardListener); glutSpecialFunc(specialKeyListener); glutMouseFunc(mouseListener); glutMainLoop(); //The main loop of OpenGL return 0; }
9,953
3,691
#include <iostream> #include <vector> using namespace std; using std::vector; using std::pair; void depth(vector<vector<int> > &adj ,vector<bool> &visited , int curr_node){ visited[curr_node] = true; for(int i = 0; i < adj[curr_node].size() ; i++){ int v = adj[curr_node][i]; if(!visited[v]) depth(adj,visited,v); } } int number_of_components(vector<vector<int> > &adj) { int res = 0; //write your code here vector<bool> visited(adj.size(),false); for(int i = 0 ; i < adj.size() ; i++){ if(!visited[i]){ depth(adj,visited,i); res++; } } return res; } int main() { size_t n, m; std::cin >> n >> m; vector<vector<int> > adj(n, vector<int>()); for (size_t i = 0; i < m; i++) { int x, y; std::cin >> x >> y; adj[x - 1].push_back(y - 1); adj[y - 1].push_back(x - 1); } std::cout << number_of_components(adj); }
873
382
/* * (C) Copyright 2019 UCAR * * This software is licensed under the terms of the Apache Licence Version 2.0 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. */ #include "ufo/filters/obsfunctions/CLWRetMW.h" #include <algorithm> #include <cmath> #include <iomanip> #include <iostream> #include <set> #include <string> #include <vector> #include "ioda/ObsDataVector.h" #include "oops/util/IntSetParser.h" #include "ufo/filters/Variable.h" #include "ufo/utils/Constants.h" namespace ufo { static ObsFunctionMaker<CLWRetMW> makerCLWRetMW_("CLWRetMW"); CLWRetMW::CLWRetMW(const eckit::LocalConfiguration & conf) : invars_() { // Initialize options options_.deserialize(conf); // Check required parameters // Get variable group types for CLW retrieval from option ASSERT(options_.varGroup.value().size() == 1 || options_.varGroup.value().size() == 2); ASSERT((options_.ch238.value() != boost::none && options_.ch314.value() != boost::none) || (options_.ch37v.value() != boost::none && options_.ch37h.value() != boost::none) || (options_.ch18v.value() != boost::none && options_.ch18h.value() != boost::none && options_.ch36v.value() != boost::none && options_.ch36h.value() != boost::none)); if (options_.ch238.value() != boost::none && options_.ch314.value() != boost::none) { // For AMSUA and ATMS retrievals // Get channels for CLW retrieval from options const std::vector<int> channels = {options_.ch238.value().get(), options_.ch314.value().get()}; ASSERT(options_.ch238.value().get() != 0 && options_.ch314.value().get() != 0 && channels.size() == 2); // Include list of required data from ObsSpace for (size_t igrp = 0; igrp < options_.varGroup.value().size(); ++igrp) { invars_ += Variable("brightness_temperature@" + options_.varGroup.value()[igrp], channels); } invars_ += Variable("brightness_temperature@" + options_.testBias.value(), channels); invars_ += Variable("sensor_zenith_angle@MetaData"); // Include list of required data from GeoVaLs invars_ += Variable("average_surface_temperature_within_field_of_view@GeoVaLs"); invars_ += Variable("water_area_fraction@GeoVaLs"); invars_ += Variable("surface_temperature_where_sea@GeoVaLs"); } else if (options_.ch37v.value() != boost::none && options_.ch37h.value() != boost::none) { // For cloud index like GMI's. // Get channels for CLW retrieval from options const std::vector<int> channels = {options_.ch37v.value().get(), options_.ch37h.value().get()}; ASSERT(options_.ch37v.value().get() != 0 && options_.ch37h.value().get() != 0 && channels.size() == 2); // Include list of required data from ObsSpace for (size_t igrp = 0; igrp < options_.varGroup.value().size(); ++igrp) { invars_ += Variable("brightness_temperature@" + options_.varGroup.value()[igrp], channels); } invars_ += Variable("brightness_temperature@" + options_.testBias.value(), channels); // Include list of required data from ObsDiag invars_ += Variable("brightness_temperature_assuming_clear_sky@ObsDiag" , channels); // Include list of required data from GeoVaLs invars_ += Variable("water_area_fraction@GeoVaLs"); } else if (options_.ch18v.value() != boost::none && options_.ch18h.value() != boost::none && options_.ch36v.value() != boost::none && options_.ch36h.value() != boost::none) { const std::vector<int> channels = {options_.ch18v.value().get(), options_.ch18h.value().get(), options_.ch36v.value().get(), options_.ch36h.value().get()}; ASSERT(options_.ch18v.value().get() != 0 && options_.ch18h.value().get() != 0 && options_.ch36v.value().get() != 0 && options_.ch36h.value().get() != 0 && channels.size() == 4); const std::vector<float> &sys_bias = options_.origbias.value().get(); ASSERT(options_.origbias.value() != boost::none); // Include list of required data from ObsSpace for (size_t igrp = 0; igrp < options_.varGroup.value().size(); ++igrp) { invars_ += Variable("brightness_temperature@" + options_.varGroup.value()[igrp], channels); } invars_ += Variable("brightness_temperature@" + options_.testBias.value(), channels); // Include list of required data from GeoVaLs invars_ += Variable("water_area_fraction@GeoVaLs"); } } // ----------------------------------------------------------------------------- CLWRetMW::~CLWRetMW() {} // ----------------------------------------------------------------------------- void CLWRetMW::compute(const ObsFilterData & in, ioda::ObsDataVector<float> & out) const { // Get required parameters const std::vector<std::string> &vargrp = options_.varGroup.value(); // Get dimension const size_t nlocs = in.nlocs(); const size_t ngrps = vargrp.size(); // Get area fraction of each surface type std::vector<float> water_frac(nlocs); in.get(Variable("water_area_fraction@GeoVaLs"), water_frac); // --------------- amsua or atms -------------------------- if (options_.ch238.value() != boost::none && options_.ch314.value() != boost::none) { const std::vector<int> channels = {options_.ch238.value().get(), options_.ch314.value().get()}; // Get variables from ObsSpace // Get sensor zenith angle std::vector<float> szas(nlocs); in.get(Variable("sensor_zenith_angle@MetaData"), szas); // Get variables from GeoVaLs // Get average surface temperature in FOV std::vector<float> tsavg(nlocs); in.get(Variable("average_surface_temperature_within_field_of_view@GeoVaLs"), tsavg); // Calculate retrieved cloud liquid water std::vector<float> bt238(nlocs), bt314(nlocs); for (size_t igrp = 0; igrp < ngrps; ++igrp) { // Get data based on group type in.get(Variable("brightness_temperature@" + vargrp[igrp], channels)[0], bt238); in.get(Variable("brightness_temperature@" + vargrp[igrp], channels)[1], bt314); // Get bias based on group type if (options_.addBias.value() == vargrp[igrp]) { std::vector<float> bias238(nlocs), bias314(nlocs); if (in.has(Variable("brightness_temperature@" + options_.testBias.value(), channels)[0])) { in.get(Variable("brightness_temperature@" + options_.testBias.value(), channels)[0], bias238); in.get(Variable("brightness_temperature@" + options_.testBias.value(), channels)[1], bias314); } else { bias238.assign(nlocs, 0.0f); bias314.assign(nlocs, 0.0f); } // Add bias correction to the assigned group (only for ObsValue; H(x) already includes bias // correction if (options_.addBias.value() == "ObsValue") { for (size_t iloc = 0; iloc < nlocs; ++iloc) { bt238[iloc] = bt238[iloc] - bias238[iloc]; bt314[iloc] = bt314[iloc] - bias314[iloc]; } } } // Compute the cloud liquid water cloudLiquidWater(szas, tsavg, water_frac, bt238, bt314, out[igrp]); } // -------------------- GMI --------------------------- } else if (options_.ch37v.value() != boost::none && options_.ch37h.value() != boost::none) { const std::vector<int> channels = {options_.ch37v.value().get(), options_.ch37h.value().get()}; // Indices of data at channeles 37v and 37h in the above array "channels" const int jch37v = 0; const int jch37h = 1; std::vector<float> bt_clr_37v(nlocs), bt_clr_37h(nlocs); in.get(Variable("brightness_temperature_assuming_clear_sky@ObsDiag" , channels) [jch37v], bt_clr_37v); in.get(Variable("brightness_temperature_assuming_clear_sky@ObsDiag" , channels) [jch37h], bt_clr_37h); // Calculate retrieved cloud liquid water std::vector<float> bt37v(nlocs), bt37h(nlocs); for (size_t igrp = 0; igrp < ngrps; ++igrp) { // Get data based on group type in.get(Variable("brightness_temperature@" + vargrp[igrp], channels) [jch37v], bt37v); in.get(Variable("brightness_temperature@" + vargrp[igrp], channels) [jch37h], bt37h); // Get bias based on group type if (options_.addBias.value() == vargrp[igrp]) { std::vector<float> bias37v(nlocs), bias37h(nlocs); if (in.has(Variable("brightness_temperature@" + options_.testBias.value(), channels) [jch37v])) { in.get(Variable("brightness_temperature@" + options_.testBias.value(), channels) [jch37v], bias37v); in.get(Variable("brightness_temperature@" + options_.testBias.value(), channels) [jch37h], bias37h); } else { bias37v.assign(nlocs, 0.0f); bias37h.assign(nlocs, 0.0f); } // Add bias correction to the assigned group (only for ObsValue; H(x) already includes bias // correction if (options_.addBias.value() == "ObsValue") { for (size_t iloc = 0; iloc < nlocs; ++iloc) { bt37v[iloc] = bt37v[iloc] - bias37v[iloc]; bt37h[iloc] = bt37h[iloc] - bias37h[iloc]; } } } // Compute cloud index CIret_37v37h_diff(bt_clr_37v, bt_clr_37h, water_frac, bt37v, bt37h, out[igrp]); } // -------------------- amsr2 --------------------------- } else if (options_.ch18v.value() != boost::none && options_.ch18h.value() != boost::none && options_.ch36v.value() != boost::none && options_.ch36h.value() != boost::none) { const std::vector<int> channels = {options_.ch18v.value().get(), options_.ch18h.value().get(), options_.ch36v.value().get(), options_.ch36h.value().get()}; const int jch18v = 0; const int jch18h = 1; const int jch36v = 2; const int jch36h = 3; // systematic bias for channels 1-14. const std::vector<float> &sys_bias = options_.origbias.value().get(); // Calculate retrieved cloud liquid water std::vector<float> bt18v(nlocs), bt18h(nlocs), bt36v(nlocs), bt36h(nlocs); for (size_t igrp = 0; igrp < ngrps; ++igrp) { // Get data based on group type const Variable btVar("brightness_temperature@" + vargrp[igrp], channels); in.get(btVar[jch18v], bt18v); in.get(btVar[jch18h], bt18h); in.get(btVar[jch36v], bt36v); in.get(btVar[jch36h], bt36h); // Get bias based on group type if (options_.addBias.value() == vargrp[igrp]) { std::vector<float> bias18v(nlocs), bias18h(nlocs); std::vector<float> bias36v(nlocs), bias36h(nlocs); if (in.has(Variable("brightness_temperature@" + options_.testBias.value(), channels) [jch36v])) { const Variable testBias("brightness_temperature@" + options_.testBias.value(), channels); in.get(testBias[jch18v], bias18v); in.get(testBias[jch18h], bias18h); in.get(testBias[jch36v], bias36v); in.get(testBias[jch36h], bias36h); } else { bias18v.assign(nlocs, 0.0f); bias18h.assign(nlocs, 0.0f); bias36v.assign(nlocs, 0.0f); bias36h.assign(nlocs, 0.0f); } // Add bias correction to the assigned group (only for ObsValue; H(x) already includes bias // correction if (options_.addBias.value() == "ObsValue") { for (size_t iloc = 0; iloc < nlocs; ++iloc) { bt18v[iloc] = bt18v[iloc] - bias18v[iloc]; bt18h[iloc] = bt18h[iloc] - bias18h[iloc]; bt36v[iloc] = bt36v[iloc] - bias36v[iloc]; bt36h[iloc] = bt36h[iloc] - bias36h[iloc]; } } } // correct systematic bias. for (size_t iloc = 0; iloc < nlocs; ++iloc) { bt18v[iloc] = bt18v[iloc] - sys_bias[6]; bt18h[iloc] = bt18h[iloc] - sys_bias[7]; bt36v[iloc] = bt36v[iloc] - sys_bias[10]; bt36h[iloc] = bt36h[iloc] - sys_bias[11]; } // Compute cloud index clw_retr_amsr2(bt18v, bt18h, bt36v, bt36h, out[igrp]); } } } // ----------------------------------------------------------------------------- void CLWRetMW::cloudLiquidWater(const std::vector<float> & szas, const std::vector<float> & tsavg, const std::vector<float> & water_frac, const std::vector<float> & bt238, const std::vector<float> & bt314, std::vector<float> & out) { /// /// \brief Retrieve cloud liquid water from AMSU-A 23.8 GHz and 31.4 GHz channels. /// /// Reference: Grody et al. (2001) /// Determination of precipitable water and cloud liquid water over oceans from /// the NOAA 15 advanced microwave sounding unit /// const float t0c = Constants::t0c; const float d1 = 0.754, d2 = -2.265; const float c1 = 8.240, c2 = 2.622, c3 = 1.846; for (size_t iloc = 0; iloc < water_frac.size(); ++iloc) { if (water_frac[iloc] >= 0.99) { float cossza = cos(Constants::deg2rad * szas[iloc]); float d0 = c1 - (c2 - c3 * cossza) * cossza; if (tsavg[iloc] > t0c - 1.0 && bt238[iloc] <= 284.0 && bt314[iloc] <= 284.0 && bt238[iloc] > 0.0 && bt314[iloc] > 0.0) { out[iloc] = cossza * (d0 + d1 * std::log(285.0 - bt238[iloc]) + d2 * std::log(285.0 - bt314[iloc])); out[iloc] = std::max(0.f, out[iloc]); } else { out[iloc] = getBadValue(); } } } } // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- void CLWRetMW::CIret_37v37h_diff(const std::vector<float> & bt_clr_37v, const std::vector<float> & bt_clr_37h, const std::vector<float> & water_frac, const std::vector<float> & bt37v, const std::vector<float> & bt37h, std::vector<float> & out) { /// /// \brief Retrieve cloud index from GMI 37V and 37H channels. /// /// GMI cloud index: 1.0 - (Tb_37v - Tb_37h)/(Tb_37v_clr - Tb_37h_clr), in which /// Tb_37v_clr and Tb_37h_clr for calculated Tb at 37 V and 37H GHz from module values /// assuming in clear-sky condition. Tb_37v and Tb_37h are Tb observations at 37 V and 37H GHz. /// for (size_t iloc = 0; iloc < water_frac.size(); ++iloc) { if (water_frac[iloc] >= 0.99) { if (bt37h[iloc] <= bt37v[iloc]) { out[iloc] = 1.0 - (bt37v[iloc] - bt37h[iloc])/(bt_clr_37v[iloc] - bt_clr_37h[iloc]); out[iloc] = std::max(0.f, out[iloc]); } else { out[iloc] = getBadValue(); } } else { out[iloc] = getBadValue(); } } } // ----------------------------------------------------------------------------- /// \brief Retrieve AMSR2_GCOM-W1 cloud liquid water. /// This retrieval function is taken from the subroutine "retrieval_amsr2()" in GSI. void CLWRetMW::clw_retr_amsr2(const std::vector<float> & bt18v, const std::vector<float> & bt18h, const std::vector<float> & bt36v, const std::vector<float> & bt36h, std::vector<float> & out) { float clw; std::vector<float> pred_var_clw(2); // intercepts const float a0_clw = -0.65929; // regression coefficients float regr_coeff_clw[3] = {-0.00013, 1.64692, -1.51916}; for (size_t iloc = 0; iloc < bt18v.size(); ++iloc) { if (bt18v[iloc] <= bt18h[iloc]) { out[iloc] = getBadValue(); } else if (bt36v[iloc] <= bt36h[iloc]) { out[iloc] = getBadValue(); } else { // Calculate predictors pred_var_clw[0] = log(bt18v[iloc] - bt18h[iloc]); pred_var_clw[1] = log(bt36v[iloc] - bt36h[iloc]); clw = a0_clw + bt36h[iloc]*regr_coeff_clw[0]; for (size_t nvar_clw=0; nvar_clw < pred_var_clw.size(); ++nvar_clw) { clw = clw + (pred_var_clw[nvar_clw] * regr_coeff_clw[nvar_clw+1]); } clw = std::max(0.0f, clw); clw = std::min(6.0f, clw); out[iloc] = clw; } } } // ----------------------------------------------------------------------------- const ufo::Variables & CLWRetMW::requiredVariables() const { return invars_; } // ----------------------------------------------------------------------------- } // namespace ufo
16,712
6,206
#pragma once #include "base.hpp" int user1_value_by_visitation(Base& base);
76
29
#include <reversed.hpp> #include <array> #include <string> #include <utility> #include <vector> #include "catch.hpp" #define DECLARE_REVERSE_ITERATOR #include "helpers.hpp" #undef DECLARE_REVERSE_ITERATOR using iter::reversed; using Vec = const std::vector<int>; TEST_CASE("reversed: can reverse a vector", "[reversed]") { Vec ns = {10, 20, 30, 40}; std::vector<int> v; SECTION("Normal call") { auto r = reversed(ns); v.assign(std::begin(r), std::end(r)); } SECTION("Pipe") { auto r = ns | reversed; v.assign(std::begin(r), std::end(r)); } Vec vc = {40, 30, 20, 10}; REQUIRE(v == vc); } #if 0 TEST_CASE("reversed: Works with different begin and end types", "[reversed]") { CharRange cr{'d'}; auto r = reversed(cr); Vec v(r.begin(), r.end()); Vec vc{'c', 'b', 'a'}; REQUIRE(v == vc); } #endif TEST_CASE("reversed: can reverse an array", "[reversed]") { int ns[] = {10, 20, 30, 40}; auto r = reversed(ns); Vec v(std::begin(r), std::end(r)); Vec vc = {40, 30, 20, 10}; REQUIRE(v == vc); } TEST_CASE("reversed: empty when iterable is empty", "[reversed]") { Vec emp{}; auto r = reversed(emp); REQUIRE(std::begin(r) == std::end(r)); } TEST_CASE("reversed: moves rvalues and binds to lvalues", "[reversed]") { itertest::BasicIterable<int> bi{1, 2}; itertest::BasicIterable<int> bi2{1, 2}; reversed(bi); REQUIRE_FALSE(bi.was_moved_from()); reversed(std::move(bi2)); REQUIRE(bi2.was_moved_from()); } TEST_CASE("reversed: doesn't move or copy elements of array", "[reversed]") { constexpr itertest::SolidInt arr[] = {{6}, {7}, {8}}; for (auto&& i : reversed(arr)) { (void)i; } } TEST_CASE("reversed: with iterable doesn't move or copy elems", "[reversed]") { constexpr std::array<itertest::SolidInt, 3> arr{{{6}, {7}, {8}}}; for (auto&& i : reversed(arr)) { (void)i; } } TEST_CASE("reversed: iterator meets requirements", "[reversed]") { Vec v; auto r = reversed(v); REQUIRE(itertest::IsIterator<decltype(std::begin(r))>::value); int a[1]; auto ra = reversed(a); REQUIRE(itertest::IsIterator<decltype(std::begin(ra))>::value); } template <typename T> using ImpT = decltype(reversed(std::declval<T>())); TEST_CASE("reversed: has correct ctor and assign ops", "[reversed]") { REQUIRE(itertest::IsMoveConstructibleOnly<ImpT<std::string&>>::value); REQUIRE(itertest::IsMoveConstructibleOnly<ImpT<std::string>>::value); }
2,437
1,046
/** * Copyright (c) 2012 - 2014 TideSDK contributors * http://www.tidesdk.org * Includes modified sources under the Apache 2 License * Copyright (c) 2008 - 2012 Appcelerator Inc * Refer to LICENSE for details of distribution and use. **/ #include "javascript_module.h" namespace tide { KKJSMethod::KKJSMethod(JSContextRef context, JSObjectRef jsobject, JSObjectRef thisObject) : TiMethod("JavaScript.KKJSMethod"), context(NULL), jsobject(jsobject), thisObject(thisObject) { /* KJS methods run in the global context that they originated from * this seems to prevent nasty crashes from trying to access invalid * contexts later. Global contexts need to be registered by all modules * that use a KJS context. */ JSObjectRef globalObject = JSContextGetGlobalObject(context); JSGlobalContextRef globalContext = JSUtil::GetGlobalContext(globalObject); // This context hasn't been registered. Something has gone pretty // terribly wrong and TideSDK will likely crash soon. Nonetheless, keep // the user up-to-date to keep their hopes up. if (globalContext == NULL) std::cerr << "Could not locate global context for a KJS method." << " One of the modules is misbehaving." << std::endl; this->context = globalContext; JSUtil::ProtectGlobalContext(this->context); JSValueProtect(this->context, jsobject); if (thisObject != NULL) JSValueProtect(this->context, thisObject); this->tiObject = new KKJSObject(this->context, jsobject); } KKJSMethod::~KKJSMethod() { JSValueUnprotect(this->context, this->jsobject); if (this->thisObject != NULL) JSValueUnprotect(this->context, this->thisObject); JSUtil::UnprotectGlobalContext(this->context); } ValueRef KKJSMethod::Get(const char *name) { return tiObject->Get(name); } void KKJSMethod::Set(const char *name, ValueRef value) { return tiObject->Set(name, value); } bool KKJSMethod::Equals(TiObjectRef other) { return this->tiObject->Equals(other); } SharedStringList KKJSMethod::GetPropertyNames() { return tiObject->GetPropertyNames(); } bool KKJSMethod::HasProperty(const char* name) { return tiObject->HasProperty(name); } bool KKJSMethod::SameContextGroup(JSContextRef c) { return tiObject->SameContextGroup(c); } JSObjectRef KKJSMethod::GetJSObject() { return this->jsobject; } ValueRef KKJSMethod::Call(JSObjectRef thisObject, const ValueList& args) { JSValueRef* jsArgs = new JSValueRef[args.size()]; for (int i = 0; i < (int) args.size(); i++) { ValueRef arg = args.at(i); jsArgs[i] = JSUtil::ToJSValue(arg, this->context); } JSValueRef exception = NULL; JSValueRef jsValue = JSObjectCallAsFunction(this->context, thisObject, this->thisObject, args.size(), jsArgs, &exception); delete [] jsArgs; // clean up args if (jsValue == NULL && exception != NULL) //exception thrown { ValueRef exceptionValue = JSUtil::ToTiValue(exception, this->context, NULL); throw ValueException(exceptionValue); } return JSUtil::ToTiValue(jsValue, this->context, NULL); } ValueRef KKJSMethod::Call(const ValueList& args) { return this->Call(this->jsobject, args); } ValueRef KKJSMethod::Call(TiObjectRef thisObject, const ValueList& args) { JSValueRef thisObjectValue = JSUtil::ToJSValue(Value::NewObject(thisObject), this->context); if (!JSValueIsObject(this->context, thisObjectValue)) { SharedString ss(thisObject->DisplayString()); throw ValueException::FromFormat("Could not convert %s to JSObjectRef for KKJSMethod::Call", ss->c_str()); } JSObjectRef jsThisObject = JSValueToObject(this->context, thisObjectValue, NULL); if (!jsThisObject) { SharedString ss(thisObject->DisplayString()); throw ValueException::FromFormat("Could not convert %s to JSObjectRef for KKJSMethod::Call", ss->c_str()); } return this->Call(jsThisObject, args); } }
4,438
1,300
/* Copyright (c) 2019 PaddlePaddle 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. */ #pragma once #include <vector> #include "lite/fpga/KD/alignment.h" namespace paddle { namespace zynqmp { enum LayoutType { N, NC, NCHW, NHWC, NHW, }; class Layout { public: virtual int numIndex() = 0; virtual int channelIndex() { return -1; } virtual int heightIndex() { return -1; } virtual int widthIndex() { return -1; } virtual int alignedElementCount(const std::vector<int>& dims) = 0; virtual int elementCount(const std::vector<int>& dims) = 0; }; struct NCHW : Layout { int numIndex() { return 0; } int channelIndex() { return 1; } int heightIndex() { return 2; } int widthIndex() { return 3; } int alignedElementCount(const std::vector<int>& dims) { return dims[0] * dims[2] * align_image(dims[1] * dims[3]); } virtual int elementCount(const std::vector<int>& dims) { return dims[0] * dims[1] * dims[2] * dims[3]; } }; struct NHWC : Layout { int numIndex() { return 0; } int heightIndex() { return 1; } int widthIndex() { return 2; } int channelIndex() { return 3; } int alignedElementCount(const std::vector<int>& dims) { return dims[0] * dims[1] * align_image(dims[2] * dims[3]); } virtual int elementCount(const std::vector<int>& dims) { return dims[0] * dims[1] * dims[2] * dims[3]; } }; struct NC : Layout { int numIndex() { return 0; } int channelIndex() { return 1; } int alignedElementCount(const std::vector<int>& dims) { return dims[0] * dims[1]; } virtual int elementCount(const std::vector<int>& dims) { return dims[0] * dims[1]; } }; struct N : Layout { int numIndex() { return 0; } int alignedElementCount(const std::vector<int>& dims) { return dims[0]; } virtual int elementCount(const std::vector<int>& dims) { return dims[0]; } }; struct NHW : Layout { int numIndex() { return 0; } int heightIndex() { return 1; } int widthIndex() { return 2; } int alignedElementCount(const std::vector<int>& dims) { // TODO(chonwhite) align it; return dims[0] * dims[1] * dims[2]; } virtual int elementCount(const std::vector<int>& dims) { return dims[0] * dims[1] * dims[2]; } }; } // namespace zynqmp } // namespace paddle
2,765
1,002
/* Problem : Vertical Order Traversal of a Binary Tree */ // Approach make variable x and y and attach them with every node x for horizontal distance and y for vertical distance // Code map<int,set<pair<int,int>>> ans; void pre( TreeNode *root, int horizontal_Level, int vertical_Level ){ if(!root) return ; ans[horizontal_Level].insert({vertical_Level,root->val}); pre(root->left,horizontal_Level-1,vertical_Level+1); pre(root->right,horizontal_Level+1,vertical_Level+1); } public: vector<vector<int>> verticalTraversal(TreeNode* root) { pre(root,0 , 0 ); vector<vector<int>> v; for( auto e : ans ){ vector<int> c; for( auto x : e.second ) c.push_back(x.second); v.push_back(c); } return v; }
854
259
#include <iostream> #include <stdio.h> #include <string> #include <fstream> #include <vector> #include <unordered_map> #include <stack> #include <deque> #include <algorithm> using namespace std; int main() { cout << "Hello World!" << endl; return 0; }
268
97
// // Created by Vitali Kurlovich on 4/13/16. // #ifndef RMVECTORMATH_QUATERNION_DOUBLE_TYPE_HPP #define RMVECTORMATH_QUATERNION_DOUBLE_TYPE_HPP #include "../quaternion/TQuaternion.hpp" namespace rmmath { typedef quaternion::TQuaternion<double> dquat; } #endif //RMVECTORMATH_QUATERNION_DOUBLE_TYPE_HPP
312
147
// 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/importer/toolbar_importer_utils.h" #include <string> #include <vector> #include "base/bind.h" #include "base/strings/string_split.h" #include "chrome/browser/profiles/profile.h" #include "content/public/browser/browser_thread.h" #include "googleurl/src/gurl.h" #include "net/cookies/cookie_store.h" #include "net/url_request/url_request_context.h" #include "net/url_request/url_request_context_getter.h" using content::BrowserThread; namespace { const char kGoogleDomainUrl[] = "http://.google.com/"; const char kGoogleDomainSecureCookieId[] = "SID="; const char kSplitStringToken = ';'; } namespace toolbar_importer_utils { void OnGetCookies(const base::Callback<void(bool)>& callback, const std::string& cookies) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); std::vector<std::string> cookie_list; base::SplitString(cookies, kSplitStringToken, &cookie_list); for (std::vector<std::string>::iterator current = cookie_list.begin(); current != cookie_list.end(); ++current) { size_t position = (*current).find(kGoogleDomainSecureCookieId); if (position == 0) { callback.Run(true); return; } } callback.Run(false); } void OnFetchComplete(const base::Callback<void(bool)>& callback, const std::string& cookies) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&OnGetCookies, callback, cookies)); } void FetchCookiesOnIOThread( const base::Callback<void(bool)>& callback, net::URLRequestContextGetter* context_getter) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); net::CookieStore* store = context_getter-> GetURLRequestContext()->cookie_store(); GURL url(kGoogleDomainUrl); net::CookieOptions options; options.set_include_httponly(); // The SID cookie might be httponly. store->GetCookiesWithOptionsAsync( url, options, base::Bind(&toolbar_importer_utils::OnFetchComplete, callback)); } void IsGoogleGAIACookieInstalled(const base::Callback<void(bool)>& callback, Profile* profile) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (!callback.is_null()) { BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(&FetchCookiesOnIOThread, callback, base::Unretained(profile->GetRequestContext()))); } } } // namespace toolbar_importer_utils
2,679
840
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ int main() { auto x = new int[8]; auto y = new int[8]; y[0] = 42; auto x_ptr = x + 8; // one past the end if (x_ptr == &y[0]) // valid *x_ptr = 23; // UB return y[0]; }
382
152