blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
115 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
192fe3a3b3aaccda690b4f15bb5f9347f070038d
46367579a54a09dd220dd9a678b1452f06897f11
/tags/hdf5-1_8_0-beta3/c++/src/H5DxferProp.cpp
0f7faa24a3e04b222f2534558efd30b879449453
[ "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-llnl" ]
permissive
TPLink32/hdf5
33ff24c9b6133f0f51cb6cc2b722fba7bb1777dd
0d6987c15284bd9f34c7e44452a152833d42a738
refs/heads/master
2021-05-31T01:15:39.463663
2016-04-14T23:02:09
2016-04-14T23:02:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
18,394
cpp
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Copyright by The HDF Group. * * Copyright by the Board of Trustees of the University of Illinois. * * All rights reserved. * * * * This file is part of HDF5. The full HDF5 copyright notice, including * * terms governing use, modification, and redistribution, is contained in * * the files COPYING and Copyright.html. COPYING can be found at the root * * of the source code distribution tree; Copyright.html can be found at the * * root level of an installed copy of the electronic HDF5 document set and * * is linked from the top-level documents page. It can also be found at * * http://hdfgroup.org/HDF5/doc/Copyright.html. If you do not have * * access to either file, you may request a copy from help@hdfgroup.org. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #include <string> #include "H5Include.h" #include "H5Exception.h" #include "H5IdComponent.h" #include "H5PropList.h" #include "H5DxferProp.h" #ifndef H5_NO_NAMESPACE namespace H5 { #endif //-------------------------------------------------------------------------- ///\brief Constant for default dataset memory and transfer property list. //-------------------------------------------------------------------------- const DSetMemXferPropList DSetMemXferPropList::DEFAULT; //-------------------------------------------------------------------------- // Function DSetMemXferPropList default constructor ///\brief Default constructor: creates a stub dataset memory and /// transfer property list object. // Programmer: Binh-Minh Ribler - 2000 //-------------------------------------------------------------------------- DSetMemXferPropList::DSetMemXferPropList() : PropList(H5P_DATASET_XFER) {} //-------------------------------------------------------------------------- // Function DSetMemXferPropList copy constructor ///\brief Copy constructor: makes a copy of the original /// DSetMemXferPropList object ///\param original - IN: Original dataset memory and transfer property /// list object to copy // Programmer: Binh-Minh Ribler - 2000 //-------------------------------------------------------------------------- DSetMemXferPropList::DSetMemXferPropList(const DSetMemXferPropList& original ) : PropList( original ) {} //-------------------------------------------------------------------------- // Function DSetMemXferPropList overloaded constructor ///\brief Creates a DSetMemXferPropList object using the id of an /// existing DSetMemXferPropList. ///\param plist_id - IN: Id of an existing dataset memory and transfer /// property list // Programmer: Binh-Minh Ribler - 2000 //-------------------------------------------------------------------------- DSetMemXferPropList::DSetMemXferPropList(const hid_t plist_id) : PropList(plist_id) {} //-------------------------------------------------------------------------- // Function: DSetMemXferPropList::setBuffer ///\brief Sets type conversion and background buffers. ///\param size - IN: Size, in bytes, of the type conversion and background buffers ///\param tconv - IN: Pointer to application-allocated type conversion buffer ///\param bkg - IN: Pointer to application-allocated background buffer ///\exception H5::PropListIException // Programmer: Binh-Minh Ribler - 2000 //-------------------------------------------------------------------------- void DSetMemXferPropList::setBuffer( size_t size, void* tconv, void* bkg ) const { herr_t ret_value = H5Pset_buffer( id, size, tconv, bkg ); if( ret_value < 0 ) { throw PropListIException("DSetMemXferPropList::setBuffer", "H5Pset_buffer failed"); } } //-------------------------------------------------------------------------- // Function: DSetMemXferPropList::getBuffer ///\brief Reads buffer settings. ///\param tconv - IN: Pointer to application-allocated type conversion buffer ///\param bkg - IN: Pointer to application-allocated background buffer ///\return Buffer size, in bytes ///\exception H5::PropListIException // Programmer: Binh-Minh Ribler - 2000 //-------------------------------------------------------------------------- size_t DSetMemXferPropList::getBuffer( void** tconv, void** bkg ) const { size_t buffer_size = H5Pget_buffer( id, tconv, bkg ); if( buffer_size == 0 ) { throw PropListIException("DSetMemXferPropList::getBuffer", "H5Pget_buffer returned 0 for buffer size - failure"); } return( buffer_size ); } //-------------------------------------------------------------------------- // Function: DSetMemXferPropList::setPreserve ///\brief Sets the dataset transfer property list status to true or false. ///\param status - IN: Status to set, true or false ///\exception H5::PropListIException // Programmer: Binh-Minh Ribler - 2000 //-------------------------------------------------------------------------- void DSetMemXferPropList::setPreserve( bool status ) const { herr_t ret_value = H5Pset_preserve( id, (hbool_t) status ); if( ret_value < 0 ) { throw PropListIException("DSetMemXferPropList::setPreserve", "H5Pset_preserve failed"); } } //-------------------------------------------------------------------------- // Function: DSetMemXferPropList::getPreserve ///\brief Checks status of the dataset transfer property list. ///\return Status of the dataset transfer property list ///\exception H5::PropListIException // Programmer: Binh-Minh Ribler - 2000 //-------------------------------------------------------------------------- bool DSetMemXferPropList::getPreserve() const { int ret_value = H5Pget_preserve( id ); if( ret_value > 0 ) return true; else if( ret_value == 0 ) return false; else { throw PropListIException("DSetMemXferPropList::getPreserve", "H5Pget_preserve returned negative value for status"); } } //-------------------------------------------------------------------------- // Function: DSetMemXferPropList::setBtreeRatios ///\brief Sets B-tree split ratios for a dataset transfer property list. ///\param left - IN: B-tree split ratio for left-most nodes ///\param middle - IN: B-tree split ratio for right-most nodes and lone nodes ///\param right - IN: B-tree split ratio for all other nodes ///\exception H5::PropListIException // Programmer: Binh-Minh Ribler - 2000 //-------------------------------------------------------------------------- void DSetMemXferPropList::setBtreeRatios( double left, double middle, double right ) const { herr_t ret_value = H5Pset_btree_ratios( id, left, middle, right ); if( ret_value < 0 ) { throw PropListIException("DSetMemXferPropList::setBtreeRatios", "H5Pset_btree_ratios failed"); } } //-------------------------------------------------------------------------- // Function: DSetMemXferPropList::getBtreeRatios ///\brief Gets B-tree split ratios for a dataset transfer property list. ///\param left - OUT: B-tree split ratio for left-most nodes ///\param middle - OUT: B-tree split ratio for right-most nodes and lone nodes ///\param right - OUT: B-tree split ratio for all other nodes ///\exception H5::PropListIException // Programmer: Binh-Minh Ribler - 2000 //-------------------------------------------------------------------------- void DSetMemXferPropList::getBtreeRatios( double& left, double& middle, double& right ) const { herr_t ret_value = H5Pget_btree_ratios( id, &left, &middle, &right ); if( ret_value < 0 ) { throw PropListIException("DSetMemXferPropList::getBtreeRatios", "H5Pget_btree_ratios failed"); } } //-------------------------------------------------------------------------- // Function: DSetMemXferPropList::setTypeConvCB ///\brief Sets an exception handling callback for datatype conversion /// for a dataset transfer property list. ///\param op - IN: User's function ///\param user_data - IN: User's data ///\exception H5::PropListIException // Programmer: Binh-Minh Ribler - April, 2004 //-------------------------------------------------------------------------- void DSetMemXferPropList::setTypeConvCB( H5T_conv_except_func_t op, void *user_data) const { herr_t ret_value = H5Pset_type_conv_cb( id, op, user_data); if( ret_value < 0 ) { throw PropListIException("DSetMemXferPropList::setTypeConvCB", "H5Pset_type_conv_cb failed"); } } //-------------------------------------------------------------------------- // Function: DSetMemXferPropList::getTypeConvCB ///\brief Gets the exception handling callback function and data. ///\param op - IN: Retrieved user function ///\param user_data - IN: Retrieved user data ///\exception H5::PropListIException // Programmer: Binh-Minh Ribler - April, 2004 //-------------------------------------------------------------------------- void DSetMemXferPropList::getTypeConvCB( H5T_conv_except_func_t *op, void **user_data) const { herr_t ret_value = H5Pget_type_conv_cb( id, op, user_data); if( ret_value < 0 ) { throw PropListIException("DSetMemXferPropList::getTypeConvCB", "H5Pget_type_conv_cb failed"); } } //-------------------------------------------------------------------------- // Function: DSetMemXferPropList::setVlenMemManager ///\brief Sets the memory manager for variable-length datatype allocation. ///\param alloc_func - IN: User's allocate routine ///\param alloc_info - IN: User's allocation parameters ///\param free_func - IN: User's free routine ///\param free_info - IN: User's free parameters ///\exception H5::PropListIException // Programmer: Binh-Minh Ribler - 2000 //-------------------------------------------------------------------------- void DSetMemXferPropList::setVlenMemManager( H5MM_allocate_t alloc_func, void* alloc_info, H5MM_free_t free_func, void* free_info ) const { herr_t ret_value = H5Pset_vlen_mem_manager( id, alloc_func, alloc_info, free_func, free_info ); if( ret_value < 0 ) { throw PropListIException("DSetMemXferPropList::setVlenMemManager", "H5Pset_vlen_mem_manager failed"); } } //-------------------------------------------------------------------------- // Function: DSetMemXferPropList::setVlenMemManager ///\brief Sets the memory manager for variable-length datatype /// allocation - system \c malloc and \c free will be used. /// ///\exception H5::PropListIException // Programmer: Binh-Minh Ribler - 2000 //-------------------------------------------------------------------------- void DSetMemXferPropList::setVlenMemManager() const { setVlenMemManager( NULL, NULL, NULL, NULL ); } //-------------------------------------------------------------------------- // Function: DSetMemXferPropList::getVlenMemManager ///\brief Gets the memory manager for variable-length datatype allocation ///\param alloc_func - OUT: User's allocate routine ///\param alloc_info - OUT: User's allocation parameters ///\param free_func - OUT: User's free routine ///\param free_info - OUT: User's free parameters ///\exception H5::PropListIException // Programmer: Binh-Minh Ribler - 2000 //-------------------------------------------------------------------------- void DSetMemXferPropList::getVlenMemManager( H5MM_allocate_t& alloc_func, void** alloc_info, H5MM_free_t& free_func, void** free_info ) const { herr_t ret_value = H5Pget_vlen_mem_manager( id, &alloc_func, alloc_info, &free_func, free_info ); if( ret_value < 0 ) { throw PropListIException("DSetMemXferPropList::getVlenMemManager", "H5Pget_vlen_mem_manager failed"); } } //-------------------------------------------------------------------------- // Function: DSetMemXferPropList::setMulti ///\brief Sets the data transfer property list for the multi-file driver. ///\param memb_dxpl - OUT: Array of data access property lists ///\exception H5::PropListIException ///\par Description /// This function can only be used after the member map has /// been set with FileAccPropList::setMulti (not done - BMR.) // Programmer: Binh-Minh Ribler - April, 2004 //-------------------------------------------------------------------------- void DSetMemXferPropList::setMulti(const hid_t *memb_dxpl) { herr_t ret_value = H5Pset_dxpl_multi(id, memb_dxpl); if (ret_value < 0) { throw PropListIException("DSetMemXferPropList::setMulti", "H5Pset_dxpl_multi failed"); } } //-------------------------------------------------------------------------- // Function: DSetMemXferPropList::getMulti ///\brief Returns multi-file data transfer property list information. ///\param memb_dxpl - OUT: Array of data access property lists ///\exception H5::PropListIException // Programmer: Binh-Minh Ribler - April, 2004 //-------------------------------------------------------------------------- void DSetMemXferPropList::getMulti(hid_t *memb_dxpl) { herr_t ret_value = H5Pget_dxpl_multi(id, memb_dxpl); if (ret_value < 0) { throw PropListIException("DSetMemXferPropList::getMulti", "H5Pget_dxpl_multi failed"); } } //-------------------------------------------------------------------------- // Function: DSetMemXferPropList::setSmallDataBlockSize ///\brief Sets the size of a contiguous block reserved for small data. ///\param size - IN: Maximum size, in bytes, of the small data block. ///\exception H5::PropListIException ///\par Description /// For detail, please refer to the C layer Reference Manual at: /// http://hdf.ncsa.uiuc.edu/HDF5/doc/RM_H5P.html#Property-SetSmallData // Programmer: Binh-Minh Ribler - April, 2004 //-------------------------------------------------------------------------- void DSetMemXferPropList::setSmallDataBlockSize(hsize_t size) { herr_t ret_value = H5Pset_small_data_block_size(id, size); if (ret_value < 0) { throw PropListIException("DSetMemXferPropList::setSmallDataBlockSize", "H5Pset_small_data_block_size failed"); } } //-------------------------------------------------------------------------- // Function: DSetMemXferPropList::getSmallDataBlockSize ///\brief Returns the current small data block size setting. ///\return Size of the small data block, in bytes ///\exception H5::PropListIException // Programmer: Binh-Minh Ribler - April, 2004 //-------------------------------------------------------------------------- hsize_t DSetMemXferPropList::getSmallDataBlockSize() { hsize_t size; herr_t ret_value = H5Pget_small_data_block_size(id, &size); if (ret_value < 0) { throw PropListIException("DSetMemXferPropList::getSmallDataBlockSize", "H5Pget_small_data_block_size failed"); } return(size); } //-------------------------------------------------------------------------- // Function: DSetMemXferPropList::setHyperVectorSize ///\brief Sets number of I/O vectors to be read/written in hyperslab I/O. /// ///\exception H5::PropListIException ///\par Description /// For information, please refer to the C layer Reference /// Manual at: /// http://hdf.ncsa.uiuc.edu/HDF5/doc/RM_H5P.html#Property-SetHyperVectorSize // Programmer: Binh-Minh Ribler - April, 2004 //-------------------------------------------------------------------------- void DSetMemXferPropList::setHyperVectorSize(size_t vector_size) { herr_t ret_value = H5Pset_hyper_vector_size(id, vector_size); if (ret_value < 0) { throw PropListIException("DSetMemXferPropList::setHyperVectorSize", "H5Pset_hyper_vector_size failed"); } } //-------------------------------------------------------------------------- // Function: DSetMemXferPropList::getHyperVectorSize ///\brief Returns the number of I/O vectors to be read/written in /// hyperslab I/O. ///\return Number of I/O vectors ///\exception H5::PropListIException // Programmer: Binh-Minh Ribler - April, 2004 //-------------------------------------------------------------------------- size_t DSetMemXferPropList::getHyperVectorSize() { size_t vector_size; herr_t ret_value = H5Pget_hyper_vector_size(id, &vector_size); if (ret_value < 0) { throw PropListIException("DSetMemXferPropList::getHyperVectorSize", "H5Pget_hyper_vector_size failed"); } return(vector_size); } //-------------------------------------------------------------------------- // Function: DSetMemXferPropList::setEDCCheck ///\brief Enables or disables error-detecting for a dataset reading /// process. ///\param check - IN: Specifies whether error detection is enabled or /// disabled ///\exception H5::PropListIException ///\par Description /// The error detection algorithm used is the algorithm previously /// specified in the corresponding dataset creation property /// list. This function does not affect the use of error /// detection in the writing process. ///\par /// Valid values are as follows: /// \li \c H5Z_ENABLE_EDC (default) /// \li \c H5Z_DISABLE_EDC // Programmer: Binh-Minh Ribler - April, 2004 //-------------------------------------------------------------------------- void DSetMemXferPropList::setEDCCheck(H5Z_EDC_t check) { herr_t ret_value = H5Pset_edc_check(id, check); if (ret_value < 0) { throw PropListIException("DSetMemXferPropList::setEDCCheck", "H5Pset_edc_check failed"); } } //-------------------------------------------------------------------------- // Function: DSetMemXferPropList::getEDCCheck ///\brief Determines whether error-detection is enabled for dataset reads. ///\return \c H5Z_ENABLE_EDC or \c H5Z_DISABLE_EDC ///\exception H5::PropListIException // Programmer: Binh-Minh Ribler - April, 2004 //-------------------------------------------------------------------------- H5Z_EDC_t DSetMemXferPropList::getEDCCheck() { H5Z_EDC_t check = H5Pget_edc_check(id); if (check < 0) { throw PropListIException("DSetMemXferPropList::getEDCCheck", "H5Pget_edc_check failed"); } return(check); } //-------------------------------------------------------------------------- // Function: DSetMemXferPropList destructor ///\brief Noop destructor. // Programmer Binh-Minh Ribler - 2000 //-------------------------------------------------------------------------- DSetMemXferPropList::~DSetMemXferPropList() {} #ifndef H5_NO_NAMESPACE } // end namespace #endif
[ "epourmal@dab4d1a6-ed17-0410-a064-d1ae371a2980" ]
epourmal@dab4d1a6-ed17-0410-a064-d1ae371a2980
166eea20423a4a8734180f2ef95de1176a8db765
e9faaa79ecc4234d4a874d0bc39eebf3014ea204
/check_energy_CPU.cpp
5819ca67984e063ebf3d597433c38e404da878ee
[ "Apache-2.0" ]
permissive
wdednam/spilady
7325f3ca7353d353868db500b9eccae020a3c80f
b19c5b92fb7631071ac4b1a3ef60c25b79763331
refs/heads/master
2022-03-31T20:29:10.750543
2018-07-27T14:58:50
2018-07-27T14:58:50
238,537,039
2
0
Apache-2.0
2020-02-05T20:00:33
2020-02-05T20:00:32
null
UTF-8
C++
false
false
4,708
cpp
/******************************************************************************** * * Copyright (C) 2015 Culham Centre for Fusion Energy, * United Kingdom Atomic Energy Authority, Oxfordshire OX14 3DB, UK * * 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. * ******************************************************************************** * * Program: SPILADY - A Spin-Lattice Dynamics Simulation Program * Version: 1.0 * Date: Aug 2015 * Author: Pui-Wai (Leo) MA * Contact: info@spilady.ccfe.ac.uk * Address: Culham Centre for Fusion Energy, OX14 3DB, United Kingdom * ********************************************************************************/ #ifdef CPU #include "spilady.h" void check_energy_CPU(int current_step){ #if defined MD || defined SLDH || defined SLDHL || defined SLDNC double ave_pe = 0e0; double ave_ke = 0e0; #pragma omp parallel for reduction(+:ave_pe,ave_ke) for (int i = 0; i < natom; ++i){ struct atom_struct *atom_ptr; atom_ptr = first_atom_ptr + i; ave_pe += atom_ptr->pe; ave_ke += atom_ptr->ke; } ave_pe /= natom; ave_ke /= natom; #endif #if defined SDH || defined SDHL || defined SLDH || defined SLDHL double ave_me = 0e0; double ave_me0 = 0e0; #pragma omp parallel for reduction(+:ave_me,ave_me0) for (int i = 0; i < natom; ++i){ struct atom_struct *atom_ptr; atom_ptr = first_atom_ptr + i; ave_me += atom_ptr->me; ave_me0 += atom_ptr->me0; } ave_me /= natom; ave_me0 /= natom; #endif #ifdef eltemp double ave_Ee = 0e0; #pragma omp parallel for reduction(+:ave_Ee) for (int i = 0; i < ncells; ++i){ struct cell_struct *cell_ptr; cell_ptr = first_cell_ptr + i; cell_ptr->Ee = Te_to_Ee(cell_ptr->Te); ave_Ee += (double(natom)/double(ncells))*cell_ptr->Ee; } ave_Ee /= natom; #ifdef renormalizeEnergy double numerical_error_ave_energy = 0e0; if (current_step == -1){ initial_ave_energy = 0e0; #if defined MD || defined SLDH || defined SLDHL || defined SLDNC initial_ave_energy += ave_pe; initial_ave_energy += ave_ke; #endif #if defined SDH || defined SDHL || defined SLDH || defined SLDHL initial_ave_energy += ave_me; initial_ave_energy += ave_me0; #endif initial_ave_energy += ave_Ee; } else { double current_ave_energy = 0e0; #if defined MD || defined SLDH || defined SLDHL || defined SLDNC current_ave_energy += ave_pe; current_ave_energy += ave_ke; #endif #if defined SDH || defined SDHL || defined SLDH || defined SLDHL current_ave_energy += ave_me; current_ave_energy += ave_me0; #endif current_ave_energy += ave_Ee; numerical_error_ave_energy = current_ave_energy - initial_ave_energy; } #pragma omp parallel for for (int i = 0; i < ncells; ++i){ struct cell_struct *cell_ptr; cell_ptr = first_cell_ptr + i; cell_ptr->Ee -= numerical_error_ave_energy; cell_ptr->Te = Ee_to_Te(cell_ptr->Ee); } #endif #endif /*eltemp*/ char out_enr_front[] = "enr-"; char out_enr[256]; strcpy(out_enr,out_enr_front); strcat(out_enr,out_body); strcat(out_enr,".dat"); ofstream out_file(out_enr,ios::app); out_file << setiosflags(ios::scientific) << setprecision(15); out_file << current_step //1 << " " << total_time //2 #if defined MD || defined SLDH || defined SLDHL || defined SLDNC << " " << ave_pe //3 << " " << ave_ke //4 #endif #if defined SDH || defined SDHL || defined SLDH || defined SLDHL << " " << ave_me //5 << " " << ave_me0 //6 #endif #ifdef eltemp << " " << ave_Ee //7 #endif << '\n'; out_file.close(); } void check_energy(int current_step){ check_energy_CPU(current_step); } #endif
[ "leo_ma55@hotmail.com" ]
leo_ma55@hotmail.com
a169d7bf87668d7e535f9401a0481f1885dd8b3f
1942a0d16bd48962e72aa21fad8d034fa9521a6c
/aws-cpp-sdk-lightsail/include/aws/lightsail/model/GetActiveNamesRequest.h
88bbcebd1c5837c7c9d0beba3bd0e89905d4d116
[ "Apache-2.0", "JSON", "MIT" ]
permissive
yecol/aws-sdk-cpp
1aff09a21cfe618e272c2c06d358cfa0fb07cecf
0b1ea31e593d23b5db49ee39d0a11e5b98ab991e
refs/heads/master
2021-01-20T02:53:53.557861
2018-02-11T11:14:58
2018-02-11T11:14:58
83,822,910
0
1
null
2017-03-03T17:17:00
2017-03-03T17:17:00
null
UTF-8
C++
false
false
2,633
h
/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #pragma once #include <aws/lightsail/Lightsail_EXPORTS.h> #include <aws/lightsail/LightsailRequest.h> #include <aws/core/utils/memory/stl/AWSString.h> namespace Aws { namespace Lightsail { namespace Model { /** */ class AWS_LIGHTSAIL_API GetActiveNamesRequest : public LightsailRequest { public: GetActiveNamesRequest(); Aws::String SerializePayload() const override; Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override; /** * <p>A token used for paginating results from your get active names request.</p> */ inline const Aws::String& GetPageToken() const{ return m_pageToken; } /** * <p>A token used for paginating results from your get active names request.</p> */ inline void SetPageToken(const Aws::String& value) { m_pageTokenHasBeenSet = true; m_pageToken = value; } /** * <p>A token used for paginating results from your get active names request.</p> */ inline void SetPageToken(Aws::String&& value) { m_pageTokenHasBeenSet = true; m_pageToken = value; } /** * <p>A token used for paginating results from your get active names request.</p> */ inline void SetPageToken(const char* value) { m_pageTokenHasBeenSet = true; m_pageToken.assign(value); } /** * <p>A token used for paginating results from your get active names request.</p> */ inline GetActiveNamesRequest& WithPageToken(const Aws::String& value) { SetPageToken(value); return *this;} /** * <p>A token used for paginating results from your get active names request.</p> */ inline GetActiveNamesRequest& WithPageToken(Aws::String&& value) { SetPageToken(value); return *this;} /** * <p>A token used for paginating results from your get active names request.</p> */ inline GetActiveNamesRequest& WithPageToken(const char* value) { SetPageToken(value); return *this;} private: Aws::String m_pageToken; bool m_pageTokenHasBeenSet; }; } // namespace Model } // namespace Lightsail } // namespace Aws
[ "henso@amazon.com" ]
henso@amazon.com
600deb17cd117c74bfd20c1f873d93336fd0cd68
6968d632ba84a48f27c682691b06ef07e1c72308
/AirLib/include/physics/PhysicsEngineBase.hpp
17a6f9d41828c72ee0cd0fd6e852e5940f56b0ec
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
Jinxinshao/AirSimMulti
e148cdc1dfb9542b9636c94f601ec02d9561f7a8
cfc1fc7eb2f7b6e67c7cb59047e9b3273da4691b
refs/heads/master
2020-09-03T16:54:02.557013
2017-09-06T01:30:45
2017-09-06T01:30:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,945
hpp
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #ifndef airsim_core_PhysicsEngineBase_hpp #define airsim_core_PhysicsEngineBase_hpp #include "common/UpdatableContainer.hpp" #include "common/Common.hpp" #include "PhysicsBody.hpp" namespace msr { namespace airlib { class PhysicsEngineBase : public UpdatableObject { public: virtual void reset() override { UpdatableObject::reset(); } virtual void update() override { UpdatableObject::update(); } virtual void reportState(StateReporter& reporter) override { //default nothing to report for physics engine } //TODO: reduce copy-past from UpdatableContainer which has same code /********************** Container interface **********************/ typedef PhysicsBody* TUpdatableObjectPtr; typedef vector<TUpdatableObjectPtr> MembersContainer; typedef typename MembersContainer::iterator iterator; typedef typename MembersContainer::const_iterator const_iterator; typedef typename MembersContainer::value_type value_type; iterator begin() { return members_.begin(); } iterator end() { return members_.end(); } const_iterator begin() const { return members_.begin(); } const_iterator end() const { return members_.end(); } uint size() const { return static_cast<uint>(members_.size()); } const TUpdatableObjectPtr &at(uint index) const { members_.at(index); } TUpdatableObjectPtr &at(uint index) { return members_.at(index); } //allow to override membership modifications virtual void clear() { members_.clear(); } virtual void insert(TUpdatableObjectPtr member) { members_.push_back(member); } virtual void erase_remove(TUpdatableObjectPtr obj) { members_.erase(std::remove(members_.begin(), members_.end(), obj), members_.end()); } private: MembersContainer members_; }; }} //namespace #endif
[ "saihemachandra.v@gmail.com" ]
saihemachandra.v@gmail.com
d6fb7c04d6888141290a5c3b3b525b142eac8255
262368055ac657f0bf12a6cbe48afdc648f4070f
/tests/unit_tests/parse_amount.cpp
64381875687946465c023d87dfda71f0c56af7b1
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
sohanlaxmicoin/chavezcoin-monero-v3
e614d2cbc2dc134feea26b1cefc95a48b65685f3
9b1d77a5c62644ff909135e1414e9cd461c8ca06
refs/heads/master
2021-01-24T07:21:58.535776
2017-07-25T03:10:10
2017-07-25T03:10:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,035
cpp
// Copyright (c) 2014-2017, The Chavezcoin Project // // 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. // // 3. 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. // // Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers #include "gtest/gtest.h" #include "cryptonote_basic/cryptonote_format_utils.h" using namespace cryptonote; namespace { void do_pos_test(uint64_t expected, const std::string& str) { uint64_t val; std::string number_str = str; std::replace(number_str.begin(), number_str.end(), '_', '.'); number_str.erase(std::remove(number_str.begin(), number_str.end(), '~'), number_str.end()); ASSERT_TRUE(parse_amount(val, number_str)); ASSERT_EQ(expected, val); } void do_neg_test(const std::string& str) { uint64_t val; std::string number_str = str; std::replace(number_str.begin(), number_str.end(), '_', '.'); number_str.erase(std::remove(number_str.begin(), number_str.end(), '~'), number_str.end()); ASSERT_FALSE(parse_amount(val, number_str)); } } #define TEST_pos(expected, str) \ TEST(parse_amount, handles_pos_ ## str) \ { \ do_pos_test(UINT64_C(expected), #str); \ } #define TEST_neg(str) \ TEST(parse_amount, handles_neg_ ## str) \ { \ do_neg_test(#str); \ } #define TEST_neg_n(str, name) \ TEST(parse_amount, handles_neg_ ## name) \ { \ do_neg_test(#str); \ } TEST_pos(0, 0); TEST_pos(0, 00); TEST_pos(0, 00000000); TEST_pos(0, 000000000); TEST_pos(0, 00000000000000000000000000000000); TEST_pos(0, _0); TEST_pos(0, _00); TEST_pos(0, _00000000); TEST_pos(0, _000000000); TEST_pos(0, _00000000000000000000000000000000); TEST_pos(0, 00000000_); TEST_pos(0, 000000000_); TEST_pos(0, 00000000000000000000000000000000_); TEST_pos(0, 0_); TEST_pos(0, 0_0); TEST_pos(0, 0_00); TEST_pos(0, 0_00000000); TEST_pos(0, 0_000000000); TEST_pos(0, 0_00000000000000000000000000000000); TEST_pos(0, 00_); TEST_pos(0, 00_0); TEST_pos(0, 00_00); TEST_pos(0, 00_00000000); TEST_pos(0, 00_000000000); TEST_pos(0, 00_00000000000000000000000000000000); TEST_pos(1, 0_000000000001); TEST_pos(1, 0_0000000000010); TEST_pos(1, 0_0000000000010000000000000000000000000); TEST_pos(9, 0_000000000009); TEST_pos(9, 0_0000000000090); TEST_pos(9, 0_0000000000090000000000000000000000000); TEST_pos(1000000000000, 1); TEST_pos(10000000000000, 10); TEST_pos(100000000000000, 100); TEST_pos(1000000000000000, 1000); TEST_pos(6553500000000000, 6553_5); TEST_pos(429496729500000000, 429496_7295); TEST_pos(18446744073700000000, 18446744_0737); TEST_pos(18446744073700000000, 18446744_0737000); TEST_pos(18446744073700000000, 18446744_07370000); TEST_pos(18446744073700000000, 18446744_073700000); TEST_pos(18446744073700000000, 18446744_0737000000000000000); /* Max supply */ TEST_pos(18446744073709551615, 18446744_073709551615); // Invalid numbers TEST_neg_n(~, empty_string); TEST_neg_n(-0, minus_0); TEST_neg_n(+0, plus_0); TEST_neg_n(-1, minus_1); TEST_neg_n(+1, plus_1); TEST_neg_n(_, only_point); // Don't go below 10^-12 TEST_neg(0_0000000000001); TEST_neg(0_0000000000009); TEST_neg(184467440737_000000001); // Overflow TEST_neg(184467440737_09551616); TEST_neg(184467440738); TEST_neg(18446744073709551616); // Two or more points TEST_neg(__); TEST_neg(0__); TEST_neg(__0); TEST_neg(0__0); TEST_neg(0_0_); TEST_neg(_0_0); TEST_neg(0_0_0);
[ "loldlm1@gmail.com" ]
loldlm1@gmail.com
d696f2542dd33069c75714574380e62bcf0f36a0
877952fc441da8749f1ccd55f0e23a61a5051efa
/AudioHandler.h
fabd9a186e3ef77bdadcdd593d62f0d8576a1e77
[]
no_license
nikopolides/thelastworldwar
a928a991d6d82855e9f055162dd0ca5d628aa1ae
bfb59e78f8ea7a36af2ee2a9fdb2ced0ad464740
refs/heads/master
2021-01-10T20:06:58.971669
2013-11-27T01:44:34
2013-11-27T01:44:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
451
h
#ifndef AUDIOHANDLER_H #define AUDIOHANDLER_H #include "SDL/SDL_mixer.h" #include "SDL/SDL.h" #include <thread> using namespace std; class AudioHandler{ public: Mix_Music *music = NULL; Mix_Chunk *effect = NULL; AudioHandler(); int playMusic(); int playMusicGame(); int playVoiceMenu(); int playEscolhaNacao(); int playEffect(); int playEffect_Enemy(); void initialize(); void finalize(); }; #endif
[ "matheus@ubuntu.ubuntu-domain" ]
matheus@ubuntu.ubuntu-domain
97cecdbee5edbf79ed0af26093fa7ea08bd92c2e
7f610e8792081df5955492c9b55755c72c79da17
/Coursera/demo/main.cpp
bf64eb0badcd4ad9878e59eac275f1eeb3c3ba29
[]
no_license
Parikshit22/Data-Structures-Algorithms-Cpp
8da910d0c1ba745ccfc016e0d0865f108b30cb04
4515f41c8a41850bc2888d4c83b9ce5dc9b66d68
refs/heads/master
2022-12-09T09:54:42.240609
2020-09-02T03:48:43
2020-09-02T03:48:43
276,821,418
1
0
null
null
null
null
UTF-8
C++
false
false
1,106
cpp
#include<bits/stdc++.h> using namespace std; class node{ public: int data; node *left; node *right; node(int n){ data = n; left = NULL; right = NULL; } }; node *bst(node *root,int n){ if(root==NULL){ root = new node(n); return root; } if(root->data>=n){ root->left = bst(root->left,n); } else{ root->right = bst(root->right,n); } return root; } node *tree(int *pre,int *in,int ps,int pe,int is,int ie){ if(ps>pe){ return NULL; } int iri; int pri = ps; int val = pre[ps]; for(int i=is;i<ie;i++){ if(i==val){ iri = i; break; } } int pls = pri+1; int ils = is; int ile = iri-1; int irs = iri+1; int ire = ie; int ple = ile-ils+pls; int prs = ple+1; int pre = pe; } int main(){ node *root = NULL; int n; cin>>n; int x; for(int i=0;i<n;i++){ cin>>x; root = bst(root,x); } int pre[] = {1,2,4,5,3,68,9,7}; int in[] = {4,2,5,1,8,6,9,3,7}; return 0; }
[ "parikshitagarwal40@gmail.com" ]
parikshitagarwal40@gmail.com
1f0002661bda7fc17a3b9cfea405391c57f8458d
9c5a72ded3a90e1afaadf194ec39bf4d9a4fc064
/LO21_PROJECT/build-UTComputer-Desktop_Qt_5_6_1_MinGW_32bit-Debug/debug/moc_qcomputer.cpp
482c108ed89a58882046bc965c11e8017c2099aa
[]
no_license
JulesAubry/UTC
f9c14e4f2dbe414c2b78c7d77e37fb716223819a
33d5cc55b678f68d46b1b689f52d7cf0d34255c5
refs/heads/master
2021-06-19T11:36:32.691200
2017-06-21T13:46:24
2017-06-21T13:46:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,294
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'qcomputer.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.6.1) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../../UTComputer/qcomputer.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'qcomputer.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.6.1. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE struct qt_meta_stringdata_QComputer_t { QByteArrayData data[18]; char stringdata0[288]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_QComputer_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_QComputer_t qt_meta_stringdata_QComputer = { { QT_MOC_LITERAL(0, 0, 9), // "QComputer" QT_MOC_LITERAL(1, 10, 7), // "refresh" QT_MOC_LITERAL(2, 18, 0), // "" QT_MOC_LITERAL(3, 19, 15), // "getNextCommande" QT_MOC_LITERAL(4, 35, 22), // "stateChangedBipOptions" QT_MOC_LITERAL(5, 58, 14), // "playBipOptions" QT_MOC_LITERAL(6, 73, 25), // "stateChangedOptionClavier" QT_MOC_LITERAL(7, 99, 15), // "buttonTriggered" QT_MOC_LITERAL(8, 115, 12), // "addProgramme" QT_MOC_LITERAL(9, 128, 15), // "deleteProgramme" QT_MOC_LITERAL(10, 144, 16), // "updateProgrammes" QT_MOC_LITERAL(11, 161, 19), // "editerProgrammeFunc" QT_MOC_LITERAL(12, 181, 22), // "lancerEditionProgramme" QT_MOC_LITERAL(13, 204, 11), // "addVariable" QT_MOC_LITERAL(14, 216, 14), // "deleteVariable" QT_MOC_LITERAL(15, 231, 15), // "updateVariables" QT_MOC_LITERAL(16, 247, 18), // "editerVariableFunc" QT_MOC_LITERAL(17, 266, 21) // "lancerEditionVariable" }, "QComputer\0refresh\0\0getNextCommande\0" "stateChangedBipOptions\0playBipOptions\0" "stateChangedOptionClavier\0buttonTriggered\0" "addProgramme\0deleteProgramme\0" "updateProgrammes\0editerProgrammeFunc\0" "lancerEditionProgramme\0addVariable\0" "deleteVariable\0updateVariables\0" "editerVariableFunc\0lancerEditionVariable" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_QComputer[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 16, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: name, argc, parameters, tag, flags 1, 0, 94, 2, 0x0a /* Public */, 3, 0, 95, 2, 0x0a /* Public */, 4, 1, 96, 2, 0x0a /* Public */, 5, 0, 99, 2, 0x0a /* Public */, 6, 1, 100, 2, 0x0a /* Public */, 7, 1, 103, 2, 0x0a /* Public */, 8, 0, 106, 2, 0x0a /* Public */, 9, 0, 107, 2, 0x0a /* Public */, 10, 0, 108, 2, 0x0a /* Public */, 11, 0, 109, 2, 0x0a /* Public */, 12, 0, 110, 2, 0x0a /* Public */, 13, 0, 111, 2, 0x0a /* Public */, 14, 0, 112, 2, 0x0a /* Public */, 15, 0, 113, 2, 0x0a /* Public */, 16, 0, 114, 2, 0x0a /* Public */, 17, 0, 115, 2, 0x0a /* Public */, // slots: parameters QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Int, 2, QMetaType::Void, QMetaType::Void, QMetaType::Int, 2, QMetaType::Void, QMetaType::Int, 2, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, 0 // eod }; void QComputer::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { QComputer *_t = static_cast<QComputer *>(_o); Q_UNUSED(_t) switch (_id) { case 0: _t->refresh(); break; case 1: _t->getNextCommande(); break; case 2: _t->stateChangedBipOptions((*reinterpret_cast< int(*)>(_a[1]))); break; case 3: _t->playBipOptions(); break; case 4: _t->stateChangedOptionClavier((*reinterpret_cast< int(*)>(_a[1]))); break; case 5: _t->buttonTriggered((*reinterpret_cast< int(*)>(_a[1]))); break; case 6: _t->addProgramme(); break; case 7: _t->deleteProgramme(); break; case 8: _t->updateProgrammes(); break; case 9: _t->editerProgrammeFunc(); break; case 10: _t->lancerEditionProgramme(); break; case 11: _t->addVariable(); break; case 12: _t->deleteVariable(); break; case 13: _t->updateVariables(); break; case 14: _t->editerVariableFunc(); break; case 15: _t->lancerEditionVariable(); break; default: ; } } } const QMetaObject QComputer::staticMetaObject = { { &QWidget::staticMetaObject, qt_meta_stringdata_QComputer.data, qt_meta_data_QComputer, qt_static_metacall, Q_NULLPTR, Q_NULLPTR} }; const QMetaObject *QComputer::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *QComputer::qt_metacast(const char *_clname) { if (!_clname) return Q_NULLPTR; if (!strcmp(_clname, qt_meta_stringdata_QComputer.stringdata0)) return static_cast<void*>(const_cast< QComputer*>(this)); return QWidget::qt_metacast(_clname); } int QComputer::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QWidget::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 16) qt_static_metacall(this, _c, _id, _a); _id -= 16; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 16) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 16; } return _id; } QT_END_MOC_NAMESPACE
[ "Jules Aubry" ]
Jules Aubry
605248a60383002b1c07470bfd695fb8a588eb74
62b29e7f99939f033a38ede3af52412889017a2d
/modules/bah.mod/datetime.mod/glue.cpp
7c2c071da8285ebe28a899c18044849bf7554c84
[]
no_license
Muttley/retroremakes-framework
f7e2642ebe5494e46933a1702fb620a5f8045816
df5fabac4fd33ee3da5ed3fdccc75c7a757afea0
refs/heads/master
2021-01-13T02:08:15.512097
2017-04-07T19:21:12
2017-04-07T19:21:12
33,143,417
1
1
null
null
null
null
UTF-8
C++
false
false
45,814
cpp
/* Copyright (c) 2007-2011 Bruce A Henderson 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 Bruce A Henderson 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 Bruce A Henderson ``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 Bruce A Henderson 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 <blitz.h> #include "boost/date_time/gregorian/gregorian.hpp" #include "boost/date_time/posix_time/posix_time.hpp" #include "boost/date_time/local_time/local_time.hpp" #include <iostream> #include <algorithm> #include <vector> using namespace boost::posix_time; using namespace boost::gregorian; using namespace boost::local_time; extern "C" { date * bmx_datetime_localday(); date * bmx_datetime_universalday(); date * bmx_datetime_newdate(int year, int month, int day); void bmx_datetime_delete(date * d); bool bmx_datetime_before(date * myDate, date * yourDate); bool bmx_datetime_after(date * myDate, date * yourDate); bool bmx_datetime_equals(date * myDate, date * yourDate); int bmx_datetime_year(date * d); int bmx_datetime_month(date * d); int bmx_datetime_day(date * d); void bmx_datetime_ymd(date * dt, int * y, int * m, int * d); date * bmx_datetime_fromstring(const char * d); date * bmx_datetime_fromundelimitedstring(const char * d); int bmx_datetime_day_of_week(date * d); int bmx_datetime_day_of_year(date * d); date * bmx_datetime_end_of_month(date * d); int bmx_datetime_week_number(date * d); date * bmx_datetime_date_add(date * d, long duration); date * bmx_datetime_date_subtract(date * d, long duration); long bmx_datetime_date_subdate(date * d1, date * d2); date_period * bmx_datetime_period_datedate(date * d1, date * d2); date_period * bmx_datetime_period_withdays(date * d, int length); void bmx_datetime_period_shift(date_period * p, int length); void bmx_datetime_period_delete(date_period * p); date * bmx_datetime_period_begin(date_period * p); date * bmx_datetime_period_last(date_period * p); date * bmx_datetime_period_end(date_period * p); int bmx_datetime_period_length(date_period * p); BBString * bmx_datetime_to_simple_string(date * d); BBString * bmx_datetime_period_to_simple_string(date_period * p); BBString * bmx_datetime_to_iso_string(date * d); BBString * bmx_datetime_to_iso_extended_string(date * d); BBString * bmx_datetime_to_string(date * d); BBString * bmx_datetime_period_to_string(date_period * p); bool bmx_datetime_period_isnull(date_period * p); bool bmx_datetime_period_containsdate(date_period * p, date * d); bool bmx_datetime_period_contains(date_period * p1, date_period * p2); bool bmx_datetime_period_intersects(date_period * p1, date_period * p2); date_period * bmx_datetime_period_intersection(date_period * p1, date_period * p2); bool bmx_datetime_period_adjacent(date_period * p1, date_period * p2); bool bmx_datetime_period_after(date_period * p, date * d); bool bmx_datetime_period_before(date_period * p, date * d); date_period * bmx_datetime_period_merge(date_period * p1, date_period * p2); date_period * bmx_datetime_period_span(date_period * p1, date_period * p2); bool bmx_datetime_period_isless(date_period * p1, date_period * p2); bool bmx_datetime_period_isgreater(date_period * p1, date_period * p2); bool bmx_datetime_period_isequal(date_period * p1, date_period * p2); void bmx_datetime_iter_forward(date_iterator * d); void bmx_datetime_iter_backward(date_iterator * d); day_iterator * bmx_datetime_dayiter(date * d, int offset); month_iterator * bmx_datetime_monthiter(date * d, int offset); year_iterator * bmx_datetime_yeariter(date * d, int offset); void bmx_datetime_iter_delete(date_iterator * d); bool bmx_datetime_iter_before(date_iterator * myDate, date * yourDate); bool bmx_datetime_iter_after(date_iterator * myDate, date * yourDate); bool bmx_datetime_iter_equals(date_iterator * myDate, date * yourDate); int bmx_datetime_iter_year(date_iterator * d); int bmx_datetime_iter_month(date_iterator * d); int bmx_datetime_iter_day(date_iterator * d); void bmx_datetime_iter_ymd(date_iterator * dt, int * y, int * m, int * d); int bmx_datetime_iter_day_of_week(date_iterator * d); int bmx_datetime_iter_day_of_year(date_iterator * d); date * bmx_datetime_iter_end_of_month(date_iterator * d); int bmx_datetime_iter_week_number(date_iterator * d); date * bmx_datetime_iter_date_add(date_iterator * d, long duration); date * bmx_datetime_iter_date_subtract(date_iterator * d, long duration); long bmx_datetime_iter_date_subdate(date_iterator * d1, date * d2); BBString * bmx_datetime_iter_to_simple_string(date_iterator * d); BBString * bmx_datetime_iter_to_iso_string(date_iterator * d); BBString * bmx_datetime_iter_to_iso_extended_string(date_iterator * d); BBString * bmx_datetime_iter_to_string(date_iterator * d); BBString * bmx_datetime_iter_asformat(date_iterator * d, const char * format); time_duration * bmx_time_duration(int hours, int minutes, int seconds, int fraction); void bmx_time_duration_delete(time_duration * d); time_duration * bmx_time_duration_new_hours(int value); time_duration * bmx_time_duration_new_minutes(int value); time_duration * bmx_time_duration_new_seconds(int value); time_duration * bmx_time_duration_new_milliseconds(int value); int bmx_time_duration_hours(time_duration * d); int bmx_time_duration_minutes(time_duration * d); int bmx_time_duration_seconds(time_duration * d); int bmx_time_duration_total_seconds(time_duration * d); int bmx_time_duration_total_milliseconds(time_duration * d); int bmx_time_duration_fractional_seconds(time_duration * d); bool bmx_time_duration_is_negative(time_duration * d); time_duration * bmx_time_duration_invert_sign(time_duration * d); BBString * bmx_time_duration_to_string(time_duration * d); BBString * bmx_time_duration_to_iso_string(time_duration * d); time_duration * bmx_time_duration_add(time_duration * d1, time_duration * d2); time_duration * bmx_time_duration_subtract(time_duration * d1, time_duration * d2); time_duration * bmx_time_duration_divide(time_duration * d1, int value); time_duration * bmx_time_duration_multiply(time_duration * d1, int value); bool bmx_time_duration_less(time_duration * d1, time_duration * d2); bool bmx_time_duration_greater(time_duration * d1, time_duration * d2); bool bmx_time_duration_equal(time_duration * d1, time_duration * d2); BBString * bmx_time_duration_asformat(time_duration * d, const char * format); int bmx_time_ticks_per_second(); int bmx_time_num_fractional_digits(); ptime * bmx_ptime_new(date * d, time_duration * t); void bmx_ptime_delete(ptime * p); ptime * bmx_ptime_local_new(); ptime * bmx_ptime_universal_new(); ptime * bmx_ptime_local_microsecond_new(); ptime * bmx_ptime_universal_microsecond_new(); date * bmx_ptime_date(ptime * p); time_duration * bmx_ptime_time_of_day(ptime * p); BBString * bmx_ptime_to_simple_string(ptime * p); BBString * bmx_ptime_to_iso_string(ptime * p); BBString * bmx_ptime_to_iso_extended_string(ptime * p); BBString * bmx_ptime_to_string(ptime * p); ptime * bmx_ptime_add_days(ptime * p, int d); ptime * bmx_ptime_subtract_days(ptime * p, int d); ptime * bmx_ptime_add_duration(ptime * p, time_duration * d); ptime * bmx_ptime_subtract_duration(ptime * p, time_duration * d); time_duration * bmx_ptime_subtract(ptime * p1, ptime * p2); bool bmx_ptime_less(ptime * p1, ptime * p2); bool bmx_ptime_greater(ptime * p1, ptime * p2); bool bmx_ptime_equal(ptime * p1, ptime * p2); ptime * bmx_ptime_from_time_t(std::time_t * t); BBString * bmx_ptime_asformat(ptime * p, const char * f); partial_date * bmx_partial_date_new(int day, int month); date * bmx_partial_date_get_date(partial_date * p, int year); void bmx_partial_date_delete(partial_date * p); last_day_of_the_week_in_month * bmx_last_day_of_week_in_month_new(int weekday, int month); date * bmx_last_day_of_week_in_month_get_date(last_day_of_the_week_in_month * p, int year); void bmx_last_day_of_week_in_month_delete(last_day_of_the_week_in_month * p); first_day_of_the_week_in_month * bmx_first_day_of_week_in_month_new(int weekday, int month); date * bmx_first_day_of_week_in_month_get_date(first_day_of_the_week_in_month * p, int year); void bmx_first_day_of_week_in_month_delete(first_day_of_the_week_in_month * p); BBString * bmx_weekday_to_string(int wd); date_facet * bmx_datefacet_new(); void bmx_datefacet_setcurrent(std::locale * loc, date_facet * d); BBString * bmx_date_asformat(date * d, const char * format); std::locale * bmx_locale_new(date_facet * d, const char * loc); time_facet * bmx_timefacet_new(); void bmx_timefacet_setcurrent(std::locale * loc, time_facet * d); void bmx_char_free(char * s); time_period * bmx_time_period_timetime(ptime * p1, ptime * p2); time_period * bmx_time_period_withduration(ptime * p, time_duration * d); void bmx_time_period_shift(time_period * tp, time_duration * d); void bmx_time_period_delete(time_period * tp); ptime * bmx_time_period_begin(time_period * tp); ptime * bmx_time_period_last(time_period * tp); ptime * bmx_time_period_end(time_period * tp); time_duration * bmx_time_period_length(time_period * tp); bool bmx_time_period_is_null(time_period * tp); bool bmx_time_period_contains(time_period * tp, ptime * t); bool bmx_time_period_containsPeriod(time_period * tp1, time_period * tp2); bool bmx_time_period_intersects(time_period * tp1, time_period * tp2); time_period * bmx_time_period_intersection(time_period * tp1, time_period * tp2); time_period * bmx_time_period_merge(time_period * tp1, time_period * tp2); time_period * bmx_time_period_span(time_period * tp1, time_period * tp2); bool bmx_time_period_isless(time_period * tp1, time_period * tp2); bool bmx_time_period_isgreater(time_period * tp1, time_period * tp2); bool bmx_time_period_isequal(time_period * tp1, time_period * tp2); posix_time_zone * bmx_posix_time_zone(const char * id); BBString * bmx_time_zone_dst_zone_abbrev(time_zone * tz); BBString * bmx_time_zone_std_zone_abbrev(time_zone * tz); BBString * bmx_time_zone_dst_zone_name(time_zone * tz); BBString * bmx_time_zone_std_zone_name(time_zone * tz); bool bmx_time_zone_has_dst(time_zone * tz); ptime * bmx_time_zone_dst_local_start_time(time_zone * tz, int year); ptime * bmx_time_zone_dst_local_end_time(time_zone * tz, int year); time_duration * bmx_time_zone_base_utc_offset(time_zone * tz); time_duration * bmx_time_zone_dst_offset(time_zone * tz); BBString * bmx_time_zone_to_posix_string(time_zone * tz); tz_database * bmx_tz_database(); tz_database * bmx_tz_load_from_file(const char * filename); time_zone_ptr bmx_tz_time_zone_from_region(tz_database * db, const char * id); local_date_time * bmx_local_date_time_new_sec_clock(time_zone * tz); local_date_time * bmx_local_date_time_new_time(ptime * p, time_zone * tz); BBString * bmx_month_to_string(int m); void bmx_date_facet_format(date_facet * f, const char * fmt); void bmx_date_facet_set_iso_format(date_facet * f); void bmx_date_facet_set_iso_extended_format(date_facet * f); void bmx_date_facet_short_month_names(date_facet * f, const char ** names); void bmx_date_facet_long_month_names(date_facet * f, const char ** names); void bmx_date_facet_short_weekday_names(date_facet * f, const char ** names); void bmx_date_facet_long_weekday_names(date_facet * f, const char ** names); void bmx_date_facet_month_format(date_facet * f, const char * fmt); void bmx_date_facet_weekday_format(date_facet * f, const char * fmt); void bmx_time_facet_format(time_facet * f, const char * fmt); void bmx_time_facet_set_iso_format(time_facet * f); void bmx_time_facet_set_iso_extended_format(time_facet * f); void bmx_time_facet_month_format(time_facet * f, const char * fmt); void bmx_time_facet_weekday_format(time_facet * f, const char * fmt); void bmx_time_facet_time_duration_format(time_facet * f, const char * fmt); nth_day_of_the_week_in_month * bmx_nth_day_of_week_in_month_new(int nth, int weekday, int month); date * bmx_nth_day_of_week_in_month_get_date(nth_day_of_the_week_in_month * p, int year); void bmx_nth_day_of_week_in_month_delete(nth_day_of_the_week_in_month * p); first_day_of_the_week_after * bmx_first_day_of_week_after_new(int weekday); date * bmx_first_day_of_week_after_get_date(first_day_of_the_week_after * p, date * d); void bmx_first_day_of_week_after_delete(first_day_of_the_week_after * p); first_day_of_the_week_before * bmx_first_day_of_week_before_new(int weekday); date * bmx_first_day_of_week_before_get_date(first_day_of_the_week_before * p, date * d); void bmx_first_day_of_week_before_delete(first_day_of_the_week_before * p); long bmx_days_until_weekday(date * d, int weekday); long bmx_days_before_weekday(date * d, int weekday); date * bmx_next_weekday(date * d, int weekday); date * bmx_previous_weekday(date * d, int weekday); time_zone_ptr bmx_local_date_time_zone(local_date_time * ldt); bool bmx_local_date_time_is_dst(local_date_time * ldt); ptime * bmx_local_date_time_utc_time(local_date_time * ldt); ptime * bmx_local_date_time_local_time(local_date_time * ldt); BBString * bmx_local_date_time_to_string(local_date_time * ldt); bool bmx_local_date_time_less(local_date_time * ldt1, local_date_time * ldt2); bool bmx_local_date_time_greater(local_date_time * ldt1, local_date_time * ldt2); bool bmx_local_date_time_equal(local_date_time * ldt1, local_date_time * ldt2); local_date_time * bmx_local_date_time_add_days(local_date_time * ldt, int value); local_date_time * bmx_local_date_time_add_months(local_date_time * ldt, int value); local_date_time * bmx_local_date_time_add_years(local_date_time * ldt, int value); local_date_time * bmx_local_date_time_subtract_days(local_date_time * ldt, int value); local_date_time * bmx_local_date_time_subtract_months(local_date_time * ldt, int value); local_date_time * bmx_local_date_time_subtract_years(local_date_time * ldt, int value); local_date_time * bmx_local_date_time_add_duration(local_date_time * ldt, time_duration * td); local_date_time * bmx_local_date_time_subtract_duration(local_date_time * ldt, time_duration * td); void bmx_local_date_time_delete(local_date_time * ldt); local_time_period * bmx_local_time_period_new(local_date_time * ldt1, local_date_time * ldt2); local_time_period * bmx_local_time_period_new_duration(local_date_time * ldt, time_duration * d); void bmx_local_time_period_delete(local_time_period * ldt); local_date_time * bmx_local_time_period_begin(local_time_period * ldt); local_date_time * bmx_local_time_period_last(local_time_period * ldt); local_date_time * bmx_local_time_period_end(local_time_period * ldt); time_duration * bmx_local_time_period_length(local_time_period * ldt); bool bmx_local_time_period_is_null(local_time_period * ldt); bool bmx_local_time_period_contains_time(local_time_period * ldt, local_date_time * t); bool bmx_local_time_period_contains(local_time_period * ldt1, local_time_period * ldt2); bool bmx_local_time_period_intersects(local_time_period * ldt1, local_time_period * ldt2); local_time_period * bmx_local_time_period_intersection(local_time_period * ldt1, local_time_period * ldt2); local_time_period * bmx_local_time_period_merge(local_time_period * ldt1, local_time_period * ldt2); local_time_period * bmx_local_time_period_span(local_time_period * ldt1, local_time_period * ldt2); void bmx_local_time_period_shift(local_time_period * ldt, time_duration * d); bool bmx_local_time_period_less(local_time_period * ldt1, local_time_period * ldt2); bool bmx_local_time_period_greater(local_time_period * ldt1, local_time_period * ldt2); bool bmx_local_time_period_equal(local_time_period * ldt1, local_time_period * ldt2); int bmx_end_of_month_day(int y, int m); } static date_facet * currentDateFacet = 0; static time_facet * currentTimeFacet = 0; static std::stringstream outputStringStream; BBString * bmx_BBString_from_stream() { BBString * s = bbStringFromCString(outputStringStream.str().c_str()); outputStringStream.str(""); return s; } char * bmx_cstr_from_stream() { char * s = strdup(outputStringStream.str().c_str()); outputStringStream.str(""); return s; } date * bmx_datetime_newdate(int year, int month, int day) { try { return new date(year, month, day); } catch (...) { return 0; } } void bmx_datetime_delete(date * d) { delete d; } date * bmx_datetime_localday() { return new date(day_clock::local_day()); } date * bmx_datetime_universalday() { return new date(day_clock::universal_day()); } bool bmx_datetime_before(date * myDate, date * yourDate) { return *myDate < *yourDate; } bool bmx_datetime_after(date * myDate, date * yourDate) { return *myDate > *yourDate; } bool bmx_datetime_equals(date * myDate, date * yourDate) { return *myDate == *yourDate; } int bmx_datetime_year(date * d) { return (int)d->year(); } int bmx_datetime_month(date * d) { return (int)d->month(); } int bmx_datetime_day(date * d) { return (int)d->day(); } void bmx_datetime_ymd(date * dt, int * y, int * m, int * d) { date::ymd_type ymd = dt->year_month_day(); *y = ymd.year; *m = ymd.month; *d = ymd.day; } date * bmx_datetime_fromstring(const char * d) { try { return new date(from_string(std::string(d))); } catch (...) { return 0; } } date * bmx_datetime_fromundelimitedstring(const char * d) { try { return new date(from_undelimited_string(std::string(d))); } catch (...) { return 0; } } int bmx_datetime_day_of_week(date * d) { return (int)d->day_of_week(); } int bmx_datetime_day_of_year(date * d) { return (int)d->day_of_year(); } date * bmx_datetime_end_of_month(date * d) { return new date(d->end_of_month()); } int bmx_datetime_week_number(date * d) { return (int)d->week_number(); } date * bmx_datetime_date_add(date * d, long duration) { return new date(*d + date_duration(duration)); } date * bmx_datetime_date_subtract(date * d, long duration) { return new date(*d - date_duration(duration)); } long bmx_datetime_date_subdate(date * d1, date * d2) { date_duration duration = *d1 - *d2; return duration.days(); } date_period * bmx_datetime_period_datedate(date * d1, date * d2) { return new date_period(*d1, *d2); } date_period * bmx_datetime_period_withdays(date * d, int length) { return new date_period(*d, days(length)); } void bmx_datetime_period_shift(date_period * p, int length) { p->shift(days(length)); } void bmx_datetime_period_delete(date_period * p) { delete p; } date * bmx_datetime_period_begin(date_period * p) { return new date(p->begin()); } date * bmx_datetime_period_last(date_period * p) { return new date(p->last()); } date * bmx_datetime_period_end(date_period * p) { return new date(p->end()); } int bmx_datetime_period_length(date_period * p) { return p->length().days(); } BBString * bmx_datetime_to_simple_string(date * d) { return bbStringFromCString(to_simple_string(*d).c_str()); /*currentDateFacet->format("%Y-%b-%d");*/ } BBString * bmx_datetime_to_string(date * d) { outputStringStream << *d; return bmx_BBString_from_stream(); } BBString * bmx_datetime_period_to_simple_string(date_period * p) { return bbStringFromCString(to_simple_string(*p).c_str()); } BBString * bmx_datetime_to_iso_string(date * d) { return bbStringFromCString(to_iso_string(*d).c_str()); //currentDateFacet->format("%Y%m%d"); //outputStringStream << *d; //return bmx_BBString_from_stream(); } BBString * bmx_datetime_to_iso_extended_string(date * d) { return bbStringFromCString(to_iso_extended_string(*d).c_str()); //currentDateFacet->format("%Y-%m-%d"); //outputStringStream << *d; //return bmx_BBString_from_stream(); } BBString * bmx_datetime_period_to_string(date_period * p) { outputStringStream << *p; return bmx_BBString_from_stream(); //return bbStringFromCString(to_simple_string(*p).c_str()); } bool bmx_datetime_period_isnull(date_period * p) { return p->is_null(); } bool bmx_datetime_period_containsdate(date_period * p, date * d) { return p->contains(*d); } bool bmx_datetime_period_contains(date_period * p1, date_period * p2) { return p1->contains(*p2); } bool bmx_datetime_period_intersects(date_period * p1, date_period * p2) { return p1->intersects(*p2); } date_period * bmx_datetime_period_intersection(date_period * p1, date_period * p2) { return new date_period(p1->intersection(*p2)); } bool bmx_datetime_period_adjacent(date_period * p1, date_period * p2) { return p1->is_adjacent(*p2); } bool bmx_datetime_period_after(date_period * p, date * d) { return p->is_after(*d); } bool bmx_datetime_period_before(date_period * p, date * d) { return p->is_before(*d); } date_period * bmx_datetime_period_merge(date_period * p1, date_period * p2) { return new date_period(p1->merge(*p2)); } date_period * bmx_datetime_period_span(date_period * p1, date_period * p2) { return new date_period(p1->span(*p2)); } bool bmx_datetime_period_isless(date_period * p1, date_period * p2) { return *p1 < *p2; } bool bmx_datetime_period_isgreater(date_period * p1, date_period * p2) { return *p1 > *p2; } bool bmx_datetime_period_isequal(date_period * p1, date_period * p2) { return *p1 == *p2; } day_iterator * bmx_datetime_dayiter(date * d, int offset) { return new day_iterator(*d, offset); } month_iterator * bmx_datetime_monthiter(date * d, int offset) { return new month_iterator(*d, offset); } year_iterator * bmx_datetime_yeariter(date * d, int offset) { return new year_iterator(*d, offset); } void bmx_datetime_iter_delete(date_iterator * d) { delete d; } void bmx_datetime_iter_forward(date_iterator * d) { ++*d; } void bmx_datetime_iter_backward(date_iterator * d) { --*d; } bool bmx_datetime_iter_before(date_iterator * myDate, date * yourDate) { return (*(day_iterator *)myDate) < *yourDate; } bool bmx_datetime_iter_after(date_iterator * myDate, date * yourDate) { return (*(day_iterator *)myDate) > *yourDate; } bool bmx_datetime_iter_equals(date_iterator * myDate, date * yourDate) { return (*(day_iterator *)myDate) == *yourDate; } int bmx_datetime_iter_year(date_iterator * d) { return (int)(*(day_iterator *)d)->year(); } int bmx_datetime_iter_month(date_iterator * d) { return (int)(*(day_iterator *)d)->month(); } int bmx_datetime_iter_day(date_iterator * d) { return (int)(*(day_iterator *)d)->day(); } void bmx_datetime_iter_ymd(date_iterator * dt, int * y, int * m, int * d) { date::ymd_type ymd = (*(day_iterator *)dt)->year_month_day(); *y = ymd.year; *m = ymd.month; *d = ymd.day; } int bmx_datetime_iter_day_of_week(date_iterator * d) { return (int)(*(day_iterator *)d)->day_of_week(); } int bmx_datetime_iter_day_of_year(date_iterator * d) { return (int)(*(day_iterator *)d)->day_of_year(); } date * bmx_datetime_iter_end_of_month(date_iterator * d) { return new date((*(day_iterator *)d)->end_of_month()); } int bmx_datetime_iter_week_number(date_iterator * d) { return (int)(*(day_iterator *)d)->week_number(); } date * bmx_datetime_iter_date_add(date_iterator * d, long duration) { date dd(**d); return new date(dd + date_duration(duration)); } date * bmx_datetime_iter_date_subtract(date_iterator * d, long duration) { return new date(**d - date_duration(duration)); } long bmx_datetime_iter_date_subdate(date_iterator * d1, date * d2) { date_duration duration = (**d1) - *d2; return duration.days(); } BBString * bmx_datetime_iter_to_simple_string(date_iterator * d) { return bbStringFromCString(to_simple_string((**d)).c_str()); } BBString * bmx_datetime_iter_to_iso_string(date_iterator * d) { return bbStringFromCString(to_iso_string((**d)).c_str()); } BBString * bmx_datetime_iter_to_iso_extended_string(date_iterator * d) { return bbStringFromCString(to_iso_extended_string((**d)).c_str()); } BBString * bmx_datetime_iter_to_string(date_iterator * d) { outputStringStream << (**d); return bmx_BBString_from_stream(); } BBString * bmx_datetime_iter_asformat(date_iterator * d, const char * format) { currentDateFacet->format(format); outputStringStream << **d; return bmx_BBString_from_stream(); } time_duration * bmx_time_duration(int hours, int minutes, int seconds, int fraction) { return new time_duration(hours, minutes, seconds, fraction); } void bmx_time_duration_delete(time_duration * d) { delete d; } time_duration * bmx_time_duration_new_hours(int value) { return new time_duration(hours(value)); } time_duration * bmx_time_duration_new_minutes(int value) { return new time_duration(minutes(value)); } time_duration * bmx_time_duration_new_seconds(int value) { return new time_duration(seconds(value)); } time_duration * bmx_time_duration_new_milliseconds(int value) { return new time_duration(milliseconds(value)); } int bmx_time_duration_hours(time_duration * d) { return d->hours(); } int bmx_time_duration_minutes(time_duration * d) { return d->minutes(); } int bmx_time_duration_seconds(time_duration * d) { return d->seconds(); } int bmx_time_duration_total_seconds(time_duration * d) { return d->total_seconds(); } int bmx_time_ticks_per_second() { return time_duration::ticks_per_second(); } int bmx_time_num_fractional_digits() { return (int)time_duration::num_fractional_digits(); } int bmx_time_duration_total_milliseconds(time_duration * d) { return d->total_milliseconds(); } int bmx_time_duration_fractional_seconds(time_duration * d) { return d->fractional_seconds(); } bool bmx_time_duration_is_negative(time_duration * d) { return d->is_negative(); } time_duration * bmx_time_duration_invert_sign(time_duration * d) { return new time_duration(d->invert_sign()); } BBString * bmx_time_duration_to_string(time_duration * d) { return bbStringFromCString(to_simple_string(*d).c_str()); } BBString * bmx_time_duration_to_iso_string(time_duration * d) { return bbStringFromCString(to_iso_string(*d).c_str()); } time_duration * bmx_time_duration_add(time_duration * d1, time_duration * d2) { return new time_duration(*d1 + *d2); } time_duration * bmx_time_duration_subtract(time_duration * d1, time_duration * d2) { return new time_duration(*d1 - *d2); } time_duration * bmx_time_duration_divide(time_duration * d1, int value) { return new time_duration(*d1 / value); } time_duration * bmx_time_duration_multiply(time_duration * d1, int value) { return new time_duration(*d1 * value); } bool bmx_time_duration_less(time_duration * d1, time_duration * d2) { return *d1 < *d2; } bool bmx_time_duration_greater(time_duration * d1, time_duration * d2) { return *d1 > *d2; } bool bmx_time_duration_equal(time_duration * d1, time_duration * d2) { return *d1 == *d2; } BBString * bmx_time_duration_asformat(time_duration * d, const char * format) { currentTimeFacet->time_duration_format(format); outputStringStream << *d; return bmx_BBString_from_stream(); } ptime * bmx_ptime_new(date * d, time_duration * t) { return new ptime(*d, *t); } void bmx_ptime_delete(ptime * p) { delete p; } ptime * bmx_ptime_local_new() { return new ptime(second_clock::local_time()); } ptime * bmx_ptime_universal_new() { return new ptime(second_clock::universal_time()); } ptime * bmx_ptime_local_microsecond_new() { return new ptime(microsec_clock::local_time()); } ptime * bmx_ptime_universal_microsecond_new() { return new ptime(microsec_clock::universal_time()); } date * bmx_ptime_date(ptime * p) { return new date(p->date()); } time_duration * bmx_ptime_time_of_day(ptime * p) { return new time_duration(p->time_of_day()); } BBString * bmx_ptime_to_simple_string(ptime * p) { return bbStringFromCString(to_simple_string(*p).c_str()); } BBString * bmx_ptime_to_string(ptime * p) { outputStringStream << (*p); return bmx_BBString_from_stream(); } BBString * bmx_ptime_to_iso_string(ptime * p) { return bbStringFromCString(to_iso_string(*p).c_str()); } BBString * bmx_ptime_to_iso_extended_string(ptime * p) { return bbStringFromCString(to_iso_extended_string(*p).c_str()); } ptime * bmx_ptime_add_days(ptime * p, int d) { return new ptime(*p + days(d)); } ptime * bmx_ptime_subtract_days(ptime * p, int d) { return new ptime(*p - days(d)); } ptime * bmx_ptime_add_duration(ptime * p, time_duration * d) { return new ptime(*p + *d); } ptime * bmx_ptime_subtract_duration(ptime * p, time_duration * d) { return new ptime(*p - *d); } time_duration * bmx_ptime_subtract(ptime * p1, ptime * p2) { return new time_duration(*p1 - *p2); } bool bmx_ptime_less(ptime * p1, ptime * p2) { return *p1 < *p2; } bool bmx_ptime_greater(ptime * p1, ptime * p2) { return *p1 > *p2; } bool bmx_ptime_equal(ptime * p1, ptime * p2) { return *p1 == *p2; } BBString * bmx_ptime_asformat(ptime * p, const char * format) { currentTimeFacet->format(format); outputStringStream << *p; return bmx_BBString_from_stream(); } partial_date * bmx_partial_date_new(int day, int month) { return new partial_date(day, month); } date * bmx_partial_date_get_date(partial_date * p, int year) { return new date(p->get_date(year)); } void bmx_partial_date_delete(partial_date * p) { delete p; } last_day_of_the_week_in_month * bmx_last_day_of_week_in_month_new(int weekday, int month) { return new last_day_of_the_week_in_month(weekday, month); } date * bmx_last_day_of_week_in_month_get_date(last_day_of_the_week_in_month * p, int year) { return new date(p->get_date(year)); } void bmx_last_day_of_week_in_month_delete(last_day_of_the_week_in_month * p) { delete p; } first_day_of_the_week_in_month * bmx_first_day_of_week_in_month_new(int weekday, int month) { return new first_day_of_the_week_in_month(weekday, month); } date * bmx_first_day_of_week_in_month_get_date(first_day_of_the_week_in_month * p, int year) { return new date(p->get_date(year)); } void bmx_first_day_of_week_in_month_delete(first_day_of_the_week_in_month * p) { delete p; } BBString * bmx_weekday_to_string(int wd) { outputStringStream << greg_weekday((unsigned short)wd); return bmx_BBString_from_stream(); } date_facet * bmx_datefacet_new() { return new date_facet; } time_facet * bmx_timefacet_new() { return new time_facet; } void bmx_datefacet_setcurrent(std::locale * loc, date_facet * d) { if (currentDateFacet) { delete currentDateFacet; } currentDateFacet = d; outputStringStream.imbue(*loc); } void bmx_timefacet_setcurrent(std::locale * loc, time_facet * t) { if (currentTimeFacet) { delete currentTimeFacet; } currentTimeFacet = t; outputStringStream.imbue(*loc); } BBString * bmx_date_asformat(date * d, const char * format) { currentDateFacet->format(format); outputStringStream << *d; return bmx_BBString_from_stream(); } std::locale * bmx_locale_new(date_facet * d, const char * loc) { try { return new std::locale(std::locale(loc), d); } catch (...) { return new std::locale(std::locale(""), d); } } void bmx_char_free(char * s) { free(s); } time_period * bmx_time_period_timetime(ptime * p1, ptime * p2) { return new time_period(*p1, *p2); } time_period * bmx_time_period_withduration(ptime * p, time_duration * d) { return new time_period(*p, *d); } void bmx_time_period_shift(time_period * tp, time_duration * d) { tp->shift(*d); } ptime * bmx_time_period_begin(time_period * tp) { return new ptime(tp->begin()); } void bmx_time_period_delete(time_period * tp) { delete tp; } ptime * bmx_time_period_last(time_period * tp) { return new ptime(tp->last()); } ptime * bmx_time_period_end(time_period * tp) { return new ptime(tp->end()); } time_duration * bmx_time_period_length(time_period * tp) { return new time_duration(tp->length()); } bool bmx_time_period_is_null(time_period * tp) { return tp->is_null(); } bool bmx_time_period_contains(time_period * tp, ptime * t) { return tp->contains(*t); } bool bmx_time_period_containsPeriod(time_period * tp1, time_period * tp2) { return tp1->contains(*tp2); } bool bmx_time_period_intersects(time_period * tp1, time_period * tp2) { return tp1->intersects(*tp2); } time_period * bmx_time_period_intersection(time_period * tp1, time_period * tp2) { return new time_period(tp1->intersection(*tp2)); } time_period * bmx_time_period_merge(time_period * tp1, time_period * tp2) { return new time_period(tp1->merge(*tp2)); } time_period * bmx_time_period_span(time_period * tp1, time_period * tp2) { return new time_period(tp1->span(*tp2)); } bool bmx_time_period_isless(time_period * tp1, time_period * tp2) { return *tp1 < *tp2; } bool bmx_time_period_isgreater(time_period * tp1, time_period * tp2) { return *tp1 > *tp2; } bool bmx_time_period_isequal(time_period * tp1, time_period * tp2) { return *tp1 == *tp2; } ptime * bmx_ptime_from_time_t(std::time_t * t) { return new ptime(from_time_t(*t)); } posix_time_zone * bmx_posix_time_zone(const char * id) { return new posix_time_zone(std::string(id)); } BBString * bmx_time_zone_dst_zone_abbrev(time_zone * tz) { return bbStringFromCString(tz->dst_zone_abbrev().c_str()); } BBString * bmx_time_zone_std_zone_abbrev(time_zone * tz) { return bbStringFromCString(tz->std_zone_abbrev().c_str()); } BBString * bmx_time_zone_dst_zone_name(time_zone * tz) { return bbStringFromCString(tz->dst_zone_name().c_str()); } BBString * bmx_time_zone_std_zone_name(time_zone * tz) { return bbStringFromCString(tz->std_zone_name().c_str()); } bool bmx_time_zone_has_dst(time_zone * tz) { return tz->has_dst(); } ptime * bmx_time_zone_dst_local_start_time(time_zone * tz, int year) { return new ptime(tz->dst_local_start_time(year)); } ptime * bmx_time_zone_dst_local_end_time(time_zone * tz, int year) { return new ptime(tz->dst_local_end_time(year)); } time_duration * bmx_time_zone_base_utc_offset(time_zone * tz) { return new time_duration(tz->base_utc_offset()); } time_duration * bmx_time_zone_dst_offset(time_zone * tz) { return new time_duration(tz->dst_offset()); } BBString * bmx_time_zone_to_posix_string(time_zone * tz) { return bbStringFromCString(tz->to_posix_string().c_str()); } tz_database * bmx_tz_database() { return new tz_database(); } tz_database * bmx_tz_load_from_file(const char * filename) { tz_database * db = new tz_database(); db->load_from_file(std::string(filename)); return db; } time_zone_ptr bmx_tz_time_zone_from_region(tz_database * db, const char * id) { return db->time_zone_from_region(std::string(id)); } local_date_time * bmx_local_date_time_new_sec_clock(time_zone * tz) { return new local_date_time(local_sec_clock::local_time(time_zone_ptr(tz))); } local_date_time * bmx_local_date_time_new_time(ptime * p, time_zone * tz) { return new local_date_time(*p, time_zone_ptr(tz)); } BBString * bmx_month_to_string(int m) { outputStringStream << greg_month((unsigned short)m); return bmx_BBString_from_stream(); } void bmx_date_facet_format(date_facet * f, const char * fmt) { f->format(fmt); } void bmx_date_facet_set_iso_format(date_facet * f) { f->set_iso_format(); } void bmx_date_facet_set_iso_extended_format(date_facet * f) { f->set_iso_extended_format(); } void bmx_date_facet_short_month_names(date_facet * f, const char ** names) { std::string m_names[12]; for (int i = 0; i < 12; i++) { m_names[i] = std::string(names[i]); } std::vector<std::string> v_names(&m_names[0], &m_names[12]); f->short_month_names(v_names); } void bmx_date_facet_long_month_names(date_facet * f, const char ** names) { std::string m_names[12]; for (int i = 0; i < 12; i++) { m_names[i] = std::string(names[i]); } std::vector<std::string> v_names(&m_names[0], &m_names[12]); f->long_month_names(v_names); } void bmx_date_facet_short_weekday_names(date_facet * f, const char ** names) { std::string m_names[7]; for (int i = 0; i < 7; i++) { m_names[i] = std::string(names[i]); } std::vector<std::string> v_names(&m_names[0], &m_names[7]); f->short_weekday_names(v_names); } void bmx_date_facet_long_weekday_names(date_facet * f, const char ** names) { std::string m_names[7]; for (int i = 0; i < 7; i++) { m_names[i] = std::string(names[i]); } std::vector<std::string> v_names(&m_names[0], &m_names[7]); f->long_weekday_names(v_names); } void bmx_date_facet_month_format(date_facet * f, const char * fmt) { f->month_format(fmt); } void bmx_date_facet_weekday_format(date_facet * f, const char * fmt) { f->weekday_format(fmt); } void bmx_time_facet_format(time_facet * f, const char * fmt) { f->format(fmt); } void bmx_time_facet_set_iso_format(time_facet * f) { f->set_iso_format(); } void bmx_time_facet_set_iso_extended_format(time_facet * f) { f->set_iso_extended_format(); } void bmx_time_facet_month_format(time_facet * f, const char * fmt) { f->month_format(fmt); } void bmx_time_facet_weekday_format(time_facet * f, const char * fmt) { f->weekday_format(fmt); } void bmx_time_facet_time_duration_format(time_facet * f, const char * fmt) { f->time_duration_format(fmt); } nth_day_of_the_week_in_month * bmx_nth_day_of_week_in_month_new(int nth, int weekday, int month) { nth_day_of_the_week_in_month::week_num w; switch (nth) { case 1: w = nth_day_of_the_week_in_month::first; break; case 2: w = nth_day_of_the_week_in_month::second; break; case 3: w = nth_day_of_the_week_in_month::third; break; case 4: w = nth_day_of_the_week_in_month::fourth; break; case 5: w = nth_day_of_the_week_in_month::fifth; break; default: w = nth_day_of_the_week_in_month::first; } return new nth_day_of_the_week_in_month(w, weekday, month); } date * bmx_nth_day_of_week_in_month_get_date(nth_day_of_the_week_in_month * p, int year) { return new date(p->get_date(year)); } void bmx_nth_day_of_week_in_month_delete(nth_day_of_the_week_in_month * p) { delete p; } first_day_of_the_week_after * bmx_first_day_of_week_after_new(int weekday) { return new first_day_of_the_week_after(weekday); } date * bmx_first_day_of_week_after_get_date(first_day_of_the_week_after * p, date * d) { return new date(p->get_date(*d)); } void bmx_first_day_of_week_after_delete(first_day_of_the_week_after * p) { delete p; } first_day_of_the_week_before * bmx_first_day_of_week_before_new(int weekday) { return new first_day_of_the_week_before(greg_weekday(weekday)); } date * bmx_first_day_of_week_before_get_date(first_day_of_the_week_before * p, date * d) { return new date(p->get_date(*d)); } void bmx_first_day_of_week_before_delete(first_day_of_the_week_before * p) { delete p; } long bmx_days_until_weekday(date * d, int weekday) { return days_until_weekday(*d, greg_weekday(weekday)).days(); } long bmx_days_before_weekday(date * d, int weekday) { return days_before_weekday(*d, greg_weekday(weekday)).days(); } date * bmx_next_weekday(date * d, int weekday) { return new date(next_weekday(*d, greg_weekday(weekday))); } date * bmx_previous_weekday(date * d, int weekday) { return new date(previous_weekday(*d, greg_weekday(weekday))); } time_zone_ptr bmx_local_date_time_zone(local_date_time * ldt) { return ldt->zone(); } bool bmx_local_date_time_is_dst(local_date_time * ldt) { return ldt->is_dst(); } ptime * bmx_local_date_time_utc_time(local_date_time * ldt) { return new ptime(ldt->utc_time()); } ptime * bmx_local_date_time_local_time(local_date_time * ldt) { return new ptime(ldt->local_time()); } BBString * bmx_local_date_time_to_string(local_date_time * ldt) { outputStringStream << *ldt; return bmx_BBString_from_stream(); } bool bmx_local_date_time_less(local_date_time * ldt1, local_date_time * ldt2) { return *ldt1 < *ldt2; } bool bmx_local_date_time_greater(local_date_time * ldt1, local_date_time * ldt2) { return *ldt1 > *ldt2; } bool bmx_local_date_time_equal(local_date_time * ldt1, local_date_time * ldt2) { return *ldt1 == *ldt2; } local_date_time * bmx_local_date_time_add_days(local_date_time * ldt, int value) { return new local_date_time(*ldt + days(value)); } local_date_time * bmx_local_date_time_add_months(local_date_time * ldt, int value) { return new local_date_time(*ldt + months(value)); } local_date_time * bmx_local_date_time_add_years(local_date_time * ldt, int value) { return new local_date_time(*ldt + years(value)); } local_date_time * bmx_local_date_time_subtract_days(local_date_time * ldt, int value) { return new local_date_time(*ldt - days(value)); } local_date_time * bmx_local_date_time_subtract_months(local_date_time * ldt, int value) { return new local_date_time(*ldt - months(value)); } local_date_time * bmx_local_date_time_subtract_years(local_date_time * ldt, int value) { return new local_date_time(*ldt - years(value)); } local_date_time * bmx_local_date_time_add_duration(local_date_time * ldt, time_duration * td) { return new local_date_time(*ldt + *td); } local_date_time * bmx_local_date_time_subtract_duration(local_date_time * ldt, time_duration * td) { return new local_date_time(*ldt - *td); } void bmx_local_date_time_delete(local_date_time * ldt) { delete ldt; } local_time_period * bmx_local_time_period_new(local_date_time * ldt1, local_date_time * ldt2) { return new local_time_period(*ldt1, *ldt2); } local_time_period * bmx_local_time_period_new_duration(local_date_time * ldt, time_duration * d) { return new local_time_period(*ldt, *d); } void bmx_local_time_period_delete(local_time_period * ldt) { delete ldt; } local_date_time * bmx_local_time_period_begin(local_time_period * ldt) { return new local_date_time(ldt->begin()); } local_date_time * bmx_local_time_period_last(local_time_period * ldt) { return new local_date_time(ldt->last()); } local_date_time * bmx_local_time_period_end(local_time_period * ldt) { return new local_date_time(ldt->end()); } time_duration * bmx_local_time_period_length(local_time_period * ldt) { return new time_duration(ldt->length()); } bool bmx_local_time_period_is_null(local_time_period * ldt) { return ldt->is_null(); } bool bmx_local_time_period_contains_time(local_time_period * ldt, local_date_time * t) { return ldt->contains(*t); } bool bmx_local_time_period_contains(local_time_period * ldt1, local_time_period * ldt2) { return ldt1->contains(*ldt2); } bool bmx_local_time_period_intersects(local_time_period * ldt1, local_time_period * ldt2) { return ldt1->intersects(*ldt2); } local_time_period * bmx_local_time_period_intersection(local_time_period * ldt1, local_time_period * ldt2) { return new local_time_period(ldt1->intersection(*ldt2)); } local_time_period * bmx_local_time_period_merge(local_time_period * ldt1, local_time_period * ldt2) { return new local_time_period(ldt1->merge(*ldt2)); } local_time_period * bmx_local_time_period_span(local_time_period * ldt1, local_time_period * ldt2) { return new local_time_period(ldt1->span(*ldt2)); } void bmx_local_time_period_shift(local_time_period * ldt, time_duration * d) { ldt->shift(*d); } bool bmx_local_time_period_less(local_time_period * ldt1, local_time_period * ldt2) { return *ldt1 < *ldt2; } bool bmx_local_time_period_greater(local_time_period * ldt1, local_time_period * ldt2) { return *ldt1 > *ldt2; } bool bmx_local_time_period_equal(local_time_period * ldt1, local_time_period * ldt2) { return *ldt1 == *ldt2; } int bmx_end_of_month_day(int y, int m) { return gregorian_calendar::end_of_month_day(y, m); }
[ "paul.maskelyne@accumuli.com" ]
paul.maskelyne@accumuli.com
0970a9aea821f548f9c103040e0f9b6cb8bbe055
c4420fa6dcb8f972cbf16eeede6bf314bfad62a2
/C/66_경로탐색(방향그래프 인접리스트_used Vector)/refSol/성공/64(참고용).cpp
bd500da69984473b6c212d1b39b34613bd94b688
[]
no_license
horingring/Algorithm
eb2815e1161527a62dcc4c8f680b798a81bcd6ab
5fd195a140876ec3a0239036153f4315951fa9bb
refs/heads/master
2023-06-12T02:27:56.963203
2021-06-30T06:14:37
2021-06-30T06:14:37
239,685,288
1
0
null
null
null
null
UTF-8
C++
false
false
583
cpp
#include <stdio.h> #include <vector> using namespace std; int n, cnt = 0; vector < vector <int> > map; vector <int> visit; void DFS(int x) { visit[x] = 1; if (x == n) { cnt++; visit[x] = 0; return; } for (int k = 1; k <= n; k++) { if (map[x][k] && !visit[k]) DFS(k); } visit[x] = 0; } int main() { int m; int a, b; scanf_s("%d %d", &n, &m); map = vector< vector <int> >(n + 1, vector <int>(n + 1, 0)); visit = vector<int>(n + 1, 0); for (int i = 0; i < m; i++) { scanf_s("%d %d", &a, &b); map[a][b] = 1; } DFS(1); printf("%d", cnt); return 0; }
[ "dldldksl@naver.com" ]
dldldksl@naver.com
0d0b2d6cefc90966ef93f8962e02380d59a415a0
2b6776c38240161c43fd1629287933448dcad168
/src/Audio/MusicStreamPlayer.hpp
af6d06af4134e0b3f7edcdbe75e7cd89c5c1bee5
[ "Zlib" ]
permissive
sammyg-dev/shade-player
ce86862e7e67c5cdaaa45a3174f7e745c94ce0a9
e00a4e0dcbe158b471e47312ffa9c86598557c00
refs/heads/main
2023-03-07T05:00:31.833039
2021-02-19T21:39:42
2021-02-19T21:39:42
318,600,449
0
0
null
null
null
null
UTF-8
C++
false
false
11,368
hpp
#ifndef _SHADEPLAYER_INCLUDE_MUSICSTREAMPLAYER_HPP_ #define _SHADEPLAYER_INCLUDE_MUSICSTREAMPLAYER_HPP_ #include <raylib.h> #include <vector> #include <string> #include "AudioTypes.h" #include "AudioAnalyzer.hpp" #include "../Core/EventEmitter.hpp" using namespace std; namespace shade { /* * AudioPlayer based on raylib's AudioStream * features: * - songs playlist with standard controls * - .wav file support (todo: add more, limited by AudioAnalyzer atm) * - AudioAnalyzer for real-time audio analysis */ class AudioPlayer { public: AudioPlayer(){ m_samplingRate = 44100.0; m_spu = 4096; m_audioAnalyzer = AudioAnalyzer(); BindEvents(); }; ~AudioPlayer(){ if(m_audioData != nullptr){ delete [] m_audioData; } if(m_audioBuff != nullptr){ delete [] m_audioBuff; } if(m_pAudioStream != nullptr){ CloseAudioStream(*m_pAudioStream); delete m_pAudioStream; m_pAudioStream = nullptr; } //m_playlist.clear(); }; void Update(float deltaTime){ if(m_state == PLAYING){ m_playTime += deltaTime; if(IsAudioStreamProcessed(*m_pAudioStream)){ for(int i = 0; i < m_spu; ++i){ // check for end of song data if(m_audioDataCursor > m_audioDataSize){ // loop buffer else fill with zeroes and playnext if(m_loopState == LoopState::SONG || (m_playlist.size() == 1 && m_loopState == LoopState::PLAYLIST)){ // this should only trigger once, we reset ish m_audioDataCursor = 0; ResetPlayTime(); } else { m_audioBuff[i] = 0; m_state = PlaybackState::SONG_FINISHED; } } else { // not end, just set data m_audioBuff[i] = m_audioData[m_audioDataCursor]; } ++m_audioDataCursor; } // } else { // setup next audio buffer // int j = 0; // for(int i = m_audioDataCursor; i < m_audioDataCursor + m_spu; ++i){ // m_audioBuff[j] = m_audioData[i]; // ++j; // } // m_audioDataCursor += m_spu; // } UpdateAudioStream(*m_pAudioStream, m_audioBuff, m_spu); } // update analyzer m_audioAnalyzer.Update(deltaTime, m_audioBuff, m_spu, m_audioDataCursor); } else if (m_state == SONG_FINISHED){ if(IsAudioStreamProcessed(*m_pAudioStream)){ OnSongFinished(); } } // do nothing } void OnSongFinished(){ Stop(); CloseAudioStream(*m_pAudioStream); delete m_pAudioStream; m_pAudioStream = nullptr; PlayNext(); } ////////////////////////////// /// Play Controls ////////////////////////////// // begins playing current song in playlist, or continues from pause void Play(){ if(m_playlist.size() <= 0 ) return; m_state = PlaybackState::LOADING; auto song = m_playlist[m_playlistIndex]; if(!IsAudioDeviceReady()){ printf("Audio device not ready! Cannot play song"); m_state = PlaybackState::ERROR; return; } // things todo: // - support 2 channels? only seems to work with setting mono this way // - instead of loading wave, just us a Music stream and grab the audio buffer per update somehow? Music music = LoadMusicStream(song.Filepath.c_str()); // not sure if i need to unload? m_audioDataSize = music.sampleCount; m_audioData = new short[m_audioDataSize]; m_audioBuff = new short[m_spu]; memcpy(m_audioData, music.stream.buffer, m_audioDataSize*2); // set the audio buff from raw data for(int i = 0; i < m_spu; ++i){ m_audioBuff[i] = m_audioData[i]; } // update audio buff cursor position m_audioDataCursor += m_spu; // begin playing stream from audio buffer m_pAudioStream = new AudioStream(InitAudioStream(m_samplingRate, music.stream.sampleSize, 1)); SetVolume(m_volume); // set audio stream volume UpdateAudioStream(*m_pAudioStream, m_audioBuff, m_spu); PlayAudioStream(*m_pAudioStream); UnloadMusicStream(music); // init audio analyzer m_audioAnalyzer.Init(m_audioBuff, m_spu, m_audioDataSize); // update plaeyr state if(IsAudioStreamPlaying(*m_pAudioStream)){ m_state = PlaybackState::PLAYING; PlaySongEvent e = { song }; EventEmitter::Emit<PlaySongEvent>(e); } else { m_state = PlaybackState::ERROR; } } // stops playing, resets play cursor void Stop(){ StopAudioStream(*m_pAudioStream); m_state = PlaybackState::STOPPED; ResetPlayTime(); ResetBuffers(); } // pause playing void Pause(){ PauseAudioStream(*m_pAudioStream); m_state = PlaybackState::PAUSED; } // plays next song in playlist void PlayNext(){ if(m_playlist.size() <= 1){ return; } else if(m_playlist.size() - 1 == (size_t)m_playlistIndex) { m_playlistIndex = 0; } else { ++m_playlistIndex; } if(m_state == PLAYING) Stop(); Play(); } // plays previous song in playlist void PlayPrev(){ if(m_playlist.size() <= 1){ return; } else if(m_playlistIndex == 0) { m_playlistIndex = m_playlist.size() - 1; } else { --m_playlistIndex; } if(m_state == PLAYING) Stop(); Play(); } // update playback volume void SetVolume(float value){ float minV = 0.0; float maxV = 1.0; m_volume = max(minV, min(value, maxV)); // only set if audio stream is valid // this means we must call SetVolume after we init the audio stream if(m_pAudioStream != nullptr){ SetAudioStreamVolume(*m_pAudioStream, value); } } ////////////////////////////// ////////////////////////////// /// Playlist Management ////////////////////////////// // return what state the player is in PlaybackState GetState(){ return m_state; } // adds songs to playlist void AddSongs(char** files, int count){ for(int i = 0; i < count; ++i){ // basic file name parse for now string path = files[i]; int offset = path.rfind("\\") + 1; // trim that .wav at the end, do a split on '.' l8r string fileName(path.substr(offset, path.length() - 4 - offset )); Song s = { fileName, // do more to find song name l8r nullptr, // and artist info so we can set this path }; m_playlist.push_back(s); } } // removes songs to playlist void RemoveSongByIndex(int index){ m_playlist.erase(m_playlist.begin() + index); } // void RemoveSong(Song& song){ // m_playlist.erase(remove(m_playlist.begin(), m_playlist.end(), [song](Song& s){ song.Filepath == s.Filepath;}), m_playlist.end()); // } ////////////////////////////// vector<string> GetSongNames(){ vector<string> v; for(auto i = 0; (size_t)i < m_playlist.size(); ++i){ v.push_back(m_playlist[i].Filepath); } return v; } protected: // audio stream obj AudioStream* m_pAudioStream = nullptr; // samping rate of audio float m_samplingRate; // samples per update int m_spu; // raw audio file data short* m_audioData = nullptr; // raw audio data buff size int m_audioDataSize; // audio data buffer for each update short* m_audioBuff = nullptr; // position of audio data reader int m_audioDataCursor = 0; // index of current song in playlist vec int m_playlistIndex = 0; // Song vector vector<Song> m_playlist; // loop control LoopState m_loopState = LoopState::PLAYLIST; // current state of player PlaybackState m_state = PlaybackState::STOPPED; // play time in seconds float m_playTime = 0; // audio analyzer used to calc DFT in real-time AudioAnalyzer m_audioAnalyzer; void ResetPlayTime(){ m_playTime = 0; } void ResetBuffers(){ delete [] m_audioData; delete [] m_audioBuff; m_audioData = nullptr; m_audioBuff = nullptr; m_audioDataSize = 0; m_audioDataCursor = 0; } ////////////////////////////// /// Event bindings ////////////////////////////// void BindEvents(){ EventEmitter::On<PlayClickEvent>([&](PlayClickEvent& e) { OnPlayClick(e); }); EventEmitter::On<PauseClickEvent>([&](PauseClickEvent& e) { OnPauseClick(e); }); EventEmitter::On<StopClickEvent>([&](StopClickEvent& e) { OnStopClick(e); }); EventEmitter::On<PlayNextClickEvent>([&](PlayNextClickEvent& e) { OnPlayNextClick(e); }); EventEmitter::On<PlayPrevClickEvent>([&](PlayPrevClickEvent& e) { OnPlayPrevClick(e); }); EventEmitter::On<VolumeUpdateEvent>([&](VolumeUpdateEvent& e) { OnVolumeUpdate(e); }); EventEmitter::On<GetVolumeEvent>([&](GetVolumeEvent& e) { OnGetVolume(e); }); EventEmitter::On<GetPlaybackStateEvent>([&](GetPlaybackStateEvent& e) { OnGetPlaybackState(e); }); EventEmitter::On<GetPlaylistEvent>([&](GetPlaylistEvent& e) { OnGetPlaylist(e); }); EventEmitter::On<RemoveSongByIndexEvent>([&](RemoveSongByIndexEvent& e) { OnRemoveSongByIndex(e); }); } // handle play btn click from UI void OnPlayClick(PlayClickEvent e){ Play(); } // handle pause btn click from UI void OnPauseClick(PauseClickEvent e){ Pause(); } // handle play btn click from UI void OnStopClick(StopClickEvent e){ Stop(); } // handle play next btn click from UI void OnPlayNextClick(PlayNextClickEvent e){ PlayNext(); } // handle play prev btn click from UI void OnPlayPrevClick(PlayPrevClickEvent e){ PlayPrev(); } // handle volume slider update from UI void OnVolumeUpdate(VolumeUpdateEvent e){ SetVolume(e.Value); } void OnGetVolume(GetVolumeEvent& e){ e.Value = m_volume; } void OnGetPlaybackState(GetPlaybackStateEvent& e){ e.State = m_state; } void OnGetPlaylist(GetPlaylistEvent& e){ e.Playlist = m_playlist;// might need to copy ish manually? } void OnRemoveSongByIndex(RemoveSongByIndexEvent& e){ RemoveSongByIndex(e.Index); } ////////////////////////////// private: float m_volume = 1.0; bool __you_cant_touch_this = true; }; } #endif // _SHADEPLAYER_INCLUDE_MUSICSTREAMPLAYER_HPP_
[ "me@sammyg.dev" ]
me@sammyg.dev
0a85f9a059ee1bea9af57c8796009d5e3202a8f0
8572fee131df532bd4e96e93ece6714a30d6ab4e
/Easy/Basic Logic/question728.cpp
c6e7c20a2d28f49be2e050cbcdb412c082490c5d
[]
no_license
akiljames83/Leetcode
c1262ca6351194b633f054e324c851cba236846a
c7ed619f831cb70529bc3a5a2c0c52577fcdcf56
refs/heads/master
2020-04-13T06:20:53.002618
2019-07-20T04:38:05
2019-07-20T04:38:05
163,017,814
3
1
null
null
null
null
UTF-8
C++
false
false
1,231
cpp
#include <cmath> auto __=[]() { std::ios::sync_with_stdio(false); cin.tie(nullptr); return nullptr; }(); class Solution { public: bool check(int original){ int num = original; int temp{num%10}; int itr = static_cast<int>(log10 (static_cast<double>(original))) + 2; while( itr-- != 0) { if ((temp == 0) || (original % temp)) return false; temp = num%10; num /= 10; } return true; } vector<int> selfDividingNumbers(int left, int right) { vector<int> ans; for(int i = left; i <= right; i++){ if (check(i)) ans.push_back(i); } return ans; } }; // Faster Solution: Same logic but implemented properly class Solution { public: bool check(int original){ int num = original; while( num != 0) { int temp{num%10}; if ((temp == 0) || (original % temp)) return false; num /= 10; } return true; } vector<int> selfDividingNumbers(int left, int right) { vector<int> ans; for(int i = left; i <= right; i++){ if (check(i)) ans.push_back(i); } return ans; } };
[ "akil.james83@gmail.com" ]
akil.james83@gmail.com
ae97c0c31a2707b398ddeea6903312b20f6e761e
9fa2b12bb08179bf574556fcb357c7b925549f3d
/Actividad3While1.cpp
00fc2e57198f81d5d4a0a473b03b68236cab85c0
[]
no_license
DavidGlezQ/C-C-codes
500db4302b902e4de8469ffd1062f922be8a783a
4eb75c007852e2ed8a2f95be5c8ba5f1cdbc8c87
refs/heads/master
2022-11-07T10:17:18.642930
2020-06-29T04:25:34
2020-06-29T04:25:34
267,651,209
0
0
null
null
null
null
UTF-8
C++
false
false
701
cpp
#include <iostream> #include <stdio.h> int main() { int i=0, b = 0, c = 0, num[30], prom = 0, mayor, min; printf("David Alejandro Gonzalez Quezada\n20110407\n"); printf("Actividad 3 con Sentencia While\n"); printf("**Ingresa tus 20 numeros a calcular**\n"); printf("Numeros: \n"); while (i <= 19){ scanf_s("%i", &num[i]); i++; } while (b <= 19) { prom = prom + num[b]; b++; } mayor = num[0]; min = num[0]; while (c <= 19){ if (num[c] < min) { min = num[c]; c++; } if (num[c] > mayor) { mayor = num[c]; } c++; } printf("La suma de tus numeros son: %i\n", prom); printf("El numero mayor es: %i\n", mayor); printf("El numero menor es: %i\n", min); return 0; }
[ "62410785+DavidGlezQ@users.noreply.github.com" ]
62410785+DavidGlezQ@users.noreply.github.com
ea6f92ddfd8d1e6eb178be46100ec5ab6e80675b
0c6aebacc3e5447d75a5256f96b98c166c9df4b5
/CPPPP/第九章/9_4_auto.cpp
ee4cee99b7c11308efba61310b8bab1604899898
[]
no_license
RaoXuntian/Learn_CPP
8c940484806ded25eca397890eff3395b9456883
1b5bca10028c09c730fe4ed3582f674a3c2ced38
refs/heads/master
2021-01-07T09:54:23.284374
2020-06-28T17:59:28
2020-06-28T17:59:28
241,656,040
0
0
null
null
null
null
UTF-8
C++
false
false
932
cpp
#include <iostream> using namespace std; void oil(int x); int main(int argc, char const *argv[]) { int texas = 31; int year = 1999; cout << "I'm main(), texas = " << texas << ", &texas = "; cout << &texas << endl; cout << "I'm main(), year = " << year << ", &year = "; cout << &year << endl; oil(texas); cout << "In main(), texas = " << texas << ", &texas = "; cout << &texas << endl; cout << "In main(), year = " << year << ", &year = "; cout << &year << endl; return 0; } void oil(int x) { int texas = 5; cout << "In oil(), texas = " << texas << ", &texas = "; cout << &texas << endl; cout << "In oil(), x = " << x << ", &x = "; cout << &x << endl; { int texas = 113; cout << "In block, texas = " << texas; cout << ", &texas = " << &texas << endl; cout << "In block, x = " << x << ", &x = "; cout << &x << endl; } cout << "Post-block texas = " << texas; cout << ", &texas = " << &texas << endl; }
[ "raoxuntian@gmail.com" ]
raoxuntian@gmail.com
0073957f0e2f85b05397fd2c78c19da795bf9e6d
f8e67b759f67b0c227bc9cbfde6bd20f91e4006a
/Source/Main.cpp
e1ab5c6e348b1108873b7f2e49379acc9146f6c6
[]
no_license
joe-robot/TapTempo
8f370ecae7d411726a7c8b32818205fce77032e8
ac096bb4f2994ab2e36adb327e9ca23e5e97788b
refs/heads/master
2022-06-19T06:03:45.370660
2020-05-12T21:26:25
2020-05-12T21:26:25
263,163,480
0
0
null
null
null
null
UTF-8
C++
false
false
3,781
cpp
/* ============================================================================== This file was auto-generated! It contains the basic startup code for a JUCE application. ============================================================================== */ #include <JuceHeader.h> #include "MainComponent.h" //============================================================================== class TapTempoApplication : public JUCEApplication { public: //============================================================================== TapTempoApplication() {} const String getApplicationName() override { return ProjectInfo::projectName; } const String getApplicationVersion() override { return ProjectInfo::versionString; } bool moreThanOneInstanceAllowed() override { return true; } //============================================================================== void initialise (const String& commandLine) override { // This method is where you should put your application's initialisation code.. mainWindow.reset (new MainWindow (getApplicationName())); } void shutdown() override { // Add your application's shutdown code here.. mainWindow = nullptr; // (deletes our window) } //============================================================================== void systemRequestedQuit() override { // This is called when the app is being asked to quit: you can ignore this // request and let the app carry on running, or call quit() to allow the app to close. quit(); } void anotherInstanceStarted (const String& commandLine) override { // When another instance of the app is launched while this one is running, // this method is invoked, and the commandLine parameter tells you what // the other instance's command-line arguments were. } //============================================================================== /* This class implements the desktop window that contains an instance of our MainComponent class. */ class MainWindow : public DocumentWindow { public: MainWindow (String name) : DocumentWindow (name, Colours::lightgrey, DocumentWindow::allButtons) { setUsingNativeTitleBar (true); setContentOwned (new MainComponent(), true); setFullScreen (true); // set to fullscreen rather than call centreWithSize() setVisible (true); } void closeButtonPressed() override { // This is called when the user tries to close this window. Here, we'll just // ask the app to quit when this happens, but you can change this to do // whatever you need. JUCEApplication::getInstance()->systemRequestedQuit(); } /* Note: Be careful if you override any DocumentWindow methods - the base class uses a lot of them, so by overriding you might break its functionality. It's best to do all your work in your content component instead, but if you really have to override any DocumentWindow methods, make sure your subclass also calls the superclass's method. */ private: JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MainWindow) }; private: std::unique_ptr<MainWindow> mainWindow; }; //============================================================================== // This macro generates the main() routine that launches the app. START_JUCE_APPLICATION (TapTempoApplication)
[ "josephcresswell@Josephs-MacBook-Pro-3.local" ]
josephcresswell@Josephs-MacBook-Pro-3.local
48104ec74bee3f76fe9425d00931f8682d4d90f3
a33aac97878b2cb15677be26e308cbc46e2862d2
/program_data/PKU_raw/2/520.c
b61c7ec18c4b86c6ee948c62c00b00d9a4f5b140
[]
no_license
GabeOchieng/ggnn.tensorflow
f5d7d0bca52258336fc12c9de6ae38223f28f786
7c62c0e8427bea6c8bec2cebf157b6f1ea70a213
refs/heads/master
2022-05-30T11:17:42.278048
2020-05-02T11:33:31
2020-05-02T11:33:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
685
c
struct book{ int num1; char au[27]; }bk[1000]; struct author{ char name; int a; int num2[1000]; }aur[27]; int main() { int n,i,j; struct author max; max.a=0; for(j=0;j<26;j++){ aur[j].name=65+j; aur[j].a=0; } scanf("%d",&n); for(i=0;i<n;i++){ scanf("%d %s",&bk[i].num1,bk[i].au); } //??????,????? for(i=0;i<n;i++){ for(j=0;bk[i].au[j]!='\0';j++){ aur[bk[i].au[j]-65].num2[aur[bk[i].au[j]-65].a]=bk[i].num1; aur[bk[i].au[j]-65].a++; } } //?????????? for(i=0;i<26;i++){ if(aur[i].a>max.a)max=aur[i]; } printf("%c\n%d\n",max.name,max.a); for(i=0;i<max.a;i++){ printf("%d\n",max.num2[i]); } return 0; }
[ "bdqnghi@gmail.com" ]
bdqnghi@gmail.com
6cfcec269ae4011a408f39f63ad02b5e2408bad9
cc3c367bf003e9d8d71e10aa14c6046ce70743b3
/opt/ir_loop_cvt.cpp
1510cad588a35cc0e77707e3d84d47a042ac246e
[ "BSD-3-Clause", "LicenseRef-scancode-generic-cla" ]
permissive
lusinga/xoc
7c0657cedaf8bcbd55597998c4dd948bb0a0c38b
f085f935deb0a82f1cfc2cb36222ee1d48ffeeb9
refs/heads/master
2020-05-13T05:19:59.009290
2019-02-10T12:26:22
2019-02-10T12:26:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,376
cpp
/*@ XOC Release License Copyright (c) 2013-2014, Alibaba Group, All rights reserved. compiler@aliexpress.com 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 Su Zhenyu 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 "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. author: Su Zhenyu @*/ #include "cominc.h" #include "prdf.h" #include "prssainfo.h" #include "ir_ssa.h" #include "ir_loop_cvt.h" namespace xoc { bool IR_LOOP_CVT::is_while_do(LI<IRBB> const* li, OUT IRBB ** gobackbb, UINT * succ1, UINT * succ2) { ASSERT0(gobackbb); IRBB * head = LI_loop_head(li); ASSERT0(head); *gobackbb = ::findSingleBackedgeStartBB(li, m_cfg); if (*gobackbb == NULL) { //loop may be too messy. return false; } if (BB_rpo(head) > BB_rpo(*gobackbb)) { //loop may already be do-while. return false; } IR * lastir = BB_last_ir(head); if (!lastir->isConditionalBr()) { return false; } bool f = findTwoSuccessorBBOfLoopHeader(li, m_cfg, succ1, succ2); if (!f) { return false; } if (li->isInsideLoop(*succ1) && li->isInsideLoop(*succ2)) { return false; } return true; } bool IR_LOOP_CVT::try_convert(LI<IRBB> * li, IRBB * gobackbb, UINT succ1, UINT succ2) { ASSERT0(gobackbb); IRBB * loopbody_start_bb; IRBB * epilog; if (li->isInsideLoop(succ1)) { ASSERT0(!li->isInsideLoop(succ2)); loopbody_start_bb = m_cfg->getBB(succ1); epilog = m_cfg->getBB(succ2); } else { ASSERT0(li->isInsideLoop(succ2)); ASSERT0(!li->isInsideLoop(succ1)); loopbody_start_bb = m_cfg->getBB(succ2); epilog = m_cfg->getBB(succ1); } ASSERT0(loopbody_start_bb && epilog); IRBB * next = m_cfg->getFallThroughBB(gobackbb); if (next == NULL || next != epilog) { //No benefit to be get to convert this kind of loop. return false; } xcom::C<IR*> * irct; IR * lastir = BB_irlist(gobackbb).get_tail(&irct); ASSERT0(lastir->is_goto()); IRBB * head = LI_loop_head(li); ASSERT0(head); //Copy ir in header to gobackbb. IR * last_cond_br = NULL; DUIter di = NULL; Vector<IR*> rmvec; for (IR * ir = BB_first_ir(head); ir != NULL; ir = BB_next_ir(head)) { IR * newir = m_ru->dupIRTree(ir); m_du->copyIRTreeDU(newir, ir, true); m_ii.clean(); for (IR * x = iterRhsInit(ir, m_ii); x != NULL; x = iterRhsNext(m_ii)) { if (!x->isMemoryRef()) { continue; } UINT cnt = 0; if (x->isReadPR() && PR_ssainfo(x) != NULL) { IR * def = SSA_def(PR_ssainfo(x)); if (def != NULL && li->isInsideLoop(BB_id(def->getBB()))) { rmvec.set(cnt++, def); } } else { DUSet const* defset = x->readDUSet(); if (defset == NULL) { continue; } for (INT d = defset->get_first(&di); d >= 0; d = defset->get_next(d, &di)) { IR * def = m_ru->getIR(d); ASSERT0(def->getBB()); if (li->isInsideLoop(BB_id(def->getBB()))) { rmvec.set(cnt++, def); } } } if (cnt != 0) { for (UINT i = 0; i < cnt; i++) { IR * d = rmvec.get(i); m_du->removeDUChain(d, x); } } } BB_irlist(gobackbb).insert_before(newir, irct); if (newir->isConditionalBr()) { ASSERT0(ir == BB_last_ir(head)); last_cond_br = newir; newir->invertIRType(m_ru); } } ASSERT0(last_cond_br); BB_irlist(gobackbb).remove(irct); m_ru->freeIR(lastir); m_cfg->removeEdge(gobackbb, head); //revise cfg. LabelInfo const* loopbody_start_lab = loopbody_start_bb->getLabelList().get_head(); if (loopbody_start_lab == NULL) { loopbody_start_lab = ::allocInternalLabel(m_ru->get_pool()); m_cfg->add_lab(loopbody_start_bb, loopbody_start_lab); } last_cond_br->setLabel(loopbody_start_lab); //Add back edge. m_cfg->addEdge(BB_id(gobackbb), BB_id(loopbody_start_bb)); //Add fallthrough edge. m_cfg->addEdge(BB_id(gobackbb), BB_id(next)); BB_is_fallthrough(next) = true; return true; } bool IR_LOOP_CVT::find_and_convert(List<LI<IRBB>*> & worklst) { bool change = false; while (worklst.get_elem_count() > 0) { LI<IRBB> * x = worklst.remove_head(); IRBB * gobackbb; UINT succ1; UINT succ2; if (is_while_do(x, &gobackbb, &succ1, &succ2)) { change |= try_convert(x, gobackbb, succ1, succ2); } x = LI_inner_list(x); while (x != NULL) { worklst.append_tail(x); x = LI_next(x); } } return change; } bool IR_LOOP_CVT::perform(OptCtx & oc) { START_TIMER(t, getPassName()); m_ru->checkValidAndRecompute(&oc, PASS_LOOP_INFO, PASS_RPO, PASS_UNDEF); LI<IRBB> * li = m_cfg->getLoopInfo(); if (li == NULL) { return false; } List<LI<IRBB>*> worklst; while (li != NULL) { worklst.append_tail(li); li = LI_next(li); } bool change = find_and_convert(worklst); if (change) { if (g_is_dump_after_pass) { dumpBBList(m_ru->getBBList(), m_ru); } //DU reference and du chain has maintained. ASSERT0(m_ru->verifyMDRef()); ASSERT0(m_du->verifyMDDUChain(COMPUTE_PR_DU | COMPUTE_NOPR_DU)); //All these changed. OC_is_reach_def_valid(oc) = false; OC_is_avail_reach_def_valid(oc) = false; OC_is_live_expr_valid(oc) = false; oc.set_flag_if_cfg_changed(); OC_is_cfg_valid(oc) = true; //Only cfg is avaiable. //TODO: make rpo, dom valid. } END_TIMER(t, getPassName()); return change; } } //namespace xoc
[ "steven.known@gmail.com" ]
steven.known@gmail.com
64c4b2476878efe376c0efcfe967837f06a101a5
45b32ffcdc7ac3864c0b810b61deeee136616554
/AutoUpdate/Extern/Win32++/samples/DockContainer/src/Text.cpp
037b6fcc5db244d539d0f310a04b5ec195ae64e1
[]
no_license
atom-chen/Tools-2
812071cf6ab3e5a22fb13e4ffdc896ac03de1c68
0c41e12bd7526d2e7bd3328b82f11ea1b4a93938
refs/heads/master
2020-11-29T10:05:24.253448
2017-07-12T06:05:17
2017-07-12T06:05:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,469
cpp
/////////////////////////////////////////////////// // Text.cpp - Definitions for the CViewText, // and CDockText classes #include "stdafx.h" #include "ContainerApp.h" #include "Text.h" #include "resource.h" /////////////////////////////////////////////// // CViewText functions CViewText::CViewText() { m_hRichEdit = ::LoadLibrary(_T("Riched20.dll")); // RichEdit ver 2.0 if (!m_hRichEdit) { ::MessageBox(NULL,_T("CRichView::CRichView Failed to load Riched20.dll"), _T(""), MB_ICONWARNING); } } CViewText::~CViewText(void) { // Free the DLL if (m_hRichEdit) ::FreeLibrary(m_hRichEdit); } void CViewText::OnInitialUpdate() { SetWindowText(_T("Text Edit Window\r\n\r\n You can type some text here ...")); } void CViewText::PreCreate(CREATESTRUCT &cs) { cs.style = ES_AUTOHSCROLL | ES_AUTOVSCROLL | ES_MULTILINE | WS_CHILD | WS_CLIPCHILDREN | WS_HSCROLL | WS_VISIBLE | WS_VSCROLL; cs.lpszClass = RICHEDIT_CLASS; // RichEdit ver 2.0 } ////////////////////////////////////////////// // Definitions for the CContainText class CContainText::CContainText() { SetDockCaption (_T("Text View - Docking container")); SetTabText(_T("Text")); SetTabIcon(IDI_TEXT); SetView(m_ViewText); } ////////////////////////////////////////////// // Definitions for the CDockText class CDockText::CDockText() { // Set the view window to our edit control SetView(m_View); // Set the width of the splitter bar SetBarWidth(8); }
[ "kuangben2010@yeah.net" ]
kuangben2010@yeah.net
1509f3853ba50f18ee4759ee0161f125cb5c99f2
51af83a3de50fcb6912b01a6d265807bf1f0dc88
/Domain/partitionmanager.hpp
285d271618d45ae289387842e8a976920a440f41
[ "MIT" ]
permissive
alanthie/Chess-001
08c3f9f9e6a3d071eb734b297e0290df25af2b6c
9c887fe062c99b7333c73b5867a5f56ff06fdcd9
refs/heads/master
2021-01-23T01:56:15.409217
2018-04-29T03:50:04
2018-04-29T03:50:04
92,897,858
1
1
null
null
null
null
UTF-8
C++
false
false
16,446
hpp
#pragma once //================================================================================================= // Copyright (C) 2017 Alain Lanthier - All Rights Reserved //================================================================================================= // // PartitionManger : Manage the multiple partitions // // #ifndef _AL_CHESS_DOMAIN_PARTITIONMANAGER_HPP #define _AL_CHESS_DOMAIN_PARTITIONMANAGER_HPP namespace chess { // PartitionManager template <typename PieceID, typename uint8_t _BoardSize, typename TYPE_PARAM, int PARAM_NBIT> class PartitionManager { using _Domain = Domain<PieceID, _BoardSize, TYPE_PARAM, PARAM_NBIT>; using _Partition = Partition<PieceID, _BoardSize, TYPE_PARAM, PARAM_NBIT>; using _PieceSet = PieceSet<PieceID, _BoardSize>; private: PartitionManager() {} PartitionManager(const PartitionManager&) = delete; PartitionManager & operator=(const PartitionManager &) = delete; PartitionManager(PartitionManager&&) = delete; public: ~PartitionManager() { if (_instance.operator bool()) { _partitions.clear(); _instance.release(); } } static const PartitionManager* instance(); public: _Partition* load_partition(const std::string& name) const; bool add_partition(_Partition* p)const; _Partition* find_partition(const std::string partition_name) const; void remove_partition(const std::string partition_name) const; bool make_classic_partition() const; // Exemple bool make_tb_partition(uint8_t maxNpiece) const; private: std::map<std::string, _Partition*> _partitions; // TODO std_unique<> ... static std::unique_ptr<PartitionManager> _instance; bool make_tb_domain_from_ps(std::string& partition_name, _PieceSet& ps, _Partition* p_tb) const; }; template <typename PieceID, typename uint8_t _BoardSize, typename TYPE_PARAM, int PARAM_NBIT> std::unique_ptr<PartitionManager<PieceID, _BoardSize, TYPE_PARAM, PARAM_NBIT>> PartitionManager<PieceID, _BoardSize, TYPE_PARAM, PARAM_NBIT>::_instance = nullptr; // make_classic_partition template <typename PieceID, typename uint8_t _BoardSize, typename TYPE_PARAM, int PARAM_NBIT> bool PartitionManager<PieceID, _BoardSize, TYPE_PARAM, PARAM_NBIT>::make_classic_partition() const { std::stringstream ss_partion_name; ss_partion_name << "classic" << std::to_string(_BoardSize); // Check if in memory _Partition* p_classic = PartitionManager::instance()->find_partition(ss_partion_name.str()); if (p_classic == nullptr) { _Partition* p = new _Partition(ss_partion_name.str()); if (!PartitionManager::instance()->add_partition(p)) { remove_partition(ss_partion_name.str()); return false; } // Try loading from disk if (p->load() == true) { return true; } else { // Continu to create it } } else { // Reload from disk if (p_classic->load() == false) { return false; } } // Check if in memory p_classic = PartitionManager::instance()->find_partition(ss_partion_name.str()); if (p_classic == nullptr) return false; // Create domains _Domain* dom_KK = new DomainKvK< PieceID, _BoardSize, TYPE_PARAM, PARAM_NBIT>(ss_partion_name.str()); _Domain* dom_KQvK = new DomainKQvK<PieceID, _BoardSize, TYPE_PARAM, PARAM_NBIT>(ss_partion_name.str()); if (!p_classic->add_domain(dom_KK)) return false; if (!p_classic->add_domain(dom_KQvK)) return false; // Just checking alternate method _Domain* ptr_dom_KQvK = p_classic->find_domain(_Domain::getDomainName(eDomainName::KQvK), "0"); if (ptr_dom_KQvK == nullptr) return false; _Domain* ptr_dom_KK = p_classic->find_domain(_Domain::getDomainName(eDomainName::KvK) , "0"); if (ptr_dom_KK == nullptr) return false; // set children relationship if (!ptr_dom_KQvK->add_child(ptr_dom_KK)) return false; ptr_dom_KQvK->save(); ptr_dom_KK->save(); p_classic->save(); return true; } // find_partition template <typename PieceID, typename uint8_t _BoardSize, typename TYPE_PARAM, int PARAM_NBIT> Partition<PieceID, _BoardSize, TYPE_PARAM, PARAM_NBIT>* PartitionManager<PieceID, _BoardSize, TYPE_PARAM, PARAM_NBIT>::find_partition(const std::string partition_name) const { if (_instance == nullptr) return nullptr; auto& iter = _instance->_partitions.find(partition_name); if (iter != _instance->_partitions.end()) { return (iter->second); } return nullptr; } // remove_partition template <typename PieceID, typename uint8_t _BoardSize, typename TYPE_PARAM, int PARAM_NBIT> void PartitionManager<PieceID, _BoardSize, TYPE_PARAM, PARAM_NBIT>::remove_partition(const std::string partition_name) const { if (_instance == nullptr) return; auto& iter = _instance->_partitions.find(partition_name); if (iter != _instance->_partitions.end()) { _instance->_partitions.erase(iter); } } // add_partition template <typename PieceID, typename uint8_t _BoardSize, typename TYPE_PARAM, int PARAM_NBIT> bool PartitionManager<PieceID, _BoardSize, TYPE_PARAM, PARAM_NBIT>::add_partition(_Partition* p) const { if (_instance == nullptr) return false; auto iter = _instance->_partitions.find(p->name()); if (iter == _instance->_partitions.end()) { _instance->_partitions.insert(std::pair<std::string, _Partition*>(p->name(), p)); return true; } return false; } // instance() template <typename PieceID, typename uint8_t _BoardSize, typename TYPE_PARAM, int PARAM_NBIT> const PartitionManager<PieceID, _BoardSize, TYPE_PARAM, PARAM_NBIT>* PartitionManager<PieceID, _BoardSize, TYPE_PARAM, PARAM_NBIT>::instance() { if (_instance == nullptr) { _instance = std::unique_ptr<PartitionManager>(new PartitionManager); return _instance.get(); } return _instance.get(); } // load_partition template <typename PieceID, typename uint8_t _BoardSize, typename TYPE_PARAM, int PARAM_NBIT> Partition<PieceID, _BoardSize, TYPE_PARAM, PARAM_NBIT> * PartitionManager<PieceID, _BoardSize, TYPE_PARAM, PARAM_NBIT>::load_partition(const std::string& name) const { // Check if in memory _Partition* pp = PartitionManager::instance()->find_partition(name); if (pp == nullptr) { _Partition* p = new _Partition(name); if (!PartitionManager::instance()->add_partition(p)) { remove_partition(name); delete p; return nullptr; } // Try loading from disk if (p->load() == true) return p; remove_partition(name); delete p; return nullptr; } else { // Reload from disk if (pp->load() == false) { return nullptr; } return pp; } return nullptr; } // make_tb_partition template <typename PieceID, typename uint8_t _BoardSize, typename TYPE_PARAM, int PARAM_NBIT> bool PartitionManager<PieceID, _BoardSize, TYPE_PARAM, PARAM_NBIT>::make_tb_partition(uint8_t maxNpiece) const { if (maxNpiece > 2 + 2 * _BoardSize) // only KP(N)vKP(M) for now (P promote to Q) { // cerr... return false; } std::stringstream ss_partion_name; ss_partion_name << "TB_N" << (int)maxNpiece << "_B" << std::to_string(_BoardSize); // Check if in memory _Partition* p_tb = PartitionManager::instance()->find_partition(ss_partion_name.str()); if (p_tb == nullptr) { _Partition* p = new _Partition(ss_partion_name.str(), PartitionType::lookup_PieceSet); if (!PartitionManager::instance()->add_partition(p)) { remove_partition(ss_partion_name.str()); return false; } // Try loading from disk if (p->load() == true) { return true; } else { // Continu to create it } } else { // Reload from disk if (p_tb->load() == false) { // cerr... return false; } } // Check if in memory p_tb = PartitionManager::instance()->find_partition(ss_partion_name.str()); if (p_tb == nullptr) { // cerr... return false; } // Create domains // pieceset (nw >= nb) gives all childs - Only doing pawn/queen for now // 2: KK // N: KP(N-2)K, KP(N-3)KP(1), KP(N-4)KP(2), ... while[(n-i) >= i] std::vector<_Domain*> v_dom; std::vector<PieceID> white_piece_set; std::vector<PieceID> black_piece_set; std::vector<std::pair<PieceID, uint8_t>> v_white_piece; std::vector<std::pair<PieceID, uint8_t>> v_black_piece; for (uint8_t N = 2; N <= maxNpiece; N++) { for (uint8_t i = 0; i < _BoardSize; i++) // P white { for (uint8_t j = 0; j < _BoardSize; j++) // P black { if ( ((2 + i + j) == N) && (i >= j) ) { v_dom.clear(); white_piece_set.clear(); black_piece_set.clear(); v_white_piece.clear(); v_black_piece.clear(); white_piece_set.push_back(_Piece::get_id(PieceName::K, PieceColor::W)); black_piece_set.push_back(_Piece::get_id(PieceName::K, PieceColor::B)); for (uint8_t z = 0; z < i; z++) { white_piece_set.push_back(_Piece::get_id(PieceName::P, PieceColor::W)); } for (uint8_t z = 0; z < j; z++) { black_piece_set.push_back(_Piece::get_id(PieceName::P, PieceColor::B)); } v_white_piece = _PieceSet::to_set(white_piece_set); v_black_piece = _PieceSet::to_set(black_piece_set); _PieceSet ps(v_white_piece, v_black_piece); make_tb_domain_from_ps(ss_partion_name.str(), ps, p_tb); // recursion } } } } if (!p_tb->save()) { //... assert(false); } return true; } // make_tb_domain_from_ps template <typename PieceID, typename uint8_t _BoardSize, typename TYPE_PARAM, int PARAM_NBIT> bool PartitionManager<PieceID, _BoardSize, TYPE_PARAM, PARAM_NBIT>::make_tb_domain_from_ps(std::string& partition_name, _PieceSet& ps, _Partition* p_tb) const { std::vector<_Domain*> v_dom; uint16_t nw; uint16_t nb; uint16_t nwK; uint16_t nbK; nw = ps.count_all_piece(PieceColor::W); nb = ps.count_all_piece(PieceColor::B); nwK = ps.count_one_piecename(PieceColor::W, PieceName::K); nbK = ps.count_one_piecename(PieceColor::B, PieceName::K); PieceSet<PieceID, _BoardSize> copy(ps.wset(), ps.bset()); PieceSet<PieceID, _BoardSize> ps_sym({ PieceSet<PieceID, _BoardSize>::reverse_color_set(copy.bset()), PieceSet<PieceID, _BoardSize>::reverse_color_set(copy.wset()) }); bool is_sym = false; if ( (nw < nb) && (nw > 0) && (nb > 0) && (nbK > 0) && (nwK > 0)) { is_sym = true; } else if ((nb == 0) || (nbK == 0) || (nw == 0) || (nwK == 0)) { ps.collapse_to_one_piece(); } else { } { _Domain* ptr_dom_parent; if (!is_sym) { ptr_dom_parent = p_tb->find_domain(ps.name(PieceColor::none), "0"); if (ptr_dom_parent == nullptr) { ptr_dom_parent = new DomainTB< PieceID, _BoardSize, TYPE_PARAM, PARAM_NBIT>(partition_name, ps); v_dom.push_back(ptr_dom_parent); p_tb->add_domain(ptr_dom_parent); } } else { ptr_dom_parent = p_tb->find_domain(ps_sym.name(PieceColor::none), "0"); if (ptr_dom_parent == nullptr) { ptr_dom_parent = new DomainTB< PieceID, _BoardSize, TYPE_PARAM, PARAM_NBIT>(partition_name, ps_sym); v_dom.push_back(ptr_dom_parent); p_tb->add_domain(ptr_dom_parent); } } // using make_all_child_TBH std::vector<STRUCT_TBH<PieceID, _BoardSize>> _tb_children_info; if (!is_sym) _tb_children_info = TB_Manager<PieceID, _BoardSize>::instance()->make_all_child_TBH(ps, TBH_IO_MODE::tb_hiearchy, TBH_OPTION::none); else _tb_children_info = TB_Manager<PieceID, _BoardSize>::instance()->make_all_child_TBH(ps_sym, TBH_IO_MODE::tb_hiearchy, TBH_OPTION::none); for (size_t z = 0; z < _tb_children_info.size(); z++) { nw = _tb_children_info[z]._ps.count_all_piece(PieceColor::W); nb = _tb_children_info[z]._ps.count_all_piece(PieceColor::B); nwK = _tb_children_info[z]._ps.count_one_piecename(PieceColor::W, PieceName::K); nbK = _tb_children_info[z]._ps.count_one_piecename(PieceColor::B, PieceName::K); if ((nb == 0) || (nbK == 0) || (nw == 0) || (nwK == 0) || (nw >= nb)) { make_tb_domain_from_ps(partition_name, _tb_children_info[z]._ps, p_tb); _Domain* ptr_dom = p_tb->find_domain(_tb_children_info[z]._ps.name(PieceColor::none), "0"); if (ptr_dom == nullptr) { ptr_dom = new DomainTB< PieceID, _BoardSize, TYPE_PARAM, PARAM_NBIT>(partition_name, _tb_children_info[z]._ps); v_dom.push_back(ptr_dom); p_tb->add_domain(ptr_dom); } ptr_dom_parent->add_child(ptr_dom); // link } else if ((nw < nb) && (nw > 0) && (nb > 0) && (nbK > 0) && (nwK > 0)) { // sym PieceSet<PieceID, _BoardSize> copy(_tb_children_info[z]._ps.wset(), _tb_children_info[z]._ps.bset()); PieceSet<PieceID, _BoardSize> ps_sym({ PieceSet<PieceID, _BoardSize>::reverse_color_set(copy.bset()), PieceSet<PieceID, _BoardSize>::reverse_color_set(copy.wset()) }); make_tb_domain_from_ps(partition_name, ps_sym, p_tb); _Domain* ptr_dom = p_tb->find_domain(ps_sym.name(PieceColor::none), "0"); if (ptr_dom == nullptr) { ptr_dom = new DomainTB< PieceID, _BoardSize, TYPE_PARAM, PARAM_NBIT>(partition_name, ps_sym); v_dom.push_back(ptr_dom); p_tb->add_domain(ptr_dom); } ptr_dom_parent->add_child(ptr_dom); // link } } for (size_t z = 0; z < v_dom.size(); z++) { v_dom[z]->save(); } } return true; } }; #endif
[ "alanthier001@hotmail.ca" ]
alanthier001@hotmail.ca
ece3b2d31629fb0a9e30eab9143638c0611c4428
402585b19a08b98e78bc9e3cf8d74c5fbe654a8f
/tests2/fn_eigs_gen.cpp
1061d557a2e6a63574d99e021774497035331592
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
ashgen/armadillo
da5a3e415cd41bd79a82191cfe34d475740a40a8
fa56977f7f1af62d193bdb750147875385d36c00
refs/heads/master
2023-04-14T00:35:29.323480
2023-03-26T06:41:28
2023-03-26T06:41:28
418,338,657
0
0
null
null
null
null
UTF-8
C++
false
false
65,180
cpp
// SPDX-License-Identifier: Apache-2.0 // // Copyright 2011-2017 Ryan Curtin (http://www.ratml.org/) // Copyright 2017 National ICT Australia (NICTA) // // 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 <armadillo> #include "catch.hpp" using namespace arma; TEST_CASE("fn_eigs_gen_odd_test") { const uword n_rows = 10; const uword n_eigval = 5; const uword n_trials = 10; uword count = 0; for(uword trial=0; trial < n_trials; ++trial) { sp_mat m; m.sprandu(n_rows, n_rows, 0.3); mat d(m); // Eigendecompose, getting first 5 eigenvectors. Col<cx_double> sp_eigval; Mat<cx_double> sp_eigvec; const bool status_sparse = eigs_gen(sp_eigval, sp_eigvec, m, n_eigval); // Do the same for the dense case. Col<cx_double> eigval; Mat<cx_double> eigvec; const bool status_dense = eig_gen(eigval, eigvec, d); if( (status_sparse == false) || (status_dense == false) ) { continue; } else { ++count; } uvec used(n_rows, fill::zeros); for(uword i=0; i < n_eigval; ++i) { // Sorting these is difficult. // Find which one is the likely dense eigenvalue. uword dense_eval = n_rows + 1; for(uword k = 0; k < n_rows; ++k) { if ((std::abs(cx_double(sp_eigval(i)).real() - eigval(k).real()) < 1e-4) && (std::abs(cx_double(sp_eigval(i)).imag() - eigval(k).imag()) < 1e-4) && (used(k) == 0)) { dense_eval = k; used(k) = 1; break; } } REQUIRE( dense_eval != n_rows + 1 ); REQUIRE( std::abs(sp_eigval(i)) == Approx(std::abs(eigval(dense_eval))).margin(0.1) ); for(uword j = 0; j < n_rows; ++j) { REQUIRE( std::abs(sp_eigvec(j, i)) == Approx(std::abs(eigvec(j, dense_eval))).margin(0.1) ); } } } REQUIRE(count > 0); } TEST_CASE("fn_eigs_gen_even_test") { const uword n_rows = 10; const uword n_eigval = 4; const uword n_trials = 10; uword count = 0; for(uword trial=0; trial < n_trials; ++trial) { sp_mat m; m.sprandu(n_rows, n_rows, 0.3); sp_mat z(5, 5); z.sprandu(5, 5, 0.5); m.submat(2, 2, 6, 6) += 5 * z; mat d(m); // Eigendecompose, getting first 4 eigenvectors. Col<cx_double> sp_eigval; Mat<cx_double> sp_eigvec; const bool status_sparse = eigs_gen(sp_eigval, sp_eigvec, m, n_eigval); // Do the same for the dense case. Col<cx_double> eigval; Mat<cx_double> eigvec; const bool status_dense = eig_gen(eigval, eigvec, d); if( (status_sparse == false) || (status_dense == false) ) { continue; } else { ++count; } uvec used(n_rows, fill::zeros); for(uword i=0; i < n_eigval; ++i) { // Sorting these is difficult. // Find which one is the likely dense eigenvalue. uword dense_eval = n_rows + 1; for(uword k = 0; k < n_rows; ++k) { if ((std::abs(cx_double(sp_eigval(i)).real() - eigval(k).real()) < 1e-4) && (std::abs(cx_double(sp_eigval(i)).imag() - eigval(k).imag()) < 1e-4) && (used(k) == 0)) { dense_eval = k; used(k) = 1; break; } } REQUIRE( dense_eval != n_rows + 1 ); REQUIRE( std::abs(sp_eigval(i)) == Approx(std::abs(eigval(dense_eval))).margin(0.01) ); for(uword j = 0; j < n_rows; ++j) { REQUIRE( std::abs(sp_eigvec(j, i)) == Approx(std::abs(eigvec(j, dense_eval))).margin(0.01) ); } } } REQUIRE(count > 0); } TEST_CASE("fn_eigs_gen_even_opts_test") { const uword n_rows = 10; const uword n_eigval = 4; const uword n_trials = 10; uword count = 0; for(uword trial=0; trial < n_trials; ++trial) { sp_mat m; m.sprandu(n_rows, n_rows, 0.3); sp_mat z(5, 5); z.sprandu(5, 5, 0.5); m.submat(2, 2, 6, 6) += 5 * z; mat d(m); // Eigendecompose, getting first 4 eigenvectors. Col<cx_double> sp_eigval; Mat<cx_double> sp_eigvec; eigs_opts opts{}; opts.maxiter = 10000; opts.tol = 1e-12; const bool status_sparse = eigs_gen(sp_eigval, sp_eigvec, m, n_eigval, "lm", opts); // Do the same for the dense case. Col<cx_double> eigval; Mat<cx_double> eigvec; const bool status_dense = eig_gen(eigval, eigvec, d); if( (status_sparse == false) || (status_dense == false) ) { continue; } else { ++count; } uvec used(n_rows, fill::zeros); for(uword i=0; i < n_eigval; ++i) { // Sorting these is difficult. // Find which one is the likely dense eigenvalue. uword dense_eval = n_rows + 1; for(uword k = 0; k < n_rows; ++k) { if ((std::abs(cx_double(sp_eigval(i)).real() - eigval(k).real()) < 1e-4) && (std::abs(cx_double(sp_eigval(i)).imag() - eigval(k).imag()) < 1e-4) && (used(k) == 0)) { dense_eval = k; used(k) = 1; break; } } REQUIRE( dense_eval != n_rows + 1 ); REQUIRE( std::abs(sp_eigval(i)) == Approx(std::abs(eigval(dense_eval))).margin(0.01) ); for(uword j = 0; j < n_rows; ++j) { REQUIRE( std::abs(sp_eigvec(j, i)) == Approx(std::abs(eigvec(j, dense_eval))).margin(0.01) ); } } } REQUIRE(count > 0); } TEST_CASE("fn_eigs_gen_odd_sigma_test") { const uword n_rows = 10; const uword n_eigval = 5; const double sigma = 1.0; const uword n_trials = 10; uword count = 0; for(uword trial=0; trial < n_trials; ++trial) { sp_mat m; m.sprandu(n_rows, n_rows, 0.3); sp_mat z(5, 5); z.sprandu(5, 5, 0.5); m.submat(2, 2, 6, 6) += 5 * z; m += (sigma+0.001)*speye(n_rows, n_rows); mat d(m); // Eigendecompose, getting first 5 eigenvectors around 1. Col<cx_double> sp_eigval; Mat<cx_double> sp_eigvec; const bool status_sparse = eigs_gen(sp_eigval, sp_eigvec, m, n_eigval, sigma); // Do the same for the dense case. Col<cx_double> eigval; Mat<cx_double> eigvec; const bool status_dense = eig_gen(eigval, eigvec, d); if( (status_sparse == false) || (status_dense == false) ) { continue; } else { ++count; } uvec used(n_rows, fill::zeros); for(uword i=0; i < n_eigval; ++i) { // Sorting these is difficult. // Find which one is the likely dense eigenvalue. uword dense_eval = n_rows + 1; for(uword k = 0; k < n_rows; ++k) { if ((std::abs(cx_double(sp_eigval(i)).real() - eigval(k).real()) < 1e-4) && (std::abs(cx_double(sp_eigval(i)).imag() - eigval(k).imag()) < 1e-4) && (used(k) == 0)) { dense_eval = k; used(k) = 1; break; } } REQUIRE( dense_eval != n_rows + 1 ); REQUIRE( std::abs(sp_eigval(i)) == Approx(std::abs(eigval(dense_eval))).margin(0.1) ); for(uword j = 0; j < n_rows; ++j) { REQUIRE( std::abs(sp_eigvec(j, i)) == Approx(std::abs(eigvec(j, dense_eval))).margin(0.1) ); } } } REQUIRE(count > 0); } TEST_CASE("fn_eigs_gen_even_sigma_test") { const uword n_rows = 10; const uword n_eigval = 4; const double sigma = 1.0; const uword n_trials = 10; uword count = 0; for(uword trial=0; trial < n_trials; ++trial) { sp_mat m; m.sprandu(n_rows, n_rows, 0.3); sp_mat z(5, 5); z.sprandu(5, 5, 0.5); m.submat(2, 2, 6, 6) += 5 * z; m += (sigma+0.001)*speye(n_rows, n_rows); mat d(m); // Eigendecompose, getting first 4 eigenvectors around 1. Col<cx_double> sp_eigval; Mat<cx_double> sp_eigvec; const bool status_sparse = eigs_gen(sp_eigval, sp_eigvec, m, n_eigval, sigma); // Do the same for the dense case. Col<cx_double> eigval; Mat<cx_double> eigvec; const bool status_dense = eig_gen(eigval, eigvec, d); if( (status_sparse == false) || (status_dense == false) ) { continue; } else { ++count; } uvec used(n_rows, fill::zeros); for(uword i=0; i < n_eigval; ++i) { // Sorting these is difficult. // Find which one is the likely dense eigenvalue. uword dense_eval = n_rows + 1; for(uword k = 0; k < n_rows; ++k) { if ((std::abs(cx_double(sp_eigval(i)).real() - eigval(k).real()) < 1e-4) && (std::abs(cx_double(sp_eigval(i)).imag() - eigval(k).imag()) < 1e-4) && (used(k) == 0)) { dense_eval = k; used(k) = 1; break; } } REQUIRE( dense_eval != n_rows + 1 ); REQUIRE( std::abs(sp_eigval(i)) == Approx(std::abs(eigval(dense_eval))).margin(0.01) ); for(uword j = 0; j < n_rows; ++j) { REQUIRE( std::abs(sp_eigvec(j, i)) == Approx(std::abs(eigvec(j, dense_eval))).margin(0.01) ); } } } REQUIRE(count > 0); } TEST_CASE("fn_eigs_gen_even_sigma_opts_test") { const uword n_rows = 10; const uword n_eigval = 4; const double sigma = 1.0; const uword n_trials = 10; uword count = 0; for(uword trial=0; trial < n_trials; ++trial) { sp_mat m; m.sprandu(n_rows, n_rows, 0.3); sp_mat z(5, 5); z.sprandu(5, 5, 0.5); m.submat(2, 2, 6, 6) += 5 * z; m += (sigma+0.001)*speye(n_rows, n_rows); mat d(m); // Eigendecompose, getting first 4 eigenvectors around 1. Col<cx_double> sp_eigval; Mat<cx_double> sp_eigvec; eigs_opts opts{}; opts.maxiter = 10000; opts.tol = 1e-12; const bool status_sparse = eigs_gen(sp_eigval, sp_eigvec, m, n_eigval, sigma, opts); // Do the same for the dense case. Col<cx_double> eigval; Mat<cx_double> eigvec; const bool status_dense = eig_gen(eigval, eigvec, d); if( (status_sparse == false) || (status_dense == false) ) { continue; } else { ++count; } uvec used(n_rows, fill::zeros); for(uword i=0; i < n_eigval; ++i) { // Sorting these is difficult. // Find which one is the likely dense eigenvalue. uword dense_eval = n_rows + 1; for(uword k = 0; k < n_rows; ++k) { if ((std::abs(cx_double(sp_eigval(i)).real() - eigval(k).real()) < 1e-4) && (std::abs(cx_double(sp_eigval(i)).imag() - eigval(k).imag()) < 1e-4) && (used(k) == 0)) { dense_eval = k; used(k) = 1; break; } } REQUIRE( dense_eval != n_rows + 1 ); REQUIRE( std::abs(sp_eigval(i)) == Approx(std::abs(eigval(dense_eval))).margin(0.01) ); for(uword j = 0; j < n_rows; ++j) { REQUIRE( std::abs(sp_eigvec(j, i)) == Approx(std::abs(eigvec(j, dense_eval))).margin(0.01) ); } } } REQUIRE(count > 0); } TEST_CASE("fn_eigs_gen_odd_sm_test") { const uword n_rows = 10; const uword n_eigval = 5; const uword n_trials = 10; uword count = 0; for(uword trial=0; trial < n_trials; ++trial) { sp_mat m; m.sprandu(n_rows, n_rows, 0.3); sp_mat z(5, 5); z.sprandu(5, 5, 0.5); m.submat(2, 2, 6, 6) += 5 * z; m += 0.001*speye(n_rows, n_rows); mat d(m); // Eigendecompose, getting first 5 eigenvectors. Col<cx_double> sp_eigval; Mat<cx_double> sp_eigvec; const bool status_sparse = eigs_gen(sp_eigval, sp_eigvec, m, n_eigval, "sm"); // Do the same for the dense case. Col<cx_double> eigval; Mat<cx_double> eigvec; const bool status_dense = eig_gen(eigval, eigvec, d); if( (status_sparse == false) || (status_dense == false) ) { continue; } else { ++count; } uvec used(n_rows, fill::zeros); for(uword i=0; i < n_eigval; ++i) { // Sorting these is difficult. // Find which one is the likely dense eigenvalue. uword dense_eval = n_rows + 1; for(uword k = 0; k < n_rows; ++k) { if ((std::abs(cx_double(sp_eigval(i)).real() - eigval(k).real()) < 1e-4) && (std::abs(cx_double(sp_eigval(i)).imag() - eigval(k).imag()) < 1e-4) && (used(k) == 0)) { dense_eval = k; used(k) = 1; break; } } REQUIRE( dense_eval != n_rows + 1 ); REQUIRE( std::abs(sp_eigval(i)) == Approx(std::abs(eigval(dense_eval))).margin(0.1) ); for(uword j = 0; j < n_rows; ++j) { REQUIRE( std::abs(sp_eigvec(j, i)) == Approx(std::abs(eigvec(j, dense_eval))).margin(0.1) ); } } } REQUIRE(count > 0); } TEST_CASE("fn_eigs_gen_even_sm_test") { const uword n_rows = 10; const uword n_eigval = 4; const uword n_trials = 10; uword count = 0; for(uword trial=0; trial < n_trials; ++trial) { sp_mat m; m.sprandu(n_rows, n_rows, 0.3); sp_mat z(5, 5); z.sprandu(5, 5, 0.5); m.submat(2, 2, 6, 6) += 5 * z; m += 0.001*speye(n_rows, n_rows); mat d(m); // Eigendecompose, getting first 4 eigenvectors. Col<cx_double> sp_eigval; Mat<cx_double> sp_eigvec; const bool status_sparse = eigs_gen(sp_eigval, sp_eigvec, m, n_eigval, "sm"); // Do the same for the dense case. Col<cx_double> eigval; Mat<cx_double> eigvec; const bool status_dense = eig_gen(eigval, eigvec, d); if( (status_sparse == false) || (status_dense == false) ) { continue; } else { ++count; } uvec used(n_rows, fill::zeros); for(uword i=0; i < n_eigval; ++i) { // Sorting these is difficult. // Find which one is the likely dense eigenvalue. uword dense_eval = n_rows + 1; for(uword k = 0; k < n_rows; ++k) { if ((std::abs(cx_double(sp_eigval(i)).real() - eigval(k).real()) < 1e-4) && (std::abs(cx_double(sp_eigval(i)).imag() - eigval(k).imag()) < 1e-4) && (used(k) == 0)) { dense_eval = k; used(k) = 1; break; } } REQUIRE( dense_eval != n_rows + 1 ); REQUIRE( std::abs(sp_eigval(i)) == Approx(std::abs(eigval(dense_eval))).margin(0.01) ); for(uword j = 0; j < n_rows; ++j) { REQUIRE( std::abs(sp_eigvec(j, i)) == Approx(std::abs(eigvec(j, dense_eval))).margin(0.01) ); } } } REQUIRE(count > 0); } TEST_CASE("fn_eigs_gen_even_sm_opts_test") { const uword n_rows = 10; const uword n_eigval = 4; const uword n_trials = 10; uword count = 0; for(uword trial=0; trial < n_trials; ++trial) { sp_mat m; m.sprandu(n_rows, n_rows, 0.3); sp_mat z(5, 5); z.sprandu(5, 5, 0.5); m.submat(2, 2, 6, 6) += 5 * z; m += 0.001*speye(n_rows, n_rows); mat d(m); // Eigendecompose, getting first 4 eigenvectors. Col<cx_double> sp_eigval; Mat<cx_double> sp_eigvec; eigs_opts opts{}; opts.maxiter = 10000; opts.tol = 1e-12; const bool status_sparse = eigs_gen(sp_eigval, sp_eigvec, m, n_eigval, "sm", opts); // Do the same for the dense case. Col<cx_double> eigval; Mat<cx_double> eigvec; const bool status_dense = eig_gen(eigval, eigvec, d); if( (status_sparse == false) || (status_dense == false) ) { continue; } else { ++count; } uvec used(n_rows, fill::zeros); for(uword i=0; i < n_eigval; ++i) { // Sorting these is difficult. // Find which one is the likely dense eigenvalue. uword dense_eval = n_rows + 1; for(uword k = 0; k < n_rows; ++k) { if ((std::abs(cx_double(sp_eigval(i)).real() - eigval(k).real()) < 1e-4) && (std::abs(cx_double(sp_eigval(i)).imag() - eigval(k).imag()) < 1e-4) && (used(k) == 0)) { dense_eval = k; used(k) = 1; break; } } REQUIRE( dense_eval != n_rows + 1 ); REQUIRE( std::abs(sp_eigval(i)) == Approx(std::abs(eigval(dense_eval))).margin(0.01) ); for(uword j = 0; j < n_rows; ++j) { REQUIRE( std::abs(sp_eigvec(j, i)) == Approx(std::abs(eigvec(j, dense_eval))).margin(0.01) ); } } } REQUIRE(count > 0); } TEST_CASE("fn_eigs_gen_odd_float_test") { const uword n_rows = 10; const uword n_eigval = 5; const uword n_trials = 10; uword count = 0; for(uword trial=0; trial < n_trials; ++trial) { SpMat<float> m; m.sprandu(n_rows, n_rows, 0.3); for(uword i = 0; i < n_rows; ++i) { m(i, i) += 5 * double(i) / double(n_rows); } Mat<float> d(m); // Eigendecompose, getting first 5 eigenvectors. Col<cx_float> sp_eigval; Mat<cx_float> sp_eigvec; const bool status_sparse = eigs_gen(sp_eigval, sp_eigvec, m, n_eigval); // Do the same for the dense case. Col<cx_float> eigval; Mat<cx_float> eigvec; const bool status_dense = eig_gen(eigval, eigvec, d); if( (status_sparse == false) || (status_dense == false) ) { continue; } else { ++count; } uvec used(n_rows, fill::zeros); for(uword i=0; i < n_eigval; ++i) { // Sorting these is difficult. // Find which one is the likely dense eigenvalue. uword dense_eval = n_rows + 1; for(uword k = 0; k < n_rows; ++k) { if ((std::abs(cx_float(sp_eigval(i)).real() - eigval(k).real()) < 0.001) && (std::abs(cx_float(sp_eigval(i)).imag() - eigval(k).imag()) < 0.001) && (used(k) == 0)) { dense_eval = k; used(k) = 1; break; } } REQUIRE( dense_eval != n_rows + 1 ); REQUIRE( std::abs(sp_eigval(i)) == Approx(std::abs(eigval(dense_eval))).margin(0.001) ); for(uword j = 0; j < n_rows; ++j) { REQUIRE( std::abs(sp_eigvec(j, i)) == Approx(std::abs(eigvec(j, dense_eval))).margin(0.01) ); } } } REQUIRE(count > 0); } TEST_CASE("fn_eigs_gen_even_float_test") { const uword n_rows = 12; const uword n_eigval = 8; const uword n_trials = 10; uword count = 0; for(uword trial=0; trial < n_trials; ++trial) { SpMat<float> m; m.sprandu(n_rows, n_rows, 0.3); for(uword i = 0; i < n_rows; ++i) { m(i, i) += 5 * double(i) / double(n_rows); } Mat<float> d(m); // Eigendecompose, getting first 8 eigenvectors. Col<cx_float> sp_eigval; Mat<cx_float> sp_eigvec; const bool status_sparse = eigs_gen(sp_eigval, sp_eigvec, m, n_eigval); // Do the same for the dense case. Col<cx_float> eigval; Mat<cx_float> eigvec; const bool status_dense = eig_gen(eigval, eigvec, d); if( (status_sparse == false) || (status_dense == false) ) { continue; } else { ++count; } uvec used(n_rows, fill::zeros); for(uword i=0; i < n_eigval; ++i) { // Sorting these is difficult. // Find which one is the likely dense eigenvalue. uword dense_eval = n_rows + 1; for(uword k = 0; k < n_rows; ++k) { if ((std::abs(cx_float(sp_eigval(i)).real() - eigval(k).real()) < 0.001) && (std::abs(cx_float(sp_eigval(i)).imag() - eigval(k).imag()) < 0.001) && (used(k) == 0)) { dense_eval = k; used(k) = 1; break; } } REQUIRE( dense_eval != n_rows + 1 ); REQUIRE( std::abs(sp_eigval(i)) == Approx(std::abs(eigval(dense_eval))).margin(0.01) ); for(uword j = 0; j < n_rows; ++j) { REQUIRE( std::abs(sp_eigvec(j, i)) == Approx(std::abs(eigvec(j, dense_eval))).margin(0.01) ); } } } REQUIRE(count > 0); } TEST_CASE("fn_eigs_gen_even_float_opts_test") { const uword n_rows = 12; const uword n_eigval = 8; const uword n_trials = 10; uword count = 0; for(uword trial=0; trial < n_trials; ++trial) { SpMat<float> m; m.sprandu(n_rows, n_rows, 0.3); for(uword i = 0; i < n_rows; ++i) { m(i, i) += 5 * double(i) / double(n_rows); } Mat<float> d(m); // Eigendecompose, getting first 8 eigenvectors. Col<cx_float> sp_eigval; Mat<cx_float> sp_eigvec; eigs_opts opts{}; opts.maxiter = 10000; opts.tol = 1e-12; const bool status_sparse = eigs_gen(sp_eigval, sp_eigvec, m, n_eigval, "lm", opts); // Do the same for the dense case. Col<cx_float> eigval; Mat<cx_float> eigvec; const bool status_dense = eig_gen(eigval, eigvec, d); if( (status_sparse == false) || (status_dense == false) ) { continue; } else { ++count; } uvec used(n_rows, fill::zeros); for(uword i=0; i < n_eigval; ++i) { // Sorting these is difficult. // Find which one is the likely dense eigenvalue. uword dense_eval = n_rows + 1; for(uword k = 0; k < n_rows; ++k) { if ((std::abs(cx_float(sp_eigval(i)).real() - eigval(k).real()) < 0.001) && (std::abs(cx_float(sp_eigval(i)).imag() - eigval(k).imag()) < 0.001) && (used(k) == 0)) { dense_eval = k; used(k) = 1; break; } } REQUIRE( dense_eval != n_rows + 1 ); REQUIRE( std::abs(sp_eigval(i)) == Approx(std::abs(eigval(dense_eval))).margin(0.01) ); for(uword j = 0; j < n_rows; ++j) { REQUIRE( std::abs(sp_eigvec(j, i)) == Approx(std::abs(eigvec(j, dense_eval))).margin(0.01) ); } } } REQUIRE(count > 0); } TEST_CASE("fn_eigs_gen_odd_float_sigma_test") { const uword n_rows = 10; const uword n_eigval = 5; const float sigma = 1.0; const uword n_trials = 10; uword count = 0; for(uword trial=0; trial < n_trials; ++trial) { SpMat<float> m; m.sprandu(n_rows, n_rows, 0.3); for(uword i = 0; i < n_rows; ++i) { m(i, i) += 5 * double(i) / double(n_rows); } m += (sigma+0.001)*speye<SpMat<float>>(n_rows, n_rows); Mat<float> d(m); // Eigendecompose, getting first 5 eigenvectors around 1. Col<cx_float> sp_eigval; Mat<cx_float> sp_eigvec; const bool status_sparse = eigs_gen(sp_eigval, sp_eigvec, m, n_eigval, sigma); // Do the same for the dense case. Col<cx_float> eigval; Mat<cx_float> eigvec; const bool status_dense = eig_gen(eigval, eigvec, d); if( (status_sparse == false) || (status_dense == false) ) { continue; } else { ++count; } uvec used(n_rows, fill::zeros); for(uword i=0; i < n_eigval; ++i) { // Sorting these is difficult. // Find which one is the likely dense eigenvalue. uword dense_eval = n_rows + 1; for(uword k = 0; k < n_rows; ++k) { if ((std::abs(cx_float(sp_eigval(i)).real() - eigval(k).real()) < 0.001) && (std::abs(cx_float(sp_eigval(i)).imag() - eigval(k).imag()) < 0.001) && (used(k) == 0)) { dense_eval = k; used(k) = 1; break; } } REQUIRE( dense_eval != n_rows + 1 ); REQUIRE( std::abs(sp_eigval(i)) == Approx(std::abs(eigval(dense_eval))).margin(0.001) ); for(uword j = 0; j < n_rows; ++j) { REQUIRE( std::abs(sp_eigvec(j, i)) == Approx(std::abs(eigvec(j, dense_eval))).margin(0.01) ); } } } REQUIRE(count > 0); } TEST_CASE("fn_eigs_gen_even_float_sigma_test") { const uword n_rows = 12; const uword n_eigval = 8; const float sigma = 1.0; const uword n_trials = 10; uword count = 0; for(uword trial=0; trial < n_trials; ++trial) { SpMat<float> m; m.sprandu(n_rows, n_rows, 0.3); for(uword i = 0; i < n_rows; ++i) { m(i, i) += 5 * double(i) / double(n_rows); } m += (sigma+0.001)*speye<SpMat<float>>(n_rows, n_rows); Mat<float> d(m); // Eigendecompose, getting first 8 eigenvectors. Col<cx_float> sp_eigval; Mat<cx_float> sp_eigvec; const bool status_sparse = eigs_gen(sp_eigval, sp_eigvec, m, n_eigval, sigma); // Do the same for the dense case around 1. Col<cx_float> eigval; Mat<cx_float> eigvec; const bool status_dense = eig_gen(eigval, eigvec, d); if( (status_sparse == false) || (status_dense == false) ) { continue; } else { ++count; } uvec used(n_rows, fill::zeros); for(uword i=0; i < n_eigval; ++i) { // Sorting these is difficult. // Find which one is the likely dense eigenvalue. uword dense_eval = n_rows + 1; for(uword k = 0; k < n_rows; ++k) { if ((std::abs(cx_float(sp_eigval(i)).real() - eigval(k).real()) < 0.001) && (std::abs(cx_float(sp_eigval(i)).imag() - eigval(k).imag()) < 0.001) && (used(k) == 0)) { dense_eval = k; used(k) = 1; break; } } REQUIRE( dense_eval != n_rows + 1 ); REQUIRE( std::abs(sp_eigval(i)) == Approx(std::abs(eigval(dense_eval))).margin(0.01) ); for(uword j = 0; j < n_rows; ++j) { REQUIRE( std::abs(sp_eigvec(j, i)) == Approx(std::abs(eigvec(j, dense_eval))).margin(0.01) ); } } } REQUIRE(count > 0); } TEST_CASE("fn_eigs_gen_even_float_sigma_opts_test") { const uword n_rows = 12; const uword n_eigval = 8; const float sigma = 1.0; const uword n_trials = 10; uword count = 0; for(uword trial=0; trial < n_trials; ++trial) { SpMat<float> m; m.sprandu(n_rows, n_rows, 0.3); for(uword i = 0; i < n_rows; ++i) { m(i, i) += 5 * double(i) / double(n_rows); } m += (sigma+0.001)*speye<SpMat<float>>(n_rows, n_rows); Mat<float> d(m); // Eigendecompose, getting first 8 eigenvectors. Col<cx_float> sp_eigval; Mat<cx_float> sp_eigvec; eigs_opts opts{}; opts.maxiter = 10000; opts.tol = 1e-12; const bool status_sparse = eigs_gen(sp_eigval, sp_eigvec, m, n_eigval, sigma, opts); // Do the same for the dense case around 1. Col<cx_float> eigval; Mat<cx_float> eigvec; const bool status_dense = eig_gen(eigval, eigvec, d); if( (status_sparse == false) || (status_dense == false) ) { continue; } else { ++count; } uvec used(n_rows, fill::zeros); for(uword i=0; i < n_eigval; ++i) { // Sorting these is difficult. // Find which one is the likely dense eigenvalue. uword dense_eval = n_rows + 1; for(uword k = 0; k < n_rows; ++k) { if ((std::abs(cx_float(sp_eigval(i)).real() - eigval(k).real()) < 0.001) && (std::abs(cx_float(sp_eigval(i)).imag() - eigval(k).imag()) < 0.001) && (used(k) == 0)) { dense_eval = k; used(k) = 1; break; } } REQUIRE( dense_eval != n_rows + 1 ); REQUIRE( std::abs(sp_eigval(i)) == Approx(std::abs(eigval(dense_eval))).margin(0.01) ); for(uword j = 0; j < n_rows; ++j) { REQUIRE( std::abs(sp_eigvec(j, i)) == Approx(std::abs(eigvec(j, dense_eval))).margin(0.01) ); } } } REQUIRE(count > 0); } TEST_CASE("fn_eigs_gen_odd_float_sm_test") { const uword n_rows = 10; const uword n_eigval = 5; const uword n_trials = 10; uword count = 0; for(uword trial=0; trial < n_trials; ++trial) { SpMat<float> m; m.sprandu(n_rows, n_rows, 0.3); for(uword i = 0; i < n_rows; ++i) { m(i, i) += 5 * double(i) / double(n_rows); } m += 0.001*speye<SpMat<float>>(n_rows, n_rows); Mat<float> d(m); // Eigendecompose, getting first 5 eigenvectors. Col<cx_float> sp_eigval; Mat<cx_float> sp_eigvec; const bool status_sparse = eigs_gen(sp_eigval, sp_eigvec, m, n_eigval, "sm"); // Do the same for the dense case. Col<cx_float> eigval; Mat<cx_float> eigvec; const bool status_dense = eig_gen(eigval, eigvec, d); if( (status_sparse == false) || (status_dense == false) ) { continue; } else { ++count; } uvec used(n_rows, fill::zeros); for(uword i=0; i < n_eigval; ++i) { // Sorting these is difficult. // Find which one is the likely dense eigenvalue. uword dense_eval = n_rows + 1; for(uword k = 0; k < n_rows; ++k) { if ((std::abs(cx_float(sp_eigval(i)).real() - eigval(k).real()) < 0.001) && (std::abs(cx_float(sp_eigval(i)).imag() - eigval(k).imag()) < 0.001) && (used(k) == 0)) { dense_eval = k; used(k) = 1; break; } } REQUIRE( dense_eval != n_rows + 1 ); REQUIRE( std::abs(sp_eigval(i)) == Approx(std::abs(eigval(dense_eval))).margin(0.001) ); for(uword j = 0; j < n_rows; ++j) { REQUIRE( std::abs(sp_eigvec(j, i)) == Approx(std::abs(eigvec(j, dense_eval))).margin(0.01) ); } } } REQUIRE(count > 0); } TEST_CASE("fn_eigs_gen_even_float_sm_test") { const uword n_rows = 12; const uword n_eigval = 8; const uword n_trials = 10; uword count = 0; for(uword trial=0; trial < n_trials; ++trial) { SpMat<float> m; m.sprandu(n_rows, n_rows, 0.3); for(uword i = 0; i < n_rows; ++i) { m(i, i) += 5 * double(i) / double(n_rows); } m += 0.001*speye<SpMat<float>>(n_rows, n_rows); Mat<float> d(m); // Eigendecompose, getting first 8 eigenvectors. Col<cx_float> sp_eigval; Mat<cx_float> sp_eigvec; const bool status_sparse = eigs_gen(sp_eigval, sp_eigvec, m, n_eigval, "sm"); // Do the same for the dense case. Col<cx_float> eigval; Mat<cx_float> eigvec; const bool status_dense = eig_gen(eigval, eigvec, d); if( (status_sparse == false) || (status_dense == false) ) { continue; } else { ++count; } uvec used(n_rows, fill::zeros); for(uword i=0; i < n_eigval; ++i) { // Sorting these is difficult. // Find which one is the likely dense eigenvalue. uword dense_eval = n_rows + 1; for(uword k = 0; k < n_rows; ++k) { if ((std::abs(cx_float(sp_eigval(i)).real() - eigval(k).real()) < 0.001) && (std::abs(cx_float(sp_eigval(i)).imag() - eigval(k).imag()) < 0.001) && (used(k) == 0)) { dense_eval = k; used(k) = 1; break; } } REQUIRE( dense_eval != n_rows + 1 ); REQUIRE( std::abs(sp_eigval(i)) == Approx(std::abs(eigval(dense_eval))).margin(0.01) ); for(uword j = 0; j < n_rows; ++j) { REQUIRE( std::abs(sp_eigvec(j, i)) == Approx(std::abs(eigvec(j, dense_eval))).margin(0.01) ); } } } REQUIRE(count > 0); } TEST_CASE("fn_eigs_gen_even_float_sm_opts_test") { const uword n_rows = 12; const uword n_eigval = 8; const uword n_trials = 10; uword count = 0; for(uword trial=0; trial < n_trials; ++trial) { SpMat<float> m; m.sprandu(n_rows, n_rows, 0.3); for(uword i = 0; i < n_rows; ++i) { m(i, i) += 5 * double(i) / double(n_rows); } m += 0.001*speye<SpMat<float>>(n_rows, n_rows); Mat<float> d(m); // Eigendecompose, getting first 8 eigenvectors. Col<cx_float> sp_eigval; Mat<cx_float> sp_eigvec; eigs_opts opts{}; opts.maxiter = 10000; opts.tol = 1e-12; const bool status_sparse = eigs_gen(sp_eigval, sp_eigvec, m, n_eigval, "sm", opts); // Do the same for the dense case. Col<cx_float> eigval; Mat<cx_float> eigvec; const bool status_dense = eig_gen(eigval, eigvec, d); if( (status_sparse == false) || (status_dense == false) ) { continue; } else { ++count; } uvec used(n_rows, fill::zeros); for(uword i=0; i < n_eigval; ++i) { // Sorting these is difficult. // Find which one is the likely dense eigenvalue. uword dense_eval = n_rows + 1; for(uword k = 0; k < n_rows; ++k) { if ((std::abs(cx_float(sp_eigval(i)).real() - eigval(k).real()) < 0.001) && (std::abs(cx_float(sp_eigval(i)).imag() - eigval(k).imag()) < 0.001) && (used(k) == 0)) { dense_eval = k; used(k) = 1; break; } } REQUIRE( dense_eval != n_rows + 1 ); REQUIRE( std::abs(sp_eigval(i)) == Approx(std::abs(eigval(dense_eval))).margin(0.01) ); for(uword j = 0; j < n_rows; ++j) { REQUIRE( std::abs(sp_eigvec(j, i)) == Approx(std::abs(eigvec(j, dense_eval))).margin(0.01) ); } } } REQUIRE(count > 0); } TEST_CASE("fn_eigs_gen_odd_complex_float_test") { const uword n_rows = 10; const uword n_eigval = 5; const uword n_trials = 10; uword count = 0; for(uword trial=0; trial < n_trials; ++trial) { SpMat<cx_float> m; m.sprandu(n_rows, n_rows, 0.3); Mat<cx_float> d(m); // Eigendecompose, getting first 5 eigenvectors. Col<cx_float> sp_eigval; Mat<cx_float> sp_eigvec; const bool status_sparse = eigs_gen(sp_eigval, sp_eigvec, m, n_eigval); // Do the same for the dense case. Col<cx_float> eigval; Mat<cx_float> eigvec; const bool status_dense = eig_gen(eigval, eigvec, d); if( (status_sparse == false) || (status_dense == false) ) { continue; } else { ++count; } uvec used(n_rows, fill::zeros); for(uword i=0; i < n_eigval; ++i) { // Sorting these is difficult. // Find which one is the likely dense eigenvalue. uword dense_eval = n_rows + 1; for(uword k = 0; k < n_rows; ++k) { if ((std::abs(cx_float(sp_eigval(i)).real() - eigval(k).real()) < 0.001) && (std::abs(cx_float(sp_eigval(i)).imag() - eigval(k).imag()) < 0.001) && (used(k) == 0)) { dense_eval = k; used(k) = 1; break; } } REQUIRE( dense_eval != n_rows + 1 ); REQUIRE( std::abs(sp_eigval(i)) == Approx(std::abs(eigval(dense_eval))).margin(0.01) ); for(uword j = 0; j < n_rows; ++j) { REQUIRE( std::abs(sp_eigvec(j, i)) == Approx(std::abs(eigvec(j, dense_eval))).margin(0.01) ); } } } REQUIRE(count > 0); } TEST_CASE("fn_eigs_gen_even_complex_float_test") { const uword n_rows = 12; const uword n_eigval = 8; const uword n_trials = 10; uword count = 0; for(uword trial=0; trial < n_trials; ++trial) { SpMat<cx_float> m; m.sprandu(n_rows, n_rows, 0.3); Mat<cx_float> d(m); // Eigendecompose, getting first 8 eigenvectors. Col<cx_float> sp_eigval; Mat<cx_float> sp_eigvec; const bool status_sparse = eigs_gen(sp_eigval, sp_eigvec, m, n_eigval); // Do the same for the dense case. Col<cx_float> eigval; Mat<cx_float> eigvec; const bool status_dense = eig_gen(eigval, eigvec, d); if( (status_sparse == false) || (status_dense == false) ) { continue; } else { ++count; } uvec used(n_rows, fill::zeros); for(uword i=0; i < n_eigval; ++i) { // Sorting these is difficult. // Find which one is the likely dense eigenvalue. uword dense_eval = n_rows + 1; for(uword k = 0; k < n_rows; ++k) { if ((std::abs(cx_float(sp_eigval(i)).real() - eigval(k).real()) < 0.001) && (std::abs(cx_float(sp_eigval(i)).imag() - eigval(k).imag()) < 0.001) && (used(k) == 0)) { dense_eval = k; used(k) = 1; break; } } REQUIRE( dense_eval != n_rows + 1 ); REQUIRE( std::abs(sp_eigval(i)) == Approx(std::abs(eigval(dense_eval))).margin(0.01) ); for(uword j = 0; j < n_rows; ++j) { REQUIRE( std::abs(sp_eigvec(j, i)) == Approx(std::abs(eigvec(j, dense_eval))).margin(0.01) ); } } } REQUIRE(count > 0); } TEST_CASE("fn_eigs_gen_even_complex_float_opts_test") { const uword n_rows = 12; const uword n_eigval = 8; const uword n_trials = 10; uword count = 0; for(uword trial=0; trial < n_trials; ++trial) { SpMat<cx_float> m; m.sprandu(n_rows, n_rows, 0.3); Mat<cx_float> d(m); // Eigendecompose, getting first 8 eigenvectors. Col<cx_float> sp_eigval; Mat<cx_float> sp_eigvec; eigs_opts opts{}; opts.maxiter = 10000; opts.tol = 1e-12; const bool status_sparse = eigs_gen(sp_eigval, sp_eigvec, m, n_eigval, "lm", opts); // Do the same for the dense case. Col<cx_float> eigval; Mat<cx_float> eigvec; const bool status_dense = eig_gen(eigval, eigvec, d); if( (status_sparse == false) || (status_dense == false) ) { continue; } else { ++count; } uvec used(n_rows, fill::zeros); for(uword i=0; i < n_eigval; ++i) { // Sorting these is difficult. // Find which one is the likely dense eigenvalue. uword dense_eval = n_rows + 1; for(uword k = 0; k < n_rows; ++k) { if ((std::abs(cx_float(sp_eigval(i)).real() - eigval(k).real()) < 0.001) && (std::abs(cx_float(sp_eigval(i)).imag() - eigval(k).imag()) < 0.001) && (used(k) == 0)) { dense_eval = k; used(k) = 1; break; } } REQUIRE( dense_eval != n_rows + 1 ); REQUIRE( std::abs(sp_eigval(i)) == Approx(std::abs(eigval(dense_eval))).margin(0.01) ); for(uword j = 0; j < n_rows; ++j) { REQUIRE( std::abs(sp_eigvec(j, i)) == Approx(std::abs(eigvec(j, dense_eval))).margin(0.01) ); } } } REQUIRE(count > 0); } TEST_CASE("fn_eigs_gen_odd_complex_float_sigma_test") { const uword n_rows = 10; const uword n_eigval = 5; const cx_float sigma = 1.0; const uword n_trials = 10; uword count = 0; for(uword trial=0; trial < n_trials; ++trial) { SpMat<cx_float> m; m.sprandu(n_rows, n_rows, 0.3); sp_cx_fmat z(5, 5); z.sprandu(5, 5, 0.5); m.submat(2, 2, 6, 6) += 5 * z; m += (sigma+cx_float(0.001,0))*speye< SpMat<cx_float> >(n_rows, n_rows); Mat<cx_float> d(m); // Eigendecompose, getting first 5 eigenvectors around 1. Col<cx_float> sp_eigval; Mat<cx_float> sp_eigvec; const bool status_sparse = eigs_gen(sp_eigval, sp_eigvec, m, n_eigval, sigma); // Do the same for the dense case. Col<cx_float> eigval; Mat<cx_float> eigvec; const bool status_dense = eig_gen(eigval, eigvec, d); if( (status_sparse == false) || (status_dense == false) ) { continue; } else { ++count; } uvec used(n_rows, fill::zeros); for(uword i=0; i < n_eigval; ++i) { // Sorting these is difficult. // Find which one is the likely dense eigenvalue. uword dense_eval = n_rows + 1; for(uword k = 0; k < n_rows; ++k) { if ((std::abs(cx_float(sp_eigval(i)).real() - eigval(k).real()) < 0.001) && (std::abs(cx_float(sp_eigval(i)).imag() - eigval(k).imag()) < 0.001) && (used(k) == 0)) { dense_eval = k; used(k) = 1; break; } } REQUIRE( dense_eval != n_rows + 1 ); REQUIRE( std::abs(sp_eigval(i)) == Approx(std::abs(eigval(dense_eval))).margin(0.01) ); for(uword j = 0; j < n_rows; ++j) { REQUIRE( std::abs(sp_eigvec(j, i)) == Approx(std::abs(eigvec(j, dense_eval))).margin(0.01) ); } } } REQUIRE(count > 0); } TEST_CASE("fn_eigs_gen_even_complex_float_sigma_test") { const uword n_rows = 12; const uword n_eigval = 8; const cx_float sigma = 1.0; const uword n_trials = 10; uword count = 0; for(uword trial=0; trial < n_trials; ++trial) { SpMat<cx_float> m; m.sprandu(n_rows, n_rows, 0.3); sp_cx_fmat z(8, 8); z.sprandu(8, 8, 0.5); m.submat(2, 2, 9, 9) += 8 * z; m += (sigma+cx_float(0.001,0))*speye< SpMat<cx_float> >(n_rows, n_rows); Mat<cx_float> d(m); // Eigendecompose, getting first 8 eigenvectors around 1. Col<cx_float> sp_eigval; Mat<cx_float> sp_eigvec; const bool status_sparse = eigs_gen(sp_eigval, sp_eigvec, m, n_eigval, sigma); // Do the same for the dense case. Col<cx_float> eigval; Mat<cx_float> eigvec; const bool status_dense = eig_gen(eigval, eigvec, d); if( (status_sparse == false) || (status_dense == false) ) { continue; } else { ++count; } uvec used(n_rows, fill::zeros); for(uword i=0; i < n_eigval; ++i) { // Sorting these is difficult. // Find which one is the likely dense eigenvalue. uword dense_eval = n_rows + 1; for(uword k = 0; k < n_rows; ++k) { if ((std::abs(cx_float(sp_eigval(i)).real() - eigval(k).real()) < 0.001) && (std::abs(cx_float(sp_eigval(i)).imag() - eigval(k).imag()) < 0.001) && (used(k) == 0)) { dense_eval = k; used(k) = 1; break; } } REQUIRE( dense_eval != n_rows + 1 ); REQUIRE( std::abs(sp_eigval(i)) == Approx(std::abs(eigval(dense_eval))).margin(0.01) ); for(uword j = 0; j < n_rows; ++j) { REQUIRE( std::abs(sp_eigvec(j, i)) == Approx(std::abs(eigvec(j, dense_eval))).margin(0.01) ); } } } REQUIRE(count > 0); } TEST_CASE("fn_eigs_gen_even_complex_float_sigma_opts_test") { const uword n_rows = 12; const uword n_eigval = 8; const cx_float sigma = 1.0; const uword n_trials = 10; uword count = 0; for(uword trial=0; trial < n_trials; ++trial) { SpMat<cx_float> m; m.sprandu(n_rows, n_rows, 0.3); sp_cx_fmat z(8, 8); z.sprandu(8, 8, 0.5); m.submat(2, 2, 9, 9) += 8 * z; m += (sigma+cx_float(0.001,0))*speye< SpMat<cx_float> >(n_rows, n_rows); Mat<cx_float> d(m); // Eigendecompose, getting first 8 eigenvectors around 1. Col<cx_float> sp_eigval; Mat<cx_float> sp_eigvec; eigs_opts opts{}; opts.maxiter = 10000; opts.tol = 1e-12; const bool status_sparse = eigs_gen(sp_eigval, sp_eigvec, m, n_eigval, sigma, opts); // Do the same for the dense case. Col<cx_float> eigval; Mat<cx_float> eigvec; const bool status_dense = eig_gen(eigval, eigvec, d); if( (status_sparse == false) || (status_dense == false) ) { continue; } else { ++count; } uvec used(n_rows, fill::zeros); for(uword i=0; i < n_eigval; ++i) { // Sorting these is difficult. // Find which one is the likely dense eigenvalue. uword dense_eval = n_rows + 1; for(uword k = 0; k < n_rows; ++k) { if ((std::abs(cx_float(sp_eigval(i)).real() - eigval(k).real()) < 0.001) && (std::abs(cx_float(sp_eigval(i)).imag() - eigval(k).imag()) < 0.001) && (used(k) == 0)) { dense_eval = k; used(k) = 1; break; } } REQUIRE( dense_eval != n_rows + 1 ); REQUIRE( std::abs(sp_eigval(i)) == Approx(std::abs(eigval(dense_eval))).margin(0.01) ); for(uword j = 0; j < n_rows; ++j) { REQUIRE( std::abs(sp_eigvec(j, i)) == Approx(std::abs(eigvec(j, dense_eval))).margin(0.01) ); } } } REQUIRE(count > 0); } TEST_CASE("fn_eigs_gen_odd_complex_float_sm_test") { const uword n_rows = 10; const uword n_eigval = 5; const uword n_trials = 10; uword count = 0; for(uword trial=0; trial < n_trials; ++trial) { SpMat<cx_float> m; m.sprandu(n_rows, n_rows, 0.3); sp_cx_fmat z(5, 5); z.sprandu(5, 5, 0.5); m.submat(2, 2, 6, 6) += 5 * z; m += cx_float(0.001,0)*speye< SpMat<cx_float> >(n_rows, n_rows); Mat<cx_float> d(m); // Eigendecompose, getting first 5 eigenvectors. Col<cx_float> sp_eigval; Mat<cx_float> sp_eigvec; const bool status_sparse = eigs_gen(sp_eigval, sp_eigvec, m, n_eigval, "sm"); // Do the same for the dense case. Col<cx_float> eigval; Mat<cx_float> eigvec; const bool status_dense = eig_gen(eigval, eigvec, d); if( (status_sparse == false) || (status_dense == false) ) { continue; } else { ++count; } uvec used(n_rows, fill::zeros); for(uword i=0; i < n_eigval; ++i) { // Sorting these is difficult. // Find which one is the likely dense eigenvalue. uword dense_eval = n_rows + 1; for(uword k = 0; k < n_rows; ++k) { if ((std::abs(cx_float(sp_eigval(i)).real() - eigval(k).real()) < 0.001) && (std::abs(cx_float(sp_eigval(i)).imag() - eigval(k).imag()) < 0.001) && (used(k) == 0)) { dense_eval = k; used(k) = 1; break; } } REQUIRE( dense_eval != n_rows + 1 ); REQUIRE( std::abs(sp_eigval(i)) == Approx(std::abs(eigval(dense_eval))).margin(0.01) ); for(uword j = 0; j < n_rows; ++j) { REQUIRE( std::abs(sp_eigvec(j, i)) == Approx(std::abs(eigvec(j, dense_eval))).margin(0.01) ); } } } REQUIRE(count > 0); } TEST_CASE("fn_eigs_gen_even_complex_float_sm_test") { const uword n_rows = 12; const uword n_eigval = 8; const uword n_trials = 10; uword count = 0; for(uword trial=0; trial < n_trials; ++trial) { SpMat<cx_float> m; m.sprandu(n_rows, n_rows, 0.3); sp_cx_fmat z(8, 8); z.sprandu(8, 8, 0.5); m.submat(2, 2, 9, 9) += 8 * z; m += cx_float(0.001,0)*speye< SpMat<cx_float> >(n_rows, n_rows); Mat<cx_float> d(m); // Eigendecompose, getting first 8 eigenvectors. Col<cx_float> sp_eigval; Mat<cx_float> sp_eigvec; const bool status_sparse = eigs_gen(sp_eigval, sp_eigvec, m, n_eigval, "sm"); // Do the same for the dense case. Col<cx_float> eigval; Mat<cx_float> eigvec; const bool status_dense = eig_gen(eigval, eigvec, d); if( (status_sparse == false) || (status_dense == false) ) { continue; } else { ++count; } uvec used(n_rows, fill::zeros); for(uword i=0; i < n_eigval; ++i) { // Sorting these is difficult. // Find which one is the likely dense eigenvalue. uword dense_eval = n_rows + 1; for(uword k = 0; k < n_rows; ++k) { if ((std::abs(cx_float(sp_eigval(i)).real() - eigval(k).real()) < 0.001) && (std::abs(cx_float(sp_eigval(i)).imag() - eigval(k).imag()) < 0.001) && (used(k) == 0)) { dense_eval = k; used(k) = 1; break; } } REQUIRE( dense_eval != n_rows + 1 ); REQUIRE( std::abs(sp_eigval(i)) == Approx(std::abs(eigval(dense_eval))).margin(0.01) ); for(uword j = 0; j < n_rows; ++j) { REQUIRE( std::abs(sp_eigvec(j, i)) == Approx(std::abs(eigvec(j, dense_eval))).margin(0.01) ); } } } REQUIRE(count > 0); } TEST_CASE("fn_eigs_gen_even_complex_float_sm_opts_test") { const uword n_rows = 12; const uword n_eigval = 8; const uword n_trials = 10; uword count = 0; for(uword trial=0; trial < n_trials; ++trial) { SpMat<cx_float> m; m.sprandu(n_rows, n_rows, 0.3); sp_cx_fmat z(8, 8); z.sprandu(8, 8, 0.5); m.submat(2, 2, 9, 9) += 8 * z; m += cx_float(0.001,0)*speye< SpMat<cx_float> >(n_rows, n_rows); Mat<cx_float> d(m); // Eigendecompose, getting first 8 eigenvectors. Col<cx_float> sp_eigval; Mat<cx_float> sp_eigvec; eigs_opts opts{}; opts.maxiter = 10000; opts.tol = 1e-12; const bool status_sparse = eigs_gen(sp_eigval, sp_eigvec, m, n_eigval, "sm", opts); // Do the same for the dense case. Col<cx_float> eigval; Mat<cx_float> eigvec; const bool status_dense = eig_gen(eigval, eigvec, d); if( (status_sparse == false) || (status_dense == false) ) { continue; } else { ++count; } uvec used(n_rows, fill::zeros); for(uword i=0; i < n_eigval; ++i) { // Sorting these is difficult. // Find which one is the likely dense eigenvalue. uword dense_eval = n_rows + 1; for(uword k = 0; k < n_rows; ++k) { if ((std::abs(cx_float(sp_eigval(i)).real() - eigval(k).real()) < 0.001) && (std::abs(cx_float(sp_eigval(i)).imag() - eigval(k).imag()) < 0.001) && (used(k) == 0)) { dense_eval = k; used(k) = 1; break; } } REQUIRE( dense_eval != n_rows + 1 ); REQUIRE( std::abs(sp_eigval(i)) == Approx(std::abs(eigval(dense_eval))).margin(0.01) ); for(uword j = 0; j < n_rows; ++j) { REQUIRE( std::abs(sp_eigvec(j, i)) == Approx(std::abs(eigvec(j, dense_eval))).margin(0.01) ); } } } REQUIRE(count > 0); } TEST_CASE("eigs_gen_odd_complex_test") { const uword n_rows = 10; const uword n_eigval = 5; const uword n_trials = 10; uword count = 0; for(uword trial=0; trial < n_trials; ++trial) { SpMat<cx_double> m; m.sprandu(n_rows, n_rows, 0.3); Mat<cx_double> d(m); // Eigendecompose, getting first 5 eigenvectors. Col<cx_double> sp_eigval; Mat<cx_double> sp_eigvec; const bool status_sparse = eigs_gen(sp_eigval, sp_eigvec, m, n_eigval); // Do the same for the dense case. Col<cx_double> eigval; Mat<cx_double> eigvec; const bool status_dense = eig_gen(eigval, eigvec, d); if( (status_sparse == false) || (status_dense == false) ) { continue; } else { ++count; } uvec used(n_rows, fill::zeros); for(uword i=0; i < n_eigval; ++i) { // Sorting these is difficult. // Find which one is the likely dense eigenvalue. uword dense_eval = n_rows + 1; for(uword k = 0; k < n_rows; ++k) { if ((std::abs(cx_double(sp_eigval(i)).real() - eigval(k).real()) < 1e-10) && (std::abs(cx_double(sp_eigval(i)).imag() - eigval(k).imag()) < 1e-10) && (used(k) == 0)) { dense_eval = k; used(k) = 1; break; } } REQUIRE( dense_eval != n_rows + 1 ); REQUIRE( std::abs(sp_eigval(i)) == Approx(std::abs(eigval(dense_eval))).margin(0.01) ); for(size_t j = 0; j < n_rows; ++j) { REQUIRE( std::abs(sp_eigvec(j, i)) == Approx(std::abs(eigvec(j, dense_eval))).margin(0.01) ); } } } REQUIRE(count > 0); } TEST_CASE("fn_eigs_gen_even_complex_test") { const uword n_rows = 15; const uword n_eigval = 6; const uword n_trials = 10; uword count = 0; for(uword trial=0; trial < n_trials; ++trial) { SpMat<cx_double> m; m.sprandu(n_rows, n_rows, 0.3); Mat<cx_double> d(m); // Eigendecompose, getting first 6 eigenvectors. Col<cx_double> sp_eigval; Mat<cx_double> sp_eigvec; const bool status_sparse = eigs_gen(sp_eigval, sp_eigvec, m, n_eigval); // Do the same for the dense case. Col<cx_double> eigval; Mat<cx_double> eigvec; const bool status_dense = eig_gen(eigval, eigvec, d); if( (status_sparse == false) || (status_dense == false) ) { continue; } else { ++count; } uvec used(n_rows, fill::zeros); for(uword i=0; i < n_eigval; ++i) { // Sorting these is difficult. // Find which one is the likely dense eigenvalue. uword dense_eval = n_rows + 1; for(uword k = 0; k < n_rows; ++k) { if ((std::abs(cx_double(sp_eigval(i)).real() - eigval(k).real()) < 1e-10) && (std::abs(cx_double(sp_eigval(i)).imag() - eigval(k).imag()) < 1e-10) && (used(k) == 0)) { dense_eval = k; used(k) = 1; break; } } REQUIRE( dense_eval != n_rows + 1 ); REQUIRE( std::abs(sp_eigval(i)) == Approx(std::abs(eigval(dense_eval))).margin(0.01) ); for(uword j = 0; j < n_rows; ++j) { REQUIRE( std::abs(sp_eigvec(j, i)) == Approx(std::abs(eigvec(j, dense_eval))).margin(0.01) ); } } } REQUIRE(count > 0); } TEST_CASE("fn_eigs_gen_even_complex_opts_test") { const uword n_rows = 15; const uword n_eigval = 6; const uword n_trials = 10; uword count = 0; for(uword trial=0; trial < n_trials; ++trial) { SpMat<cx_double> m; m.sprandu(n_rows, n_rows, 0.3); Mat<cx_double> d(m); // Eigendecompose, getting first 6 eigenvectors. Col<cx_double> sp_eigval; Mat<cx_double> sp_eigvec; eigs_opts opts{}; opts.maxiter = 10000; opts.tol = 1e-12; const bool status_sparse = eigs_gen(sp_eigval, sp_eigvec, m, n_eigval, "lm", opts); // Do the same for the dense case. Col<cx_double> eigval; Mat<cx_double> eigvec; const bool status_dense = eig_gen(eigval, eigvec, d); if( (status_sparse == false) || (status_dense == false) ) { continue; } else { ++count; } uvec used(n_rows, fill::zeros); for(uword i=0; i < n_eigval; ++i) { // Sorting these is difficult. // Find which one is the likely dense eigenvalue. uword dense_eval = n_rows + 1; for(uword k = 0; k < n_rows; ++k) { if ((std::abs(cx_double(sp_eigval(i)).real() - eigval(k).real()) < 1e-10) && (std::abs(cx_double(sp_eigval(i)).imag() - eigval(k).imag()) < 1e-10) && (used(k) == 0)) { dense_eval = k; used(k) = 1; break; } } REQUIRE( dense_eval != n_rows + 1 ); REQUIRE( std::abs(sp_eigval(i)) == Approx(std::abs(eigval(dense_eval))).margin(0.01) ); for(uword j = 0; j < n_rows; ++j) { REQUIRE( std::abs(sp_eigvec(j, i)) == Approx(std::abs(eigvec(j, dense_eval))).margin(0.01) ); } } } REQUIRE(count > 0); } TEST_CASE("eigs_gen_odd_complex_sigma_test") { const uword n_rows = 10; const uword n_eigval = 5; const cx_double sigma = 1.0; const uword n_trials = 10; uword count = 0; for(uword trial=0; trial < n_trials; ++trial) { SpMat<cx_double> m; m.sprandu(n_rows, n_rows, 0.3); sp_cx_mat z(5, 5); z.sprandu(5, 5, 0.5); m.submat(2, 2, 6, 6) += 5 * z; m += (sigma+cx_double(0.001,0))*speye< SpMat<cx_double> >(n_rows, n_rows); Mat<cx_double> d(m); // Eigendecompose, getting first 5 eigenvectors around 1. Col<cx_double> sp_eigval; Mat<cx_double> sp_eigvec; const bool status_sparse = eigs_gen(sp_eigval, sp_eigvec, m, n_eigval, sigma); // Do the same for the dense case. Col<cx_double> eigval; Mat<cx_double> eigvec; const bool status_dense = eig_gen(eigval, eigvec, d); if( (status_sparse == false) || (status_dense == false) ) { continue; } else { ++count; } uvec used(n_rows, fill::zeros); for(uword i=0; i < n_eigval; ++i) { // Sorting these is difficult. // Find which one is the likely dense eigenvalue. uword dense_eval = n_rows + 1; for(uword k = 0; k < n_rows; ++k) { if ((std::abs(cx_double(sp_eigval(i)).real() - eigval(k).real()) < 1e-10) && (std::abs(cx_double(sp_eigval(i)).imag() - eigval(k).imag()) < 1e-10) && (used(k) == 0)) { dense_eval = k; used(k) = 1; break; } } REQUIRE( dense_eval != n_rows + 1 ); REQUIRE( std::abs(sp_eigval(i)) == Approx(std::abs(eigval(dense_eval))).margin(0.01) ); for(size_t j = 0; j < n_rows; ++j) { REQUIRE( std::abs(sp_eigvec(j, i)) == Approx(std::abs(eigvec(j, dense_eval))).margin(0.01) ); } } } REQUIRE(count > 0); } TEST_CASE("fn_eigs_gen_even_complex_sigma_test") { const uword n_rows = 15; const uword n_eigval = 6; const cx_double sigma = 1.0; const uword n_trials = 10; uword count = 0; for(uword trial=0; trial < n_trials; ++trial) { SpMat<cx_double> m; m.sprandu(n_rows, n_rows, 0.3); sp_cx_mat z(8, 8); z.sprandu(8, 8, 0.5); m.submat(2, 2, 9, 9) += 8 * z; m += (sigma+cx_double(0.001,0))*speye< SpMat<cx_double> >(n_rows, n_rows); Mat<cx_double> d(m); // Eigendecompose, getting first 6 eigenvectors around 1. Col<cx_double> sp_eigval; Mat<cx_double> sp_eigvec; const bool status_sparse = eigs_gen(sp_eigval, sp_eigvec, m, n_eigval, sigma); // Do the same for the dense case. Col<cx_double> eigval; Mat<cx_double> eigvec; const bool status_dense = eig_gen(eigval, eigvec, d); if( (status_sparse == false) || (status_dense == false) ) { continue; } else { ++count; } uvec used(n_rows, fill::zeros); for(uword i=0; i < n_eigval; ++i) { // Sorting these is difficult. // Find which one is the likely dense eigenvalue. uword dense_eval = n_rows + 1; for(uword k = 0; k < n_rows; ++k) { if ((std::abs(cx_double(sp_eigval(i)).real() - eigval(k).real()) < 1e-10) && (std::abs(cx_double(sp_eigval(i)).imag() - eigval(k).imag()) < 1e-10) && (used(k) == 0)) { dense_eval = k; used(k) = 1; break; } } REQUIRE( dense_eval != n_rows + 1 ); REQUIRE( std::abs(sp_eigval(i)) == Approx(std::abs(eigval(dense_eval))).margin(0.01) ); for(uword j = 0; j < n_rows; ++j) { REQUIRE( std::abs(sp_eigvec(j, i)) == Approx(std::abs(eigvec(j, dense_eval))).margin(0.01) ); } } } REQUIRE(count > 0); } TEST_CASE("fn_eigs_gen_even_complex_sigma_opts_test") { const uword n_rows = 15; const uword n_eigval = 6; const cx_double sigma = 1.0; const uword n_trials = 10; uword count = 0; for(uword trial=0; trial < n_trials; ++trial) { SpMat<cx_double> m; m.sprandu(n_rows, n_rows, 0.3); sp_cx_mat z(8, 8); z.sprandu(8, 8, 0.5); m.submat(2, 2, 9, 9) += 8 * z; m += (sigma+cx_double(0.001,0))*speye< SpMat<cx_double> >(n_rows, n_rows); Mat<cx_double> d(m); // Eigendecompose, getting first 6 eigenvectors around 1.0. Col<cx_double> sp_eigval; Mat<cx_double> sp_eigvec; eigs_opts opts{}; opts.maxiter = 10000; opts.tol = 1e-12; const bool status_sparse = eigs_gen(sp_eigval, sp_eigvec, m, n_eigval, sigma, opts); // Do the same for the dense case. Col<cx_double> eigval; Mat<cx_double> eigvec; const bool status_dense = eig_gen(eigval, eigvec, d); if( (status_sparse == false) || (status_dense == false) ) { continue; } else { ++count; } uvec used(n_rows, fill::zeros); for(uword i=0; i < n_eigval; ++i) { // Sorting these is difficult. // Find which one is the likely dense eigenvalue. uword dense_eval = n_rows + 1; for(uword k = 0; k < n_rows; ++k) { if ((std::abs(cx_double(sp_eigval(i)).real() - eigval(k).real()) < 1e-10) && (std::abs(cx_double(sp_eigval(i)).imag() - eigval(k).imag()) < 1e-10) && (used(k) == 0)) { dense_eval = k; used(k) = 1; break; } } REQUIRE( dense_eval != n_rows + 1 ); REQUIRE( std::abs(sp_eigval(i)) == Approx(std::abs(eigval(dense_eval))).margin(0.01) ); for(uword j = 0; j < n_rows; ++j) { REQUIRE( std::abs(sp_eigvec(j, i)) == Approx(std::abs(eigvec(j, dense_eval))).margin(0.01) ); } } } REQUIRE(count > 0); } TEST_CASE("eigs_gen_odd_complex_sm_test") { const uword n_rows = 10; const uword n_eigval = 5; const uword n_trials = 10; uword count = 0; for(uword trial=0; trial < n_trials; ++trial) { SpMat<cx_double> m; m.sprandu(n_rows, n_rows, 0.3); m += cx_double(0.001,0)*speye< SpMat<cx_double> >(n_rows, n_rows); Mat<cx_double> d(m); // Eigendecompose, getting first 5 eigenvectors. Col<cx_double> sp_eigval; Mat<cx_double> sp_eigvec; const bool status_sparse = eigs_gen(sp_eigval, sp_eigvec, m, n_eigval, "sm"); // Do the same for the dense case. Col<cx_double> eigval; Mat<cx_double> eigvec; const bool status_dense = eig_gen(eigval, eigvec, d); if( (status_sparse == false) || (status_dense == false) ) { continue; } else { ++count; } uvec used(n_rows, fill::zeros); for(uword i=0; i < n_eigval; ++i) { // Sorting these is difficult. // Find which one is the likely dense eigenvalue. uword dense_eval = n_rows + 1; for(uword k = 0; k < n_rows; ++k) { if ((std::abs(cx_double(sp_eigval(i)).real() - eigval(k).real()) < 1e-10) && (std::abs(cx_double(sp_eigval(i)).imag() - eigval(k).imag()) < 1e-10) && (used(k) == 0)) { dense_eval = k; used(k) = 1; break; } } REQUIRE( dense_eval != n_rows + 1 ); REQUIRE( std::abs(sp_eigval(i)) == Approx(std::abs(eigval(dense_eval))).margin(0.01) ); for(size_t j = 0; j < n_rows; ++j) { REQUIRE( std::abs(sp_eigvec(j, i)) == Approx(std::abs(eigvec(j, dense_eval))).margin(0.01) ); } } } REQUIRE(count > 0); } TEST_CASE("fn_eigs_gen_even_complex_sm_test") { const uword n_rows = 15; const uword n_eigval = 6; const uword n_trials = 10; uword count = 0; for(uword trial=0; trial < n_trials; ++trial) { SpMat<cx_double> m; m.sprandu(n_rows, n_rows, 0.3); m += cx_double(0.001,0)*speye< SpMat<cx_double> >(n_rows, n_rows); Mat<cx_double> d(m); // Eigendecompose, getting first 6 eigenvectors. Col<cx_double> sp_eigval; Mat<cx_double> sp_eigvec; const bool status_sparse = eigs_gen(sp_eigval, sp_eigvec, m, n_eigval, "sm"); // Do the same for the dense case. Col<cx_double> eigval; Mat<cx_double> eigvec; const bool status_dense = eig_gen(eigval, eigvec, d); if( (status_sparse == false) || (status_dense == false) ) { continue; } else { ++count; } uvec used(n_rows, fill::zeros); for(uword i=0; i < n_eigval; ++i) { // Sorting these is difficult. // Find which one is the likely dense eigenvalue. uword dense_eval = n_rows + 1; for(uword k = 0; k < n_rows; ++k) { if ((std::abs(cx_double(sp_eigval(i)).real() - eigval(k).real()) < 1e-10) && (std::abs(cx_double(sp_eigval(i)).imag() - eigval(k).imag()) < 1e-10) && (used(k) == 0)) { dense_eval = k; used(k) = 1; break; } } REQUIRE( dense_eval != n_rows + 1 ); REQUIRE( std::abs(sp_eigval(i)) == Approx(std::abs(eigval(dense_eval))).margin(0.01) ); for(uword j = 0; j < n_rows; ++j) { REQUIRE( std::abs(sp_eigvec(j, i)) == Approx(std::abs(eigvec(j, dense_eval))).margin(0.01) ); } } } REQUIRE(count > 0); } TEST_CASE("fn_eigs_gen_even_complex_sm_opts_test") { const uword n_rows = 15; const uword n_eigval = 6; const uword n_trials = 10; uword count = 0; for(uword trial=0; trial < n_trials; ++trial) { SpMat<cx_double> m; m.sprandu(n_rows, n_rows, 0.3); m += cx_double(0.001,0)*speye< SpMat<cx_double> >(n_rows, n_rows); Mat<cx_double> d(m); // Eigendecompose, getting first 6 eigenvectors. Col<cx_double> sp_eigval; Mat<cx_double> sp_eigvec; eigs_opts opts{}; opts.maxiter = 10000; opts.tol = 1e-12; const bool status_sparse = eigs_gen(sp_eigval, sp_eigvec, m, n_eigval, "sm", opts); // Do the same for the dense case. Col<cx_double> eigval; Mat<cx_double> eigvec; const bool status_dense = eig_gen(eigval, eigvec, d); if( (status_sparse == false) || (status_dense == false) ) { continue; } else { ++count; } uvec used(n_rows, fill::zeros); for(uword i=0; i < n_eigval; ++i) { // Sorting these is difficult. // Find which one is the likely dense eigenvalue. uword dense_eval = n_rows + 1; for(uword k = 0; k < n_rows; ++k) { if ((std::abs(cx_double(sp_eigval(i)).real() - eigval(k).real()) < 1e-10) && (std::abs(cx_double(sp_eigval(i)).imag() - eigval(k).imag()) < 1e-10) && (used(k) == 0)) { dense_eval = k; used(k) = 1; break; } } REQUIRE( dense_eval != n_rows + 1 ); REQUIRE( std::abs(sp_eigval(i)) == Approx(std::abs(eigval(dense_eval))).margin(0.01) ); for(uword j = 0; j < n_rows; ++j) { REQUIRE( std::abs(sp_eigvec(j, i)) == Approx(std::abs(eigvec(j, dense_eval))).margin(0.01) ); } } } REQUIRE(count > 0); }
[ "ashishsachan919@gmail.com" ]
ashishsachan919@gmail.com
acab21c2079606b258ba6884c41abfdf19110f93
4503b4ec29e9a30d26c433bac376f2bddaefd9e5
/Qt5.7/VC12/Win32/include/QtNetwork/qsslpresharedkeyauthenticator.h
06fb5e068e61c22162e6540fde92389121ac9d86
[]
no_license
SwunZH/ecocommlibs
0a872e0bbecbb843a0584fb787cf0c5e8a2a270b
4cff09ff1e479f5f519f207262a61ee85f543b3a
refs/heads/master
2021-01-25T12:02:39.067444
2018-02-23T07:04:43
2018-02-23T07:04:43
123,447,012
1
0
null
2018-03-01T14:37:53
2018-03-01T14:37:53
null
UTF-8
C++
false
false
3,950
h
/**************************************************************************** ** ** Copyright (C) 2014 Governikus GmbH & Co. KG. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the QtNetwork module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QSSLPRESHAREDKEYAUTHENTICATOR_H #define QSSLPRESHAREDKEYAUTHENTICATOR_H #include <QtCore/QtGlobal> #include <QtCore/QString> #include <QtCore/QSharedDataPointer> #include <QtCore/QMetaType> QT_BEGIN_NAMESPACE class QSslPreSharedKeyAuthenticatorPrivate; class QSslPreSharedKeyAuthenticator { public: Q_NETWORK_EXPORT QSslPreSharedKeyAuthenticator(); Q_NETWORK_EXPORT ~QSslPreSharedKeyAuthenticator(); Q_NETWORK_EXPORT QSslPreSharedKeyAuthenticator(const QSslPreSharedKeyAuthenticator &authenticator); Q_NETWORK_EXPORT QSslPreSharedKeyAuthenticator &operator=(const QSslPreSharedKeyAuthenticator &authenticator); #ifdef Q_COMPILER_RVALUE_REFS QSslPreSharedKeyAuthenticator &operator=(QSslPreSharedKeyAuthenticator &&other) Q_DECL_NOTHROW { swap(other); return *this; } #endif void swap(QSslPreSharedKeyAuthenticator &other) Q_DECL_NOTHROW { qSwap(d, other.d); } Q_NETWORK_EXPORT QByteArray identityHint() const; Q_NETWORK_EXPORT void setIdentity(const QByteArray &identity); Q_NETWORK_EXPORT QByteArray identity() const; Q_NETWORK_EXPORT int maximumIdentityLength() const; Q_NETWORK_EXPORT void setPreSharedKey(const QByteArray &preSharedKey); Q_NETWORK_EXPORT QByteArray preSharedKey() const; Q_NETWORK_EXPORT int maximumPreSharedKeyLength() const; private: friend Q_NETWORK_EXPORT bool operator==(const QSslPreSharedKeyAuthenticator &lhs, const QSslPreSharedKeyAuthenticator &rhs); friend class QSslSocketBackendPrivate; QSharedDataPointer<QSslPreSharedKeyAuthenticatorPrivate> d; }; inline bool operator!=(const QSslPreSharedKeyAuthenticator &lhs, const QSslPreSharedKeyAuthenticator &rhs) { return !operator==(lhs, rhs); } Q_DECLARE_SHARED(QSslPreSharedKeyAuthenticator) QT_END_NAMESPACE Q_DECLARE_METATYPE(QSslPreSharedKeyAuthenticator) Q_DECLARE_METATYPE(QSslPreSharedKeyAuthenticator*) #endif // QSSLPRESHAREDKEYAUTHENTICATOR_H
[ "deokhyun@3e9e098e-e079-49b3-9d2b-ee27db7392fb" ]
deokhyun@3e9e098e-e079-49b3-9d2b-ee27db7392fb
19b6df55a8998b06011b63e587d5780dabff63e9
78f7e2d25b092012c4d92d014e32fe6c6ea8325e
/Digital Image Processing/Homework4/Code & Image/main.cpp
293cffc10328d41b52f5c07c8a909bd54a550989
[ "MIT" ]
permissive
lulu754022140/Undergraduate-Course-Homework-ZJU
3c255eb78af20341b20e730f0d60ddf51275ea85
60028a18a811f52d92da63ed4aff7a4572e72052
refs/heads/master
2023-01-29T22:00:25.784876
2020-12-10T19:34:31
2020-12-10T19:34:31
null
0
0
null
null
null
null
GB18030
C++
false
false
10,335
cpp
#include <iostream> #include "opencv2/core/core.hpp" #include "opencv2/imgproc/imgproc.hpp" #include "opencv2/highgui/highgui.hpp" using namespace std; using namespace cv; float sigma = 0.002f; // 高斯白噪声方差 float K = 0.002f; // 维纳滤波系数 // 利用Box - Muller算法产生高斯随机数 float GenerateGaussianNoise() { static bool flag = false; static float rand1, rand2; if (flag) { flag = false; return sqrt(-2.0f * log(rand1)) * cos(2.0f * (float)CV_PI * rand2); } flag = true; rand1 = rand() / ((float)RAND_MAX); rand2 = rand() / ((float)RAND_MAX); if (rand1 < 1e-10) rand1 = (float)1e-10; if (rand2 < 1e-10) rand2 = (float)1e-10; return sqrt(-2.0f * log(rand1)) * sin(2.0f * (float)CV_PI * rand2); } void AddGaussianNoise(Mat& Image) { for (int i = 0; i < Image.rows; ++i) { for (int j = 0; j < Image.cols; ++j) { float value = Image.at<float>(i, j) + GenerateGaussianNoise() * sigma; if (value > 1.0f) value = 1.0f; if (value < 0.0f) value = 0.0f; Image.at<float>(i, j) = value; } } } int main() { Mat image = imread("原图像.png", CV_8UC1); // 获取最佳傅里叶变换尺寸 int optM = getOptimalDFTSize(image.rows); int optN = getOptimalDFTSize(image.cols); // 边界扩展 Mat expandedImage; copyMakeBorder(image, expandedImage, 0, optM - image.rows, 0, optM - image.cols, BORDER_CONSTANT, Scalar::all(0)); // 转成浮点图像 expandedImage.convertTo(expandedImage, CV_32FC1); normalize(expandedImage, expandedImage, 1, 0, CV_C); imshow("原图像", expandedImage); // 使频谱平移到中心 for (int i = 0; i < expandedImage.rows; i++) { for (int j = 0; j < expandedImage.cols; j++) { expandedImage.at<float>(i, j) *= (float)pow(-1, i + j); } } // 建立双通道(实部与虚部)图像 Mat planes[] = { Mat_<float>(expandedImage),Mat::zeros(expandedImage.size(),CV_32FC1) }; // 合成双通道 Mat complexImage; merge(planes, 2, complexImage); // 对双通道图像进行傅里叶变换 dft(complexImage, complexImage); // 定义运动模糊变换矩阵 Mat Motion(expandedImage.size(), CV_32FC2); Mat DeMotion(expandedImage.size(), CV_32FC2); float a = 0.03f; float b = 0.03f; float T = 1.0f; float CutOffBlur = 0.01f; float CutOffDeblur = 0.01f; for (int i = 0; i < expandedImage.rows; i++) { for (int j = 0; j < expandedImage.cols; j++) { float temp = (float)CV_PI * ((i - expandedImage.rows / 2) * a + (j - expandedImage.cols / 2) * b); if (temp == 0) { Motion.at<Vec2f>(i, j)[0] = T; Motion.at<Vec2f>(i, j)[1] = T; DeMotion.at<Vec2f>(i, j)[0] = T; DeMotion.at<Vec2f>(i, j)[1] = T; } else { Motion.at<Vec2f>(i, j)[0] = T / temp * (float)sin(temp)*(float)cos(temp); Motion.at<Vec2f>(i, j)[1] = T / temp * (float)sin(temp)*(float)cos(temp); DeMotion.at<Vec2f>(i, j)[0] = T / temp * (float)sin(temp)*(float)cos(temp); DeMotion.at<Vec2f>(i, j)[1] = T / temp * (float)sin(temp)*(float)cos(temp); // 滤波阈值 if (Motion.at<Vec2f>(i, j)[0] < CutOffBlur) { Motion.at<Vec2f>(i, j)[0] = CutOffBlur; Motion.at<Vec2f>(i, j)[1] = CutOffBlur; } // 滤波阈值 if (DeMotion.at<Vec2f>(i, j)[0] < CutOffDeblur) { DeMotion.at<Vec2f>(i, j)[0] = CutOffDeblur; DeMotion.at<Vec2f>(i, j)[1] = CutOffDeblur; } } } } Mat Blurred(expandedImage.size(), CV_32FC2); // 模糊频谱 Mat BlurredWithNoise(expandedImage.size(), CV_32FC2); // 模糊带噪声频谱 Mat BlurredImage(expandedImage.size(), CV_32FC1); // 模糊图像 Mat BlurredWithNoiseImage(expandedImage.size(), CV_32FC1); // 模糊带噪声图像 Mat Deblurred(expandedImage.size(), CV_32FC2); // 模糊逆滤波频谱 Mat DeblurredWithNoise(expandedImage.size(), CV_32FC2); // 模糊带噪声逆滤波频谱 Mat DeblurredImage(expandedImage.size(), CV_32FC1); // 模糊逆滤波图像 Mat DeblurredWithNoiseImage(expandedImage.size(), CV_32FC1); // 模糊带噪声逆滤波图像 Mat DeblurredWiener(expandedImage.size(), CV_32FC2); // 模糊维纳滤波频谱 Mat DeblurredWienerWithNoise(expandedImage.size(), CV_32FC2); // 模糊带噪声维纳滤波频谱 Mat DeblurredWienerImage(expandedImage.size(), CV_32FC1); // 模糊维纳滤波图像 Mat DeblurredWienerWithNoiseImage(expandedImage.size(), CV_32FC1); // 模糊带噪声维纳滤波图像 split(complexImage, planes); magnitude(planes[0], planes[1], planes[0]); planes[0] += Scalar::all(1); log(planes[0], planes[0]); normalize(planes[0], planes[0], 1, 0, CV_C); imshow("原图像频谱", planes[0]); normalize(planes[0], planes[0], 255, 0, CV_C); imwrite("原图像频谱.png", planes[0]); multiply(complexImage, Motion, Blurred); // 加入运动模糊 split(Blurred, planes); magnitude(planes[0], planes[1], planes[0]); planes[0] += Scalar::all(1); log(planes[0], planes[0]); normalize(planes[0], planes[0], 1, 0, CV_C); imshow("模糊图像频谱", planes[0]); normalize(planes[0], planes[0], 255, 0, CV_C); imwrite("模糊图像频谱.png", planes[0]); divide(Blurred, DeMotion, Deblurred); // 解运动模糊 split(Deblurred, planes); magnitude(planes[0], planes[1], planes[0]); planes[0] += Scalar::all(1); log(planes[0], planes[0]); normalize(planes[0], planes[0], 1, 0, CV_C); imshow("直接解模糊图像频谱", planes[0]); normalize(planes[0], planes[0], 255, 0, CV_C); imwrite("直接解模糊图像频谱.png", planes[0]); idft(Deblurred, Deblurred); split(Deblurred, planes); magnitude(planes[0], planes[1], DeblurredImage); normalize(DeblurredImage, DeblurredImage, 1, 0, CV_C); imshow("直接解模糊图像", DeblurredImage); normalize(DeblurredImage, DeblurredImage, 255, 0, CV_C); imwrite("直接解模糊图像.png", DeblurredImage); // 加噪声 idft(Blurred, Blurred); split(Blurred, planes); magnitude(planes[0], planes[1], BlurredImage); normalize(BlurredImage, BlurredImage, 1, 0, CV_C); imshow("模糊图像", BlurredImage); BlurredImage.copyTo(BlurredWithNoiseImage); AddGaussianNoise(BlurredWithNoiseImage); imshow("带噪声模糊图像", BlurredWithNoiseImage); normalize(BlurredImage, BlurredImage, 255, 0, CV_C); imwrite("模糊图像.png", BlurredImage); normalize(BlurredWithNoiseImage, BlurredWithNoiseImage, 255, 0, CV_C); imwrite("带噪声模糊图像.png", BlurredWithNoiseImage); for (int i = 0; i < BlurredWithNoiseImage.rows; i++) { for (int j = 0; j < BlurredWithNoiseImage.cols; j++) { BlurredWithNoiseImage.at<float>(i, j) *= (float)pow(-1, i + j); } } BlurredWithNoiseImage.copyTo(planes[0]); planes[1] = Mat::zeros(BlurredWithNoiseImage.size(), CV_32FC1); merge(planes, 2, BlurredWithNoise); dft(BlurredWithNoise, BlurredWithNoise); split(BlurredWithNoise, planes); magnitude(planes[0], planes[1], planes[0]); planes[0] += Scalar::all(1); log(planes[0], planes[0]); normalize(planes[0], planes[0], 1, 0, CV_C); imshow("带噪声模糊图像频谱", planes[0]); normalize(planes[0], planes[0], 255, 0, CV_C); imwrite("带噪声模糊图像频谱.png", planes[0]); divide(BlurredWithNoise, DeMotion, DeblurredWithNoise); split(DeblurredWithNoise, planes); magnitude(planes[0], planes[1], planes[0]); planes[0] += Scalar::all(1); log(planes[0], planes[0]); normalize(planes[0], planes[0], 1, 0, CV_C); imshow("解带噪声模糊图像频谱", planes[0]); normalize(planes[0], planes[0], 255, 0, CV_C); imwrite("解带噪声模糊图像频谱.png", planes[0]); idft(DeblurredWithNoise, DeblurredWithNoise); split(DeblurredWithNoise, planes); magnitude(planes[0], planes[1], DeblurredWithNoiseImage); normalize(DeblurredWithNoiseImage, DeblurredWithNoiseImage, 1, 0, CV_C); imshow("解带噪声模糊图像", DeblurredWithNoiseImage); normalize(DeblurredWithNoiseImage, DeblurredWithNoiseImage, 255, 0, CV_C); imwrite("解带噪声模糊图像.png", DeblurredWithNoiseImage); dft(Blurred, Blurred); // 维纳滤波 Mat temp(expandedImage.size(), CV_32FC2); Mat MagTransform(expandedImage.size(), CV_32FC2); for (int i = 0; i < MagTransform.rows; i++) { for (int j = 0; j < MagTransform.cols; j++) { MagTransform.at<Vec2f>(i, j)[0] = ((pow(Motion.at<Vec2f>(i, j)[0], 2) + pow(Motion.at<Vec2f>(i, j)[1], 2)) / (pow(Motion.at<Vec2f>(i, j)[0], 2) + pow(Motion.at<Vec2f>(i, j)[1], 2) + K)); MagTransform.at<Vec2f>(i, j)[1] = ((pow(Motion.at<Vec2f>(i, j)[0], 2) + pow(Motion.at<Vec2f>(i, j)[1], 2)) / (pow(Motion.at<Vec2f>(i, j)[0], 2) + pow(Motion.at<Vec2f>(i, j)[1], 2) + K)); } } divide(Blurred, Motion, temp); multiply(temp, MagTransform, DeblurredWiener); divide(BlurredWithNoise, Motion, temp); multiply(temp, MagTransform, DeblurredWienerWithNoise); split(DeblurredWiener, planes); magnitude(planes[0], planes[1], planes[0]); planes[0] += Scalar::all(1); log(planes[0], planes[0]); normalize(planes[0], planes[0], 1, 0, CV_C); imshow("维纳滤波解模糊图像频谱", planes[0]); normalize(planes[0], planes[0], 255, 0, CV_C); imwrite("维纳滤波解模糊图像频谱.png", planes[0]); idft(DeblurredWiener, DeblurredWiener); split(DeblurredWiener, planes); magnitude(planes[0], planes[1], DeblurredWienerImage); normalize(DeblurredWienerImage, DeblurredWienerImage, 1, 0, CV_C); imshow("维纳滤波解模糊图像", DeblurredWienerImage); normalize(DeblurredWienerImage, DeblurredWienerImage, 255, 0, CV_C); imwrite("维纳滤波解模糊图像.png", DeblurredWienerImage); split(DeblurredWienerWithNoise, planes); magnitude(planes[0], planes[1], planes[0]); planes[0] += Scalar::all(1); log(planes[0], planes[0]); normalize(planes[0], planes[0], 1, 0, CV_C); imshow("维纳滤波解带噪声模糊图像频谱", planes[0]); normalize(planes[0], planes[0], 255, 0, CV_C); imwrite("维纳滤波解带噪声模糊图像频谱.png", planes[0]); idft(DeblurredWienerWithNoise, DeblurredWienerWithNoise); split(DeblurredWienerWithNoise, planes); magnitude(planes[0], planes[1], DeblurredWienerWithNoiseImage); normalize(DeblurredWienerWithNoiseImage, DeblurredWienerWithNoiseImage, 1, 0, CV_C); imshow("维纳滤波解带噪声模糊图像", DeblurredWienerWithNoiseImage); normalize(DeblurredWienerWithNoiseImage, DeblurredWienerWithNoiseImage, 255, 0, CV_C); imwrite("维纳滤波解带噪声模糊图像.png", DeblurredWienerWithNoiseImage); waitKey(); return 0; }
[ "3150102239@zju.edu.cn" ]
3150102239@zju.edu.cn
1cb6d2c0559dcf850f2b689c001f59ad093b1d33
1b46d77d8715655996c88d4eefeada5af3e66ef3
/include/util/surfacemask/heightmapprobabilityfield.h
6f7481f8154301eea352d8ff9aa8a62b6e0b4de2
[]
no_license
sessamekesh/Indigo-Sapphire
7869084126576512914d9374f89d6490fe180393
c883df5c300ee4243231d385770567f877ae9e8f
refs/heads/master
2021-09-14T18:36:13.796173
2018-02-27T05:39:43
2018-02-27T05:39:43
114,555,973
0
0
null
null
null
null
UTF-8
C++
false
false
746
h
#pragma once #include <util/surfacemask/surfaceprobabilityfieldbase.h> #include <model/specialgeo/heightfield.h> #include <memory> #include <util/math/curve1to1.h> namespace util { class HeightmapProbabilityField : public SurfaceProbabilityFieldBase { public: HeightmapProbabilityField( std::shared_ptr<model::specialgeo::Heightfield> heightfield, std::shared_ptr<util::math::Curve1To1> probabilityCurve ); HeightmapProbabilityField() = default; HeightmapProbabilityField(const HeightmapProbabilityField&) = default; float getProbabilityAtPoint(const glm::vec2& location) override; protected: std::shared_ptr<model::specialgeo::Heightfield> heightfield_; std::shared_ptr<util::math::Curve1To1> probabilityCurve_; }; }
[ "kam.is.amazing@gmail.com" ]
kam.is.amazing@gmail.com
e9d7b4cf30801be6bdde79b4b70bf6bcb5668f54
4024f653077d530e4eb6554707c8180ea9089b59
/Source/ProceduralMesh/Terrain.h
9fb98dc9a9173306d759a4525d0f44a712587be4
[]
no_license
dzoidx/UE4ProceduralMesh
1335a2e750dc98893f898f8210ab16e0f5c121c7
5d6e5548cc7b155953809aecabfb8795a722d723
refs/heads/master
2020-12-13T12:52:15.057466
2015-05-25T22:03:58
2015-05-25T22:03:58
36,254,029
0
0
null
2015-05-25T20:55:13
2015-05-25T20:55:13
null
UTF-8
C++
false
false
748
h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "GameFramework/Actor.h" #include "ProceduralMeshComponent.h" #include "Terrain.generated.h" UCLASS() class PROCEDURALMESH_API ATerrain : public AActor { GENERATED_BODY() public: // Sets default values for this actor's properties ATerrain(); // Called when the game starts or when spawned virtual void BeginPlay() override; // Called every frame virtual void Tick( float DeltaSeconds ) override; void GenerateTerrain(TArray<FProceduralMeshTriangle>& OutTriangles); UPROPERTY(EditAnywhere, Category = HeightMap) UTexture2D* HeightMap; UPROPERTY(VisibleAnywhere, Category = Materials) UProceduralMeshComponent* mesh; };
[ "dzoidx@gmail.com" ]
dzoidx@gmail.com
0dbffdfeb2a5e2a2fb9ebdaac79629d42f40b76d
2febe3b6474962d3281e5cbdca676d7a3408ef96
/Lab 3/VectorTesting.cpp
c5598e247a047604103f77d109ebb205a8a65c59
[]
no_license
kunapavk/Data-Structures
1f8f773a4b23de69801a1a8244e4e06b70291b4f
5d5b12a7bef04043d3674195569192a15e0454ba
refs/heads/master
2021-01-23T10:23:16.720745
2017-09-06T13:53:26
2017-09-06T13:53:26
102,614,294
0
0
null
null
null
null
UTF-8
C++
false
false
1,795
cpp
#include <iostream> #include <string> #include "Vector.h" using namespace std; //Function prototyping Vector_H get_second_vector(); double get_user_num_choice(); int main() { bool user_choice = true; while (user_choice) { user_choice = false; int temp_x; int temp_y; cout << "Please enter the x co-ordinate for the vector: "; cin >> temp_x; cout << "Please enter the y co-ordinate for the vector: "; cin >> temp_y; Vector_H first(temp_x, temp_y); char operation_choice; cout << "Please enter the operation to perform(+, -, *, /): "; cin >> operation_choice; Vector_H second, result; double num_choice; switch (operation_choice) { case '+': second = get_second_vector(); result = first + second; result.print_members(); break; case '-': second = get_second_vector(); result = first - second; result.print_members(); break; case '*': num_choice = get_user_num_choice(); result = first * num_choice; result.print_members(); break; case '/': num_choice = get_user_num_choice(); result = first / num_choice; result.print_members(); break; default: cout << "Incorrect input. Please try again." << endl; break; } char user_choice_char; cout << "Do you wish to continue?(Y/N): "; cin >> user_choice_char; if (tolower(user_choice_char) == 'y') { user_choice = true; } } } Vector_H get_second_vector() { int temp_x_2; int temp_y_2; cout << "Enter x co-ordinate of second vector: "; cin >> temp_x_2; cout << "Enter y co-ordinate of second vector: "; cin >> temp_y_2; return Vector_H(temp_x_2, temp_y_2); } double get_user_num_choice() { double ret_val; cout << "Please enter the scalar operand you wish to work with: "; cin >> ret_val; return ret_val; }
[ "kunapavk@mail.uc.edu" ]
kunapavk@mail.uc.edu
ada87e504f957f0939039a3a519e78baf2324965
551aeab5a40423df8b671a2cc557d5191ccf4703
/frame/base/AFTimer.hpp
d3873300c6e53c10df8ac08c21840785367b5f14
[ "Apache-2.0" ]
permissive
bbants/ARK
998bd8f839e28c2104d7e9d3fc18ceb468e2ad8f
94f9c40146bc41bab5f59be785ef7eff87697ac5
refs/heads/master
2020-05-02T22:18:49.469382
2019-01-21T01:50:17
2019-01-21T01:50:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,332
hpp
/* * This source file is part of ARK * For the latest info, see https://github.com/QuadHex * * Copyright (c) 2013-2018 QuadHex authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #pragma once #include "AFPlatform.hpp" #include "AFDefine.hpp" #include "AFSingleton.hpp" #include "AFDateTime.hpp" namespace ark { enum AFTimerEnum { TIMER_TYPE_COUNT_LIMIT = 0, TIMER_TYPE_FOREVER = 1, MAX_SLOT = 1000, SLOT_TIME = 1, WHEEL_TIME = MAX_SLOT * SLOT_TIME, }; class AFTimerData { public: AFTimerData() { memset(name, 0x0, sizeof(name)); } char name[16]; uint32_t type = 0; uint32_t count = 0; uint32_t interval = 0; uint32_t rotation = 0; uint32_t slot = 0; TIMER_FUNCTOR_PTR callback; //callback data AFGUID entity_id = 0; AFTimerData* prev = nullptr; AFTimerData* next = nullptr; }; class AFTimerManager : public AFSingleton<AFTimerManager> { public: AFTimerManager() { mnNowSlot = 0; mnLastUpdateTime = 0; memset(mxSlots, 0x0, sizeof(mxSlots)); } ~AFTimerManager() { } void Init(uint64_t now_time) { mnNowSlot = 0; mnLastUpdateTime = now_time; } void Update(int64_t now_time) { UpdateTimerReg(); UpdateTimer(now_time); } void Shut() { for (auto iter : mxTimers) { for (auto it : iter.second) { ARK_DELETE(it.second); } } mxTimers.clear(); memset(mxSlots, 0x0, sizeof(mxSlots)); } bool AddForverTimer(const std::string& name, const AFGUID& entity_id, uint32_t interval_time, TIMER_FUNCTOR_PTR callback) { AFTimerData* data = ARK_NEW AFTimerData(); memset(data, 0, sizeof(AFTimerData)); ARK_STRNCPY(data->name, name.c_str(), (name.length() > 16) ? 16 : name.length()); data->type = TIMER_TYPE_FOREVER; data->interval = interval_time; data->callback = callback; data->entity_id = entity_id; mxRegTimers.push_back(data); return true; } bool AddSingleTimer(const std::string& name, const AFGUID& entity_id, uint32_t interval_time, uint32_t count, TIMER_FUNCTOR_PTR callback) { AFTimerData* data = ARK_NEW AFTimerData(); memset(data, 0, sizeof(AFTimerData)); ARK_STRNCPY(data->name, name.c_str(), (name.length() > 16) ? 16 : name.length()); data->type = TIMER_TYPE_COUNT_LIMIT; data->count = std::max((uint32_t)1, count); data->interval = interval_time; data->callback = callback; data->entity_id = entity_id; mxRegTimers.push_back(data); return true; } bool RemoveTimer(const std::string& name) { //TODO:remove registered timer return RemoveTimerData(name); } bool RemoveTimer(const std::string& name, const AFGUID& entity_id) { //TODO:remove registered timer return RemoveTimerData(name, entity_id); } uint32_t FindLeftTime(const std::string& name, const AFGUID& entity_id) { //TODO: return 0; } protected: void UpdateTimer(int64_t now_time) { uint64_t passedSlot = (now_time - mnLastUpdateTime) / SLOT_TIME; if (passedSlot == 0) { return; } mnLastUpdateTime += passedSlot * SLOT_TIME; for (uint64_t i = 0; i < passedSlot; ++i) { mnNowSlot = (mnNowSlot + 1) % MAX_SLOT; UpdateSlotTimer(); } } void UpdateTimerReg() { if (mxRegTimers.empty()) { return; } for (auto data : mxRegTimers) { switch (data->type) { case TIMER_TYPE_FOREVER: AddSlotTimer(data, true); break; case TIMER_TYPE_COUNT_LIMIT: AddSlotTimer(data, false); break; default: ARK_ASSERT_NO_EFFECT(0); break; } } mxRegTimers.clear(); } AFTimerData* FindTimerData(const std::string& name, const AFGUID& entity_id) { auto iter = mxTimers.find(name); if (iter == mxTimers.end()) { return nullptr; } auto it = iter->second.find(entity_id); if (it == iter->second.end()) { return nullptr; } return it->second; } bool AddTimerData(const std::string& name, const AFGUID& entity_id, AFTimerData* timer_data) { auto iter = mxTimers.find(name); if (iter == mxTimers.end()) { std::map<AFGUID, AFTimerData*> tmp; iter = mxTimers.insert(std::make_pair(name, tmp)).first; } return iter->second.insert(std::make_pair(entity_id, timer_data)).second; } bool RemoveTimerData(const std::string& name) { auto iter = mxTimers.find(name); if (iter == mxTimers.end()) { return false; } for (auto it : iter->second) { AFTimerData* data = it.second; RemoveSlotTimer(data); ARK_DELETE(data); } iter->second.clear(); mxTimers.erase(iter); return true; } bool RemoveTimerData(const std::string& name, const AFGUID& entity_id) { auto iter = mxTimers.find(name); if (iter == mxTimers.end()) { return false; } auto it = iter->second.find(entity_id); if (it == iter->second.end()) { return false; } AFTimerData* data = it->second; RemoveSlotTimer(data); ARK_DELETE(data); iter->second.erase(it); if (iter->second.empty()) { mxTimers.erase(iter); } return true; } void AddSlotTimer(AFTimerData* timer_data, bool first) { if (first) { timer_data->rotation = 0; timer_data->slot = (mnNowSlot + 1) % MAX_SLOT; } else { uint32_t ticks = timer_data->interval / SLOT_TIME; timer_data->rotation = ticks / MAX_SLOT; timer_data->slot = ((ticks % MAX_SLOT) + mnNowSlot) % MAX_SLOT; } auto wheelData = mxSlots[timer_data->slot]; if (wheelData != nullptr) { timer_data->next = wheelData; wheelData->prev = timer_data; } mxSlots[timer_data->slot] = timer_data; } void RemoveSlotTimer(AFTimerData* timer_data) { auto* prev = timer_data->prev; if (prev != nullptr) { prev->next = timer_data->next; } auto* next = timer_data->next; if (next != nullptr) { next->prev = timer_data->prev; } if (timer_data == mxSlots[timer_data->slot]) { mxSlots[timer_data->slot] = next; } timer_data->prev = nullptr; timer_data->next = nullptr; } void UpdateSlotTimer() { std::list<AFTimerData*> doneDatas; auto timerData = mxSlots[mnNowSlot]; while (timerData != nullptr) { if (timerData->rotation > 0) { --timerData->rotation; } if (timerData->rotation == 0) { doneDatas.push_back(timerData); } timerData = timerData->next; } for (auto data : doneDatas) { RemoveSlotTimer(data); (*(data->callback))(data->name, data->entity_id); switch (data->type) { case TIMER_TYPE_FOREVER: AddSlotTimer(data, false); break; case TIMER_TYPE_COUNT_LIMIT: { --data->count; if (data->count == 0) { RemoveTimerData(data->name, data->entity_id); } else { AddSlotTimer(data, false); } } break; default: RemoveTimerData(data->name, data->entity_id); break; } } } private: uint32_t mnNowSlot; AFTimerData* mxSlots[MAX_SLOT]; uint64_t mnLastUpdateTime; std::map<std::string, std::map<AFGUID, AFTimerData*>> mxTimers; std::list<AFTimerData*> mxRegTimers; }; }
[ "362148418@qq.com" ]
362148418@qq.com
3f0200c9b26c2bc3838e992f551a33e0c77abce9
2426ae6b2205cceaee961e53685c74e01e9e8a2a
/Advanced_C++_Programming/20t2-cs6771-tut03-master/solutions/car.cpp
64e34b40d875d68be0946d41efdef19c455018fb
[ "Apache-2.0" ]
permissive
HeSixiang/UNSW
937e54eab653a3efdeaf4686f4089c2a25acd800
6f63ebed517eac29f303ca364ee764d55a9581f4
refs/heads/master
2023-03-06T04:26:48.035280
2021-02-16T06:04:56
2021-02-16T06:04:56
245,617,469
0
0
null
null
null
null
UTF-8
C++
false
false
374
cpp
#include "./car.h" int car::n_objects_ = 0; car::~car() noexcept { --n_objects_; } auto car::get_manufacturer() const -> const std::string& { return manufacturer_; } auto car::get_num_seats() const -> int { return num_seats_; } auto car::set_num_seats(int num_seats) -> void { num_seats_ = num_seats; } auto car::get_num_cars() -> int { return n_objects_; }
[ "z5280561@unsw.edu.au" ]
z5280561@unsw.edu.au
36a263858e5dad40b40b57a9955634f60a53e01a
c1626152963432aa221a4a9b0e4767a4608a51f7
/src/boost/lexical_cast/try_lexical_convert.hpp
52376742a32d98bd2e2e0184a28aed07a70cb5ce
[ "MIT" ]
permissive
107-systems/107-Arduino-BoostUnits
d2bffefc2787e99173797c9a89d47961718f9b03
f1a4dfa7bf2af78c422bf10ba0c30e2a703cb69b
refs/heads/main
2023-09-06T03:46:02.903776
2023-09-05T09:32:35
2023-09-05T09:32:35
401,328,494
0
0
MIT
2023-09-05T09:32:37
2021-08-30T12:03:20
C++
UTF-8
C++
false
false
9,125
hpp
// Copyright Kevlin Henney, 2000-2005. // Copyright Alexander Nasonov, 2006-2010. // Copyright Antony Polukhin, 2011-2021. // // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // what: lexical_cast custom keyword cast // who: contributed by Kevlin Henney, // enhanced with contributions from Terje Slettebo, // with additional fixes and suggestions from Gennaro Prota, // Beman Dawes, Dave Abrahams, Daryle Walker, Peter Dimov, // Alexander Nasonov, Antony Polukhin, Justin Viiret, Michael Hofmann, // Cheng Yang, Matthew Bradbury, David W. Birdsall, Pavel Korzh and other Boosters // when: November 2000, March 2003, June 2005, June 2006, March 2011 - 2014 #ifndef BOOST_LEXICAL_CAST_TRY_LEXICAL_CONVERT_HPP #define BOOST_LEXICAL_CAST_TRY_LEXICAL_CONVERT_HPP #include "boost/config.hpp" #ifdef BOOST_HAS_PRAGMA_ONCE # pragma once #endif #if defined(__clang__) || (defined(__GNUC__) && \ !(defined(__INTEL_COMPILER) || defined(__ICL) || defined(__ICC) || defined(__ECC)) && \ (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6))) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wuninitialized" #pragma GCC diagnostic ignored "-Wsign-conversion" #endif #include <string> #include "boost/type_traits/is_integral.hpp" #include "boost/type_traits/type_identity.hpp" #include "boost/type_traits/conditional.hpp" #include "boost/type_traits/is_same.hpp" #include "boost/type_traits/is_arithmetic.hpp" #include "boost/lexical_cast/detail/is_character.hpp" #include "boost/lexical_cast/detail/converter_numeric.hpp" #include "boost/lexical_cast/detail/converter_lexical.hpp" #include "boost/range/iterator_range_core.hpp" #include "boost/container/container_fwd.hpp" namespace boost { namespace detail { template<typename T> struct is_stdstring : boost::false_type {}; template<typename CharT, typename Traits, typename Alloc> struct is_stdstring< std::basic_string<CharT, Traits, Alloc> > : boost::true_type {}; // Sun Studio has problem with partial specialization of templates differing only in namespace. // We workaround that by making `is_booststring` trait, instead of specializing `is_stdstring` for `boost::container::basic_string`. template<typename T> struct is_booststring : boost::false_type {}; template<typename CharT, typename Traits, typename Alloc> struct is_booststring< boost::container::basic_string<CharT, Traits, Alloc> > : boost::true_type {}; template<typename Target, typename Source> struct is_arithmetic_and_not_xchars { typedef boost::integral_constant< bool, !(boost::detail::is_character<Target>::value) && !(boost::detail::is_character<Source>::value) && boost::is_arithmetic<Source>::value && boost::is_arithmetic<Target>::value > type; BOOST_STATIC_CONSTANT(bool, value = ( type::value )); }; /* * is_xchar_to_xchar<Target, Source>::value is true, * Target and Souce are char types of the same size 1 (char, signed char, unsigned char). */ template<typename Target, typename Source> struct is_xchar_to_xchar { typedef boost::integral_constant< bool, sizeof(Source) == sizeof(Target) && sizeof(Source) == sizeof(char) && boost::detail::is_character<Target>::value && boost::detail::is_character<Source>::value > type; BOOST_STATIC_CONSTANT(bool, value = ( type::value )); }; template<typename Target, typename Source> struct is_char_array_to_stdstring : boost::false_type {}; template<typename CharT, typename Traits, typename Alloc> struct is_char_array_to_stdstring< std::basic_string<CharT, Traits, Alloc>, CharT* > : boost::true_type {}; template<typename CharT, typename Traits, typename Alloc> struct is_char_array_to_stdstring< std::basic_string<CharT, Traits, Alloc>, const CharT* > : boost::true_type {}; // Sun Studio has problem with partial specialization of templates differing only in namespace. // We workaround that by making `is_char_array_to_booststring` trait, instead of specializing `is_char_array_to_stdstring` for `boost::container::basic_string`. template<typename Target, typename Source> struct is_char_array_to_booststring : boost::false_type {}; template<typename CharT, typename Traits, typename Alloc> struct is_char_array_to_booststring< boost::container::basic_string<CharT, Traits, Alloc>, CharT* > : boost::true_type {}; template<typename CharT, typename Traits, typename Alloc> struct is_char_array_to_booststring< boost::container::basic_string<CharT, Traits, Alloc>, const CharT* > : boost::true_type {}; template <typename Target, typename Source> struct copy_converter_impl { // MSVC fail to forward an array (DevDiv#555157 "SILENT BAD CODEGEN triggered by perfect forwarding", // fixed in 2013 RTM). #if !defined(BOOST_NO_CXX11_RVALUE_REFERENCES) && (!defined(BOOST_MSVC) || BOOST_MSVC >= 1800) template <class T> static inline bool try_convert(T&& arg, Target& result) { result = static_cast<T&&>(arg); // eqaul to `result = std::forward<T>(arg);` return true; } #else static inline bool try_convert(const Source& arg, Target& result) { result = arg; return true; } #endif }; } namespace conversion { namespace detail { template <typename Target, typename Source> inline bool try_lexical_convert(const Source& arg, Target& result) { typedef BOOST_DEDUCED_TYPENAME boost::detail::array_to_pointer_decay<Source>::type src; typedef boost::integral_constant< bool, boost::detail::is_xchar_to_xchar<Target, src >::value || boost::detail::is_char_array_to_stdstring<Target, src >::value || boost::detail::is_char_array_to_booststring<Target, src >::value || ( boost::is_same<Target, src >::value && (boost::detail::is_stdstring<Target >::value || boost::detail::is_booststring<Target >::value) ) || ( boost::is_same<Target, src >::value && boost::detail::is_character<Target >::value ) > shall_we_copy_t; typedef boost::detail::is_arithmetic_and_not_xchars<Target, src > shall_we_copy_with_dynamic_check_t; // We do evaluate second `if_` lazily to avoid unnecessary instantiations // of `shall_we_copy_with_dynamic_check_t` and improve compilation times. typedef BOOST_DEDUCED_TYPENAME boost::conditional< shall_we_copy_t::value, boost::type_identity<boost::detail::copy_converter_impl<Target, src > >, boost::conditional< shall_we_copy_with_dynamic_check_t::value, boost::detail::dynamic_num_converter_impl<Target, src >, boost::detail::lexical_converter_impl<Target, src > > >::type caster_type_lazy; typedef BOOST_DEDUCED_TYPENAME caster_type_lazy::type caster_type; return caster_type::try_convert(arg, result); } template <typename Target, typename CharacterT> inline bool try_lexical_convert(const CharacterT* chars, std::size_t count, Target& result) { BOOST_STATIC_ASSERT_MSG( boost::detail::is_character<CharacterT>::value, "This overload of try_lexical_convert is meant to be used only with arrays of characters." ); return ::boost::conversion::detail::try_lexical_convert( ::boost::iterator_range<const CharacterT*>(chars, chars + count), result ); } }} // namespace conversion::detail namespace conversion { // ADL barrier using ::boost::conversion::detail::try_lexical_convert; } } // namespace boost #if defined(__clang__) || (defined(__GNUC__) && \ !(defined(__INTEL_COMPILER) || defined(__ICL) || defined(__ICC) || defined(__ECC)) && \ (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6))) #pragma GCC diagnostic pop #endif #endif // BOOST_LEXICAL_CAST_TRY_LEXICAL_CONVERT_HPP
[ "cto@lxrobotics.com" ]
cto@lxrobotics.com
3c3f634aff6a928ca0a4e22245bd4132c158f703
763a9632d11e1936557a19452f62b1e1410af6b5
/a3-launch-170050077_170050081-master/src/gl_framework0.hpp
2ad729fdcd72c73756bb53e06c6bc634e4150dd1
[]
no_license
hari1500/CS475-Computer-Graphics-Assignments
ecc4d00057428c6b6777806cd17b95b30f26499c
255ae74d0d7b29476a943831ce44a5888f0d442f
refs/heads/main
2023-06-04T19:41:23.277957
2021-06-20T15:25:37
2021-06-20T15:25:37
378,674,243
0
0
null
null
null
null
UTF-8
C++
false
false
708
hpp
#ifndef _GL_FRAMEWORK_HPP_ #define _GL_FRAMEWORK_HPP_ #include <GL/glew.h> #include <GLFW/glfw3.h> #include <iostream> #include <cmath> #include <array> #include <fstream> #include <iterator> // Define a helpful macro for handling offsets into buffer objects #define BUFFER_OFFSET( offset ) ((GLvoid*) (offset)) namespace csX75 { //! Initialize GL State void initGL(void); //!GLFW Error Callback void error_callback(int error, const char* description); //!GLFW framebuffer resize callback void framebuffer_size_callback(GLFWwindow* window, int width, int height); //!GLFW keyboard callback void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods); }; #endif
[ "hari_personal@Haris-MacBook-Pro.local" ]
hari_personal@Haris-MacBook-Pro.local
ce41c1eb388e806e1e484ef159064f6aa1727e3b
7a24da1408ef55097098a415acdbe53043fc1f63
/src/kernel/arch/x86/32Bit/paging.cpp
dd641245b1a8570687785a99d70d6eb84aa833f1
[ "MIT" ]
permissive
jbw3/OS
4caeaaf2d097e195d614e2af7abf5bed3ab37c16
52026277e20f3f8d504b8094084ba883f1f462df
refs/heads/master
2021-03-22T02:08:51.126798
2018-10-07T03:20:33
2018-10-07T03:20:33
48,518,341
2
0
null
null
null
null
UTF-8
C++
false
false
4,377
cpp
#include <stdio.h> #include "kernellogger.h" #include "multiboot.h" #include "paging.h" #include "system.h" #include "utils.h" extern "C" void pageFault(const registers* regs) { klog.logError(PAGING_TAG, "Page fault!"); klog.logError(PAGING_TAG, "Error code: {}", regs->errCode); char msg[128]; int idx = 0; if ( (regs->errCode & PAGE_ERROR_USER) != 0 ) { idx += sprintf(msg + idx, "A user process "); } else { idx += sprintf(msg + idx, "A supervisory process "); } if ( (regs->errCode & PAGE_ERROR_WRITE) != 0 ) { idx += sprintf(msg + idx, "tried to write to "); } else { idx += sprintf(msg + idx, "tried to read from "); } if ( (regs->errCode & PAGE_ERROR_PRESENT) != 0 ) { idx += sprintf(msg + idx, "a page and caused a protection fault."); } else { idx += sprintf(msg + idx, "a non-present page."); } klog.logError(PAGING_TAG, msg); klog.logError(PAGING_TAG, "Address: {x0>8}", getRegCR2()); PANIC("Page fault!"); } void configPaging() { // register page fault handler registerIsrHandler(ISR_PAGE_FAULT, pageFault); } void mapPageTable(uint32_t* pageDir, uint32_t pageTableAddr, int pageDirIdx, bool user) { if (pageDirIdx < 0 || pageDirIdx >= 1024) { PANIC("Invalid page directory index."); } // add the page table to the page directory uint32_t pageDirEntry = 0; pageDirEntry |= pageTableAddr & PAGE_DIR_ADDRESS; // add new address pageDirEntry |= PAGE_DIR_READ_WRITE | PAGE_DIR_PRESENT; // set read/write and present bits if (user) { pageDirEntry |= PAGE_DIR_USER; // set user privilege } pageDir[pageDirIdx] = pageDirEntry; } void mapPage(uint32_t* pageTable, uint32_t virtualAddr, uint32_t physicalAddr, bool user) { // calculate the page table index int pageTableIdx = (virtualAddr >> 12) & PAGE_TABLE_INDEX_MASK; // get the page entry from the page table uint32_t pageTableEntry = pageTable[pageTableIdx]; // add the page address to the page table pageTableEntry &= ~PAGE_TABLE_ADDRESS; // clear previous address pageTableEntry |= physicalAddr & PAGE_TABLE_ADDRESS; // add new address pageTableEntry |= PAGE_TABLE_READ_WRITE | PAGE_TABLE_PRESENT; // set read/write and present bits if (user) { pageTableEntry |= PAGE_TABLE_USER; // set user privilege } pageTable[pageTableIdx] = pageTableEntry; } bool mapPage(int pageDirIdx, uint32_t* pageTable, uint32_t& virtualAddr, uint32_t physicalAddr, bool user) { for (int idx = 0; idx < PAGE_TABLE_NUM_ENTRIES; ++idx) { uint32_t entry = pageTable[idx]; if ( (entry & PAGE_TABLE_PRESENT) == 0 ) { uint32_t newEntry = physicalAddr & PAGE_TABLE_ADDRESS; // set address newEntry |= PAGE_TABLE_READ_WRITE | PAGE_TABLE_PRESENT; // set read/write and present bits if (user) { newEntry |= PAGE_TABLE_USER; // set user privilege } pageTable[idx] = newEntry; virtualAddr = (pageDirIdx << 22) | (idx << 12); return true; } } return false; } void unmapPage(uint32_t* pageTable, uint32_t virtualAddr) { // calculate the page table index int pageTableIdx = (virtualAddr >> 12) & PAGE_TABLE_INDEX_MASK; // clear the page table entry pageTable[pageTableIdx] = 0; // invalidate page in TLB invalidatePage(virtualAddr); } void mapModules(const multiboot_info* mbootInfo) { uint32_t modAddr = mbootInfo->mods_addr + KERNEL_VIRTUAL_BASE; for (uint32_t i = 0; i < mbootInfo->mods_count; ++i) { const multiboot_mod_list* module = reinterpret_cast<const multiboot_mod_list*>(modAddr); uint32_t startPageAddr = align(module->mod_start, PAGE_SIZE, false); // end page is the page after the last page the module is in uint32_t endPageAddr = align(module->mod_end, PAGE_SIZE); for (uint32_t pageAddr = startPageAddr; pageAddr < endPageAddr; pageAddr += PAGE_SIZE) { uint32_t virtualAddr = pageAddr + KERNEL_VIRTUAL_BASE; mapPage(getKernelPageTableStart(), virtualAddr, pageAddr); } modAddr += sizeof(multiboot_mod_list); } }
[ "jwilkes0011@gmail.com" ]
jwilkes0011@gmail.com
32bf9cd7799ee879c0e900a57a0a395f5528d768
04ad90dbafb2f075cce9409c8211722c79208be9
/ardPassiveLoggerNoTimeStaticIP.ino
7069370b6afeadc0018ad8cf4631796ae7408440
[]
no_license
jonsag/ardPassiveLoggerNoTimeStaticIP
a01fb2316a86452e952eb1e59ccc7df2e6eb0ad2
433ec8dc130f6fffcf4b951f80e6be239e879f0b
refs/heads/master
2021-08-10T10:05:26.516175
2017-11-12T13:10:57
2017-11-12T13:10:57
110,433,193
0
0
null
null
null
null
UTF-8
C++
false
false
15,513
ino
/* Define these variables down in the code: ------------------------------------ byte mac[] = -----the hex numbers on the sticker on your ethernet shield IPAddress ip( ----- the IP number you want yor arduino board to use if ( pollAge > 600000 ----- how long is the intervals between automatic reset of puls counting, milliseconds if (!tempsRead || tempAge > 60000 -----how often should we reset temps, milliseconds intervals - millis() - milliseconds: ------------------------------------ 10 seconds = 10000 1 min = 60000 5 min = 300000 10 min = 600000 1 hour = 3600000 1 day = 86400000 1 week = 604800000 LEDs ------------------------------------ YELLOW - discovering or reading temp sensors GREEN - activity on internet interface RED - pulse recieved */ #include <SPI.h> // ethernet libraries #include <Dhcp.h> #include <Dns.h> #include <Ethernet.h> #include <EthernetServer.h> //#include <EthernetUdp.h> #include <OneWire.h> // oneWire libraries #include <DallasTemperature.h> #include <util.h> //#include <Time.h> // time library ///////////////////// ethernet settings byte mac[] = { 0x90, 0xA2, 0xDA, 0x0C, 0x00, 0x76 }; // MAC address, printed on a sticker on the shield IPAddress ip(192,168,10,10); // ethernet shields wanted IP //IPAddress gateway(192,168,10,1); // internet access via router //IPAddress subnet(255,255,255,0); //subnet mask EthernetServer server(80); // this arduinos web server port String readString; // string read from servers interface ///////////////////// oneWire settings #define ONE_WIRE_BUS 2 // oneWire bus bin OneWire oneWire(ONE_WIRE_BUS); // setup oneWire instance to communicate with any OneWire devices DallasTemperature sensors(&oneWire); // pass our oneWire reference to Dallas Temperature byte numberOfSensors; // will store how many sensors we have float tempValue[] = { // will store the temps 0, 1, 2, 3}; boolean tempsRead = false; // will be true after first temp reading byte present = 0; byte data[12]; byte addr[8]; byte count = 0; ///////////////////// set pin numbers: const int pinPulse = 4; // number of the pin connected to the photo transistor const int yellowPinTemp = 7; // number of the yellow LED pin, status const int greenPinNetwork = 8; // number of the green LED pin, polled const int redPinPulse = 9; // number of the red LED pin, pulse recieved ///////////////////// analog inputs for the current clamps const int phase[] = { A2,A3,A4}; ///////////////////// holds various current values double displayedCurrent[] = { // the displayed value on the web page 1, 2, 3}; double ackDisplayedCurrent[] = { // all reads ackumulated 1, 2, 3}; double polledCurrent[] = { // the average current between each poll 1, 2, 3}; double ackPolledCurrent[] = { // all averages ackumulated 1, 2, 3}; int readAverageCounter = 200; // counter for how many readings should be averaged ///////////////////// variables int pulseButtonState = 0; // variable for reading pulse button status int lastPulseButtonState = 0; // saves pulse buttons previous state byte pulseState = 0; int lastPulseState = 0; int syncButtonState = 0; // variable for reading sync button status int ledStateYellow = LOW; // ledState holds the LED outputs int ledStateGreen = LOW; int ledStateRed = LOW; boolean blinkRed = false; // blink the LEDs boolean blinkGreen = false; boolean blinkYellow = false; int blinkRedCounter = 0; // counters for blinks of the LEDs int blinkGreenCounter = 0; int blinkYellowCounter = 0; int blinkYellowOffCounter = 0; ///////////////////// times unsigned long currentMillis = 000000; // will store millis() unsigned long pollMillis = 000000; // will store last time resetInterval was reset unsigned long pollAge = 000000; // how long since last poll unsigned long tempsMillis = 000000; // will store last time temps was read unsigned long tempAge = 000000; // how long since the temps was read unsigned int pulsesLastPoll = 0; // various pulse counters, 1 pulse = 1/1000 kwh unsigned int pulses = 0; ///////////////////// counters int i = 0; // various purposes byte phaseCount = 0; // counting throug the 3 phases byte tempsCounter = 0; // counter for displaying values on web page int currentDisplayedCounter = 0; // counter for displayed current average unsigned long currentPollCounter = 0; // counter för current interval average unsigned int readCounter = 0; // counter for how often to read currents boolean readTemps = false; //////////////////////////////////// setup //////////////////////////////////// void setup() { Serial.begin(9600); // start serial communication Serial.println("js_arduino_passive_logger_no_time_static_ip"); // display this sketchs name Serial.println("Started serial communication"); Serial.println("Initiating in/outputs..."); pinMode(pinPulse, INPUT); pinMode(yellowPinTemp, OUTPUT); // initialize the LED pins as outputs pinMode(greenPinNetwork, OUTPUT); pinMode(redPinPulse, OUTPUT); Serial.println("Starting 1-wire sensors..."); sensors.begin(); // start up the oneWire library Serial.println("Discovering and counting sensors..."); numberOfSensors = discoverOneWireDevices(); // count sensors Serial.println("Waiting 5 seconds..."); delay(5000); //important on linux a serial port can lock up otherwise Serial.println("Starting ethernet..."); Ethernet.begin(mac, ip); Serial.println("Starting web server..."); server.begin(); //start arduinos web server Serial.println("Starting..."); } //////////////////////////////////// main loop //////////////////////////////////// void loop() { ///////////////////// checking some times currentMillis = millis(); // millis right now pollAge = (currentMillis - pollMillis); // how much time elapsed since last log write tempAge = (currentMillis - tempsMillis); // how much time elapsed since last temp reading ///////////////////// read digital inputs pulseState = digitalRead(pinPulse); // read pulse input ///////////////////// read analog inputs if (!readTemps) { readCurrents(); } ///////////////////// check for pulse if (pulseState != lastPulseState) { // light red LED if button is pressed if (pulseState == HIGH) { // if the current state is HIGH then the button went from off to on pulses++; // +1 on puls counter Serial.print("Pulse recieved, pulses this interval is now "); Serial.println(pulses); blinkRed = true; } } lastPulseState = pulseState; // save pulse button state till next loop ///////////////////// check if it's time to reset pulses if ( pollAge > 600000) { pollMillis = currentMillis; Serial.println("---Resetting pulses"); pulsesLastPoll = pulses; pulses = 0; } ///////////////////// check if we should read temps if (!tempsRead || tempAge > 60000) { // read temperatures if we haven't before, or if it's time to do so readTemps = true; getTemperatures(); } ///////////////////// blink LEDs blinkLEDs(); ///////////////////// webserver presentWebPage(); } // end of main loop /////////////////////////////// discover sensors //////////////////////////////// int discoverOneWireDevices(void) { digitalWrite(yellowPinTemp, HIGH); // turn yellow LED on while(oneWire.search(addr)) { Serial.print("Found \'1-Wire\' device with address: "); for( i = 0; i < 8; i++) { Serial.print("0x"); if (addr[i] < 16) { Serial.print('0'); } Serial.print(addr[i], HEX); if (i < 7) { Serial.print(", "); } } if ( OneWire::crc8( addr, 7) != addr[7]) { Serial.println("CRC is not valid!"); return 0; } Serial.println(); count++; } oneWire.reset_search(); return count; digitalWrite(yellowPinTemp, LOW); // turn yellow LED off } /////////////////////////////// request temperatures /////////////////////////////// void getTemperatures(void) { digitalWrite(yellowPinTemp, HIGH); // turn yellow LED on tempsMillis = currentMillis; // save the last time you synced time Serial.println("---Requesting temperatures..."); sensors.requestTemperatures(); // Send the command to get temperatures for(i=0; i < numberOfSensors; i++) { // read each of our sensors and print the value Serial.print("Temperature for Device "); Serial.print( i ); Serial.print(" is: "); tempValue[i] = sensors.getTempCByIndex(i); Serial.println(tempValue[i]); } tempsRead = true; digitalWrite(yellowPinTemp, LOW); // turn yellow LED off readTemps = false; } /////////////////////////////// present webpage /////////////////////////////// void presentWebPage(void) { EthernetClient client = server.available(); // listen for incoming clients if (client) { digitalWrite(greenPinNetwork, HIGH); // turn green LED on while (client.connected()) { if (client.available()) { char c = client.read(); if (readString.length() < 100) { //read char by char HTTP request readString += c; //store characters to string } if (c == '\n') { //if HTTP request has ended Serial.println(readString); //print to serial monitor for debuging //now output HTML data header if(readString.indexOf('?') >=0) { //don't send new page client.println("HTTP/1.1 204 JS Arduino"); client.println(); client.println(); } else { // headers client.println("HTTP/1.1 200 OK"); //send new page client.println("Content-Type: text/html"); client.println(); client.println("<HTML>"); client.println("<HEAD>"); client.println("<TITLE>Arduino logger</TITLE>"); client.println("</HEAD>"); client.println("<BODY>"); client.println("<H1>JS temp and power consumption logger</H1>"); // currents client.println("<br>"); for(phaseCount=0; phaseCount <= 2; phaseCount++) { client.print("Current phase "); client.print(phaseCount + 1); client.print(": "); client.print(displayedCurrent[phaseCount]); //client.print(current[i]); client.println(" A<br>"); } client.println("<br>"); for(phaseCount=0; phaseCount <= 2; phaseCount++) { client.print("Current average phase "); client.print(phaseCount + 1); client.print(": "); client.print(polledCurrent[phaseCount]); client.println(" A<br>"); } client.print("Based on "); client.print(currentPollCounter); client.println(" values<br>"); client.print("Polled "); client.print(pollAge/1000); client.println(" seconds ago"); client.println("<br><br>"); // temps for(tempsCounter=0; tempsCounter < numberOfSensors; tempsCounter++) { client.print("Temperature sensor "); client.print(tempsCounter); client.print(": "); client.print(tempValue[tempsCounter]); client.println(" C<br>"); } client.print("Temps read "); client.print(tempAge/1000); client.println(" seconds ago<br>"); client.println("<br>"); // pulses client.print("Pulses last poll: "); client.print(pulsesLastPoll); client.println("<br>"); client.print("Pulses since last poll: "); client.print(pulses); client.println("<br>"); client.println("<br>"); client.println("<a href=\"/?pulse\" target=\"inlineframe\">Send pulse</a><br>"); client.println("<IFRAME name=inlineframe style=\"display:none\" >"); client.println("</IFRAME><br>"); client.println("</BODY>"); client.println("</HTML>"); } ///////////////////// check if we should add a pulse if(readString.indexOf("pulse") > 0) { //checks for click simulating a pulse pulses++; Serial.print("Pulse from webpage, pulses this interval is now "); Serial.println(pulses); blinkRed = true; } ///////////////////// check if this is a poll if(readString.indexOf("pollReset") > 0) { //checks for poll reset //Serial.println("---Recieved pollReset, will reset pulses and average current values"); Serial.println("---Recieved pollReset"); pollMillis = currentMillis; pulsesLastPoll = pulses; pulses =0; currentPollCounter = 0; for(phaseCount = 0; phaseCount <= 2; phaseCount++) { ackPolledCurrent[phaseCount] = 0; } } ///////////////////// check if we should read temps if(readString.indexOf("readTemps") > 0) { //will read 1-wire temps getTemperatures(); } readString=""; //clearing string for next read delay(100); client.stop(); //stopping client digitalWrite(greenPinNetwork, HIGH); // turn green LED on } } } } } // end of web page /////////////////////////////// blink LEDs /////////////////////////////// void blinkLEDs(void) { if (blinkYellow && blinkYellowCounter < 20) { blinkYellowCounter++; digitalWrite(yellowPinTemp, HIGH); } else { blinkYellow = false; blinkYellowCounter = 0; digitalWrite(yellowPinTemp, LOW); } if (!blinkYellow && blinkYellowOffCounter < 10000) { blinkYellowOffCounter++; } else { blinkYellow = true; blinkYellowOffCounter = 0; } if (blinkGreen && blinkGreenCounter < 20) { blinkGreenCounter++; digitalWrite(greenPinNetwork, HIGH); } else { blinkGreen = false; blinkGreenCounter = 0; digitalWrite(greenPinNetwork, LOW); } if (blinkRed && blinkRedCounter < 20) { blinkRedCounter++; digitalWrite(redPinPulse, HIGH); } else { blinkRed = false; blinkRedCounter = 0; digitalWrite(redPinPulse, LOW); } } /////////////////////////////// read currents /////////////////////////////// void readCurrents(void) { if (currentDisplayedCounter < readAverageCounter) { for(phaseCount = 0; phaseCount <= 2; phaseCount++) { ackDisplayedCurrent[phaseCount] = ackDisplayedCurrent[phaseCount] + abs((analogRead(phase[phaseCount]) - 511) * 0.33); } currentDisplayedCounter++; } else { Serial.print("Reading #"); Serial.print(currentPollCounter); Serial.print(" "); for(phaseCount = 0; phaseCount <= 2; phaseCount++) { displayedCurrent[phaseCount] = ackDisplayedCurrent[phaseCount] / readAverageCounter; // set the displayed current value Serial.print(phaseCount); Serial.print(": "); Serial.print(displayedCurrent[phaseCount]); Serial.print(" A "); ackDisplayedCurrent[phaseCount] = 0; } Serial.println(); currentDisplayedCounter = 0; currentPollCounter++; for(phaseCount = 0; phaseCount <= 2; phaseCount++) { ackPolledCurrent[phaseCount] = ackPolledCurrent[phaseCount] + displayedCurrent[phaseCount]; // calculate an average for interval polledCurrent[phaseCount] = ackPolledCurrent[phaseCount] / currentPollCounter; // set the displayed current value } } }
[ "jon@HP-Pavilion-15" ]
jon@HP-Pavilion-15
00c23572bdf01a23e7e1e2fae3fefb29584614ec
904497b803fa3313d69a90be91d5ee51797bbc3d
/StrictlyCode_HVH/StrictlyCode/SqchSDK/SDK/IMDLCache.h
8bb1d00f6b99288dc693ea4a4247474904117bf3
[]
no_license
Shaxzy/strictlycode
f6bcf42505606e422eb88c371060933805bfe2be
c7aca1eeaec56b127303d27b1be34d0f2b3a566d
refs/heads/master
2020-03-18T01:34:17.800323
2018-05-19T13:58:32
2018-05-19T13:58:32
134,148,244
1
0
null
null
null
null
UTF-8
C++
false
false
88
h
#pragma once namespace NSDK { typedef unsigned short MDLHandle_t; class IMDLCache; }
[ "nullflex@gmail.com" ]
nullflex@gmail.com
b79d254b0fa5e43dfca4f148475a73b89fdc2c06
48d07617c3d078f122c3c4ee8953f99f1bb88709
/Greedy/Dijkstra.cpp
ab19044b1c8eb7bc5ec51f995a7a00bd2a13d236
[]
no_license
lijiyao111/Algorithms
871fe788e65deb0a8fd6a28ec9ae293522e4bd3d
22941ce23307d7b18e99cdb396efe9767702dd1b
refs/heads/master
2021-04-30T16:41:53.808474
2017-03-03T21:17:10
2017-03-03T21:17:10
80,122,775
1
0
null
null
null
null
UTF-8
C++
false
false
2,237
cpp
#include <stdio.h> #include <cstring> #include <limits.h> #include "../array_utils.h" // Number of vertices in the graph #define V 9 // const bool True=1, False=0; // just use true, false // A utility function to find the vertex with minimum distance value, from // the set of vertices not yet included in shortest path tree int minDistance(int dist[], bool sptSet[]) { // Initialize min value int min = INT_MAX, min_index; for (int v = 0; v < V; v++) if (sptSet[v] == false && dist[v] <= min) min = dist[v], min_index = v; return min_index; } // A utility function to print the constructed distance array int printSolution(int dist[]) { printf("Vertex Distance from Source\n"); for (int i = 0; i < V; i++) printf("%d \t\t %d\n", i, dist[i]); } int countSet(bool sptSet[]){ int count=0; for(int i=0; i<V; ++i){ if(sptSet[i]==true) count++; } return count; } void dijkstra(int graph[V][V],int s){ int dist[V]; bool sptSet[V]; for(int i=0; i<V; ++i){ dist[i]=INT_MAX; sptSet[i]=false; } dist[s]=0; sptSet[s]=true; for(int i=0; i<V; ++i){ if(graph[s][i]!=0) dist[i]=graph[s][i]; } // JL::print_array1d(dist,V); // JL::print_array1d(sptSet,V); while(countSet(sptSet)<V){ int idx=minDistance(dist, sptSet); sptSet[idx]=true; for(int i=0; i<V; ++i){ if(graph[idx][i]!=0) if(dist[i]>dist[idx]+graph[idx][i]) dist[i]=dist[idx]+graph[idx][i]; } } JL::print_array1d(dist,V); JL::print_array1d(sptSet,V); printSolution(dist); } // driver program to test above function int main() { /* Let us create the example graph discussed above */ int graph[V][V] = {{0, 4, 0, 0, 0, 0, 0, 8, 0}, {4, 0, 8, 0, 0, 0, 0, 11, 0}, {0, 8, 0, 7, 0, 4, 0, 0, 2}, {0, 0, 7, 0, 9, 14, 0, 0, 0}, {0, 0, 0, 9, 0, 10, 0, 0, 0}, {0, 0, 4, 14, 10, 0, 2, 0, 0}, {0, 0, 0, 0, 0, 2, 0, 1, 6}, {8, 11, 0, 0, 0, 0, 1, 0, 7}, {0, 0, 2, 0, 0, 0, 6, 7, 0} }; dijkstra(graph, 0); return 0; }
[ "jiyao.lee@gmail.com" ]
jiyao.lee@gmail.com
364f459a3cc2ba4ccb02c56a7135be4011f2660c
1742cd526f243de44a84769c07266c473648ecd6
/uri/1021.cpp
3ff33aab4f31c981cc4b6a839a6959ef01d900fd
[]
no_license
filipeabelha/gym-solutions
0d555f124fdb32508f6406f269a67eed5044d9c6
4eb8ad60643d7923780124cba3d002c5383a66a4
refs/heads/master
2021-01-23T05:09:38.962238
2020-11-29T07:14:31
2020-11-29T07:14:31
86,275,942
2
0
null
null
null
null
UTF-8
C++
false
false
1,059
cpp
#include <bits/stdc++.h> int main () { double n; scanf("%lf", &n); int n100 = n / 100; n -= 100*n100; int n50 = n / 50; n -= 50*n50; int n20 = n / 20; n -= 20*n20; int n10 = n / 10; n -= 10*n10; int n5 = n / 5; n -= 5*n5; int n2 = n / 2; n -= 2*n2; int m1 = n / 1; n -= 1*m1; int m50 = n / 0.50; n -= 0.50*m50; int m25 = n / 0.25; n -= 0.25*m25; int m10 = n / 0.10; n -= 0.10*m10; int m05 = n / 0.05; n -= 0.05*m05; float k = 100*n; int m01 = k; printf("NOTAS:\n%d nota(s) de R$ 100.00\n%d nota(s) de R$ 50.00\n%d nota(s) de R$ 20.00\n%d nota(s) de R$ 10.00\n%d nota(s) de R$ 5.00\n%d nota(s) de R$ 2.00\nMOEDAS:\n%d moeda(s) de R$ 1.00\n%d moeda(s) de R$ 0.50\n%d moeda(s) de R$ 0.25\n%d moeda(s) de R$ 0.10\n%d moeda(s) de R$ 0.05\n%d moeda(s) de R$ 0.01\n", n100, n50, n20, n10, n5, n2, m1, m50, m25, m10, m05, m01); return 0; }
[ "me@filipeabelha.com" ]
me@filipeabelha.com
818a22f7f68ceeda61e85742b25e19deb34da18e
57040e855ec1d81b8e6ae3d9db8cbecc1bb0a0e2
/ACM/Unidirectional TSP.cpp
5c2b889ffbc9541d86642d1cfc495865b02f7b3e
[]
no_license
TRLVMMR/algorithm
32f2a06fef0228c98766bb4a19895eed737d2602
b11f4096f234efe0473e4adc096a02e0ef1e4fa7
refs/heads/master
2020-03-18T17:36:41.174465
2018-12-02T13:49:25
2018-12-02T13:49:25
135,039,099
0
0
null
null
null
null
GB18030
C++
false
false
1,024
cpp
#include<stdio.h> #include<algorithm> #define INF 9999999 using namespace std; struct Cur { int x; int y; }; int a[100][100]; int dp[100][100]; int next[100][100]; int main() { int n, m; scanf("%d %d", m, n); for(int i = 0; i < m; i++) { for(int j = 0; j < n; j++) { scanf("%d",&a[i][j]); } } int ans = INF, first = 0;//fist是第一个节点 //递推要逆序,保证最优解无后效性 for(int j = n-1; j >= 0; j--) { for(int i = 0; i < m; i++) { if(j == n-1) dp[i][j] = a[i][j]; int dir[3] = {i, i-1, i+1}; //最上面的上一行是最下面,最下面的下一行是最上面 if(i == 0) dir[1] = m-1; if(i == m-1) dir[2] = 0; sort(dir, dir+3); //更新dp dp[i][j] = INF; for(int k = 0; k < 3; k++) { int temp = dp[dir[k]][j+1] + a[i][j]; if(temp < dp[i][j]) { dp[i][j] = temp; next[i][j] = dir[k]; } } } if(j == 0 && dp[i][j] < ans) { ans = dp[i][j]; first = i; } } return 0; }
[ "735029684@qq.com" ]
735029684@qq.com
109113905e15692369565f36f34164beb5a3c116
95324c309a940681d6717217b8272b7c627e258e
/src/PacketGenerator.cc
2aa9e5a3974393c2f859a354ea3f8467600b5aad
[]
no_license
rotsla/Wireless_Communication_Simulation
bc18675a9f1e16f08861359cacc2b570eab15b8b
3112cfe149aadb04de9eb4eca8d6f6c7f8ee96c3
refs/heads/master
2021-07-07T10:56:33.539537
2017-10-03T07:28:00
2017-10-03T07:28:00
105,740,944
0
0
null
2017-10-04T07:24:58
2017-10-04T07:12:43
C++
UTF-8
C++
false
false
2,138
cc
#include <omnetpp.h> #include <stdio.h> #include <string.h> #include <iostream> using namespace omnetpp; #include "AppMessage_m.h" class PacketGenerator : public cSimpleModule { public: PacketGenerator(); ~PacketGenerator(); protected: double iatDistribution; int messageSize; int seqno; int senderId; virtual void initialize(); virtual void handleMessage(cMessage *msg); AppMessage *generateMessage(); }; Define_Module(PacketGenerator); PacketGenerator::PacketGenerator() {} PacketGenerator::~PacketGenerator() { } void PacketGenerator::initialize() { seqno = 0; iatDistribution = par("iatDistribution"); messageSize = par("messageSize"); senderId = getParentModule()->par("nodeIdentifier");//from TransmitterNode's identifier scheduleAt(simTime() + iatDistribution, new cMessage("SCHEDULE"));// sends the message to itself for simulating inter-generation time } void PacketGenerator::handleMessage(cMessage *msg) { if (dynamic_cast<AppMessage*>(msg))// check the type of the msg is AppMessage or not { delete msg;// discard AppMessage from MAC } else { if (strcmp(msg->getName(), "SCHEDULE") == 0)//from PacketGenerator itself { AppMessage * appMsg = generateMessage();// create a new AppMessage send(appMsg, "gate$o");// send the message scheduleAt(simTime() + iatDistribution, new cMessage("SCHEDULE"));// schedule the next transmission } delete msg; } } AppMessage *PacketGenerator::generateMessage() { simtime_t timeStamp = simTime();//current simulation time int sequenceNumber = seqno++;//sequence id++ int msgSize = messageSize; char msgname[32]; snprintf(msgname, 32, "sender=%d seq=%d ts=%f", senderId, sequenceNumber, timeStamp.dbl()); // generate message name include info. AppMessage * msg = new AppMessage(msgname); msg->setTimeStamp(timeStamp); msg->setSenderId(senderId); msg->setSequenceNumber(sequenceNumber); msg->setMsgSize(msgSize); return msg; }
[ "yxzhjason@gmail.com" ]
yxzhjason@gmail.com
e905a773e606da5f5364b2082b060e7d6ea53f50
3ab9c539c7069dfc8e40173f2817031eae6ae98d
/src/tests/test_misc.cxx
97dcc57f664140bf02f99cf03ac100022c1b459e
[ "MIT" ]
permissive
DerThorsten/multi_array
e6dd5f89bf5b45e84548d64bbfc7398c763d8293
658bfb6c4ea83c3f53525e056cb972569cdeb185
refs/heads/master
2020-04-05T13:33:15.302915
2017-07-15T20:11:08
2017-07-15T20:11:08
94,878,859
0
0
null
2017-07-15T20:11:08
2017-06-20T10:22:14
C++
UTF-8
C++
false
false
7,831
cxx
#include "doctest.h" #include <iostream> #include <memory> #include <type_traits> #include "multi_array/multi_array_factories.hxx" #include "multi_array/multi_array.hxx" #include "multi_array/meta.hxx" #include "multi_array/runtime_check.hxx" TEST_SUITE_BEGIN("Misc"); TEST_CASE( "[Factories] -- arange]" ) { namespace ma = multi_array; SUBCASE("integer a"){ auto a = ma::arange(3); REQUIRE_EQ(a.dimension(),1); REQUIRE_EQ(a.size(),3); REQUIRE_EQ(a(0),0); REQUIRE_EQ(a(1),1); REQUIRE_EQ(a(2),2); } SUBCASE("integer b"){ auto a = ma::arange(3,7); REQUIRE_EQ(a.dimension(),1); REQUIRE_EQ(a.size(),4); REQUIRE_EQ(a(0),3); REQUIRE_EQ(a(1),4); REQUIRE_EQ(a(2),5); REQUIRE_EQ(a(3),6); } SUBCASE("integer c"){ auto a = ma::arange(3,7,2); REQUIRE_EQ(a.dimension(),1); REQUIRE_EQ(a.size(),2); REQUIRE_EQ(a(0),3); REQUIRE_EQ(a(1),5); } SUBCASE("float a"){ auto a = ma::arange(3.0f); REQUIRE_EQ(a.dimension(),1); REQUIRE_EQ(a.size(),3); REQUIRE_EQ(a(0),doctest::Approx(0.0f)); REQUIRE_EQ(a(1),doctest::Approx(1.0f)); REQUIRE_EQ(a(2),doctest::Approx(2.0f)); } SUBCASE("float b"){ auto a = ma::arange(3.0, 7.0); REQUIRE_EQ(a.dimension(),1); REQUIRE_EQ(a.size(),4); REQUIRE_EQ(a(0),doctest::Approx(3.0)); REQUIRE_EQ(a(1),doctest::Approx(4.0)); REQUIRE_EQ(a(2),doctest::Approx(5.0)); REQUIRE_EQ(a(3),doctest::Approx(6.0)); } SUBCASE("float c"){ auto a = ma::arange(3.0, 7.0, 2.0); REQUIRE_EQ(a.dimension(),1); REQUIRE_EQ(a.size(),2); REQUIRE_EQ(a(0),doctest::Approx(3.0)); REQUIRE_EQ(a(1),doctest::Approx(5.0)); } SUBCASE("float d"){ auto a = ma::arange(0.0, 1.0, 0.3); REQUIRE_EQ(a.dimension(),1); REQUIRE_EQ(a.size(),4); REQUIRE_EQ(a(0),doctest::Approx(0.0)); REQUIRE_EQ(a(1),doctest::Approx(0.3)); REQUIRE_EQ(a(2),doctest::Approx(0.6)); REQUIRE_EQ(a(3),doctest::Approx(0.9)); } } TEST_CASE( "[Shape] -- [detail_multi_array::dot()]" ) { SUBCASE("0D Shape"){ auto s = multi_array::shape(); REQUIRE_EQ(s.size(),0); } SUBCASE("1D Shape"){ auto s = multi_array::shape(2); REQUIRE_EQ(s.size(),1); REQUIRE_EQ(s[0],2); } SUBCASE("3D Shape mixed types rrefs"){ auto s = multi_array::shape(int(2),char(4),uint16_t(6)); REQUIRE_EQ(s.size(),3); REQUIRE_EQ(s[0],2); REQUIRE_EQ(s[1],4); REQUIRE_EQ(s[2],6); } SUBCASE("3D Shape same type rrefs"){ auto s = multi_array::shape(2,4,6); REQUIRE_EQ(s.size(),3); REQUIRE_EQ(s[0],2); REQUIRE_EQ(s[1],4); REQUIRE_EQ(s[2],6); } SUBCASE("4D Shape mixed types lref/cref"){ const auto s0 = int(4); auto s2 = uint16_t(1); auto s = multi_array::shape(s0,char(4), s2); REQUIRE_EQ(s.size(),3); REQUIRE_EQ(s[0],4); REQUIRE_EQ(s[1],4); REQUIRE_EQ(s[2],1); } } TEST_CASE( "[Shape] -- [Shape::countNegativeEntries()]" ) { SUBCASE("1D Shape"){ auto s = multi_array::shape(-1); REQUIRE_EQ(s.size(),1); const auto nNeg = s.countNegativeEntries(); REQUIRE_EQ(nNeg,1); } } TEST_CASE( "[Shape] -- [Shape::makeShape()]" ) { SUBCASE("1D Shape"){ auto sa = multi_array::shape(-1); auto s = sa.makeShape(6); REQUIRE_EQ(s.size(),1); REQUIRE_EQ(s[0], 6); } } TEST_CASE( "[Strides] " ) { SUBCASE("copy strides"){ auto shape = multi_array::shape(3); auto strides = multi_array::detail_multi_array::cOrderStrides(shape); REQUIRE_EQ(strides[0],1); multi_array::Strides<1> s = strides; REQUIRE_EQ(s[0],1); } } TEST_CASE( "2D dot -- [detail_multi_array::dot()]" ) { multi_array::Shape<2> shape; shape[0] = 2; shape[1] = 3; auto strides = multi_array::detail_multi_array::cOrderStrides(shape); { auto i = multi_array::detail_multi_array::dot(strides, 0,0); REQUIRE(i==0); } { auto i = multi_array::detail_multi_array::dot(strides, 0,1); REQUIRE(i==1); } { auto i = multi_array::detail_multi_array::dot(strides, 0,2); REQUIRE(i==2); } { auto i = multi_array::detail_multi_array::dot(strides, 1,0); REQUIRE(i==3); } { auto i = multi_array::detail_multi_array::dot(strides, 1,1); REQUIRE(i==4); } { auto i = multi_array::detail_multi_array::dot(strides, 1,2); REQUIRE(i==5); } } TEST_CASE( "2D cOrderStrides -- [detail_multi_array::cOrderStrides()]" ) { multi_array::Shape<2> shape; shape[0] = 20; shape[1] = 30; auto strides = multi_array::detail_multi_array::cOrderStrides(shape); REQUIRE(strides[0] == 30); REQUIRE(strides[1] == 1); } TEST_CASE( "3D cOrderStrides -- [detail_multi_array::cOrderStrides()]" ) { multi_array::Shape<3> shape; shape[0] = 2; shape[1] = 3; shape[2] = 4; auto strides = multi_array::detail_multi_array::cOrderStrides(shape); REQUIRE(strides[0] == 12); REQUIRE(strides[1] == 4); REQUIRE(strides[2] == 1); } TEST_CASE( "4D cOrderStrides with Singleton -- [detail_multi_array::cOrderStrides()]" ) { SUBCASE("1 Singleton") { multi_array::Shape<4> shape; shape[0] = 2; shape[1] = 1; shape[2] = 4; shape[3] = 5; auto strides = multi_array::detail_multi_array::cOrderStrides(shape); REQUIRE(strides[0] == 20); REQUIRE(strides[1] == 20); REQUIRE(strides[2] == 5); REQUIRE(strides[3] == 1); } SUBCASE("Begin Singleton") { multi_array::Shape<4> shape; shape[0] = 1; shape[1] = 2; shape[2] = 3; shape[3] = 4; auto strides = multi_array::detail_multi_array::cOrderStrides(shape); REQUIRE(strides[0] == 24); REQUIRE(strides[1] == 12); REQUIRE(strides[2] == 4); REQUIRE(strides[3] == 1); } SUBCASE("Begin Singletons") { multi_array::Shape<4> shape; shape[0] = 1; shape[1] = 1; shape[2] = 3; shape[3] = 4; auto strides = multi_array::detail_multi_array::cOrderStrides(shape); REQUIRE(strides[0] == 12); REQUIRE(strides[1] == 12); REQUIRE(strides[2] == 4); REQUIRE(strides[3] == 1); } SUBCASE("Middle Singletons") { multi_array::Shape<4> shape; shape[0] = 2; shape[1] = 1; shape[2] = 1; shape[3] = 4; auto strides = multi_array::detail_multi_array::cOrderStrides(shape); REQUIRE(strides[0] == 4); REQUIRE(strides[1] == 4); REQUIRE(strides[2] == 4); REQUIRE(strides[3] == 1); } SUBCASE("End Singletons") { multi_array::Shape<4> shape; shape[0] = 3; shape[1] = 2; shape[2] = 1; shape[3] = 1; auto strides = multi_array::detail_multi_array::cOrderStrides(shape); REQUIRE(strides[0] == 2); REQUIRE(strides[1] == 1); REQUIRE(strides[2] == 1); REQUIRE(strides[3] == 1); } SUBCASE("Only Singletons") { multi_array::Shape<4> shape; shape[0] = 1; shape[1] = 1; shape[2] = 1; shape[3] = 1; auto strides = multi_array::detail_multi_array::cOrderStrides(shape); REQUIRE(strides[0] == 1); REQUIRE(strides[1] == 1); REQUIRE(strides[2] == 1); REQUIRE(strides[3] == 1); } } TEST_SUITE_END();
[ "thorsten.beier@iwr.uni-heidelberg.de" ]
thorsten.beier@iwr.uni-heidelberg.de
e48da5c9274aba432337c1157f58d597bbd844a3
b59630ef940a2f3977c5bab63b971a3466ba93e1
/UnifiedMapEditor/Spriteeditor.h
ff6394bb98fa78bf3f6cc1c832d8e5bc41769e35
[]
no_license
curvi/Unified_Map_Editor
e88177cdd4f7693c712bbb7fbb453d1b6bfd1673
365f287860d3e2763610247f6ea7a2e7db2ae576
refs/heads/master
2021-06-04T11:39:32.665593
2016-09-12T08:35:12
2016-09-12T08:35:12
8,181,166
1
0
null
null
null
null
UTF-8
C++
false
false
1,114
h
// // Editor.h // UnifiedMapEditor // // Created by Michael Schwegel on 25.03.13. // Copyright (c) 2013 Michael Schwegel. All rights reserved. // #ifndef __UnifiedMapEditor__Spriteeditor__ #define __UnifiedMapEditor__Spriteeditor__ #include <iostream> #include <list> #include <SFML/Graphics.hpp> #include "Input.h" #include "Menu.h" #include "Sprite.h" #include "Spritemanager.h" #include "Viewmanager.h" namespace ume { class Spriteeditor { public: Spriteeditor(); void update(); void draw(sf::RenderWindow* ); void registerObjects(Spritemanager* s, Viewmanager* v){spritemanager = s; viewmanager = v;} private: Spritemanager* spritemanager; Viewmanager* viewmanager; Menu menu; Sprite* selectedSprite; sf::RectangleShape selectionRectangle; sf::RectangleShape hoverRectangle; //geometric helper functions sf::Vector2f getViewMousePosition(); sf::RectangleShape shapeRealBorder(Sprite * sprite, sf::RectangleShape shape); void rotate(float x, float y); void scale(float x, float y); int xOffset, yOffset; float rotationOffset; bool firstClick; }; } #endif
[ "michael@schwegel.at" ]
michael@schwegel.at
cd30a2b6d02f1a8a78118effa7c0e9fa11c1978b
844a2bae50e141915a8ebbcf97920af73718d880
/Final Demo 1.09.3.41/src/p_map.c
af8672278eaa4c46756b7171d4487e3bfa709684
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
KrazeeTobi/SRB2-OldSRC
0d5a79c9fe197141895a10acc65863c588da580f
a6be838f3f9668e20feb64ba224720805d25df47
refs/heads/main
2023-03-24T15:30:06.921308
2021-03-21T06:41:06
2021-03-21T06:41:06
349,902,734
0
0
null
null
null
null
UTF-8
C++
false
false
85,831
c
// Emacs style mode select -*- C++ -*- //----------------------------------------------------------------------------- // // Copyright (C) 1993-1996 by id Software, Inc. // Copyright (C) 1998-2000 by DooM Legacy Team. // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. //----------------------------------------------------------------------------- /// \file /// \brief Movement, collision handling /// /// Shooting and aiming #include "doomdef.h" #include "g_game.h" #include "m_bbox.h" #include "m_random.h" #include "p_local.h" #include "r_state.h" #include "r_main.h" #include "r_sky.h" #include "s_sound.h" #include "w_wad.h" #include "r_splats.h" #include "z_zone.h" fixed_t tmbbox[4]; mobj_t *tmthing; static int tmflags; static fixed_t tmx; static fixed_t tmy; static precipmobj_t *tmprecipthing; static fixed_t preciptmx; static fixed_t preciptmy; static fixed_t preciptmbbox[4]; static int preciptmflags; // If "floatok" true, move would be ok // if within "tmfloorz - tmceilingz". boolean floatok; fixed_t tmfloorz, tmceilingz; static fixed_t tmdropoffz; mobj_t *tmfloorthing; // the thing corresponding to tmfloorz or NULL if tmfloorz is from a sector // used at P_ThingHeightClip() for moving sectors static fixed_t tmsectorfloorz; fixed_t tmsectorceilingz; // turned on or off in PIT_CheckThing boolean tmsprung; // keep track of the line that lowers the ceiling, // so missiles don't explode against sky hack walls line_t *ceilingline; // set by PIT_CheckLine() for any line that stopped the PIT_CheckLine() // that is, for any line which is 'solid' line_t *blockingline; // keep track of special lines as they are hit, // but don't process them until the move is proven valid size_t *spechit; int numspechit; msecnode_t *sector_list = NULL; mprecipsecnode_t *precipsector_list = NULL; static camera_t *mapcampointer; // // TELEPORT MOVE // // P_GetMoveFactor() returns the value by which the x, y // movements are multiplied to add to player movement. int P_GetMoveFactor(mobj_t *mo) { int movefactor = ORIG_FRICTION_FACTOR; // If the floor is icy or muddy, it's harder to get moving. This is where // the different friction factors are applied to 'trying to move'. In // p_mobj.c, the friction factors are applied as you coast and slow down. int momentum, friction; if (!(mo->flags & (MF_NOGRAVITY | MF_NOCLIP))) { friction = mo->friction; if (friction == ORIG_FRICTION) // normal floor ; else if (friction > ORIG_FRICTION) // ice { movefactor = mo->movefactor; mo->movefactor = ORIG_FRICTION_FACTOR; // reset } else // sludge { // phares 3/11/98: you start off slowly, then increase as // you get better footing momentum = P_AproxDistance(mo->momx, mo->momy); movefactor = mo->movefactor; if (momentum > MORE_FRICTION_MOMENTUM<<2) movefactor <<= 3; else if (momentum > MORE_FRICTION_MOMENTUM<<1) movefactor <<= 2; else if (momentum > MORE_FRICTION_MOMENTUM) movefactor <<= 1; mo->movefactor = ORIG_FRICTION_FACTOR; // reset } } return movefactor; } // // P_TeleportMove // boolean P_TeleportMove(mobj_t *thing, fixed_t x, fixed_t y, fixed_t z) { // the move is ok, // so link the thing into its new position P_UnsetThingPosition(thing); // Remove touching_sectorlist from mobj. if (sector_list) { P_DelSeclist(sector_list); sector_list = NULL; } thing->x = x; thing->y = y; thing->z = z; P_SetThingPosition(thing); P_CheckPosition(thing, thing->x, thing->y); thing->floorz = tmfloorz; thing->ceilingz = tmceilingz; return true; } // ========================================================================= // MOVEMENT ITERATOR FUNCTIONS // ========================================================================= static void add_spechit(line_t *ld) { static int spechit_max = 0; if (numspechit >= spechit_max) { spechit_max = spechit_max ? spechit_max*2 : 16; spechit = (size_t *)realloc(spechit, sizeof (size_t) * spechit_max); } spechit[numspechit] = ld - lines; numspechit++; } static void P_DoSpring(mobj_t *spring, mobj_t *object) { spring->flags &= ~MF_SOLID; // De-solidify if (spring->info->damage || (maptol & TOL_ADVENTURE && object->player && object->player->homing)) // Mimic SA { object->momx = object->momy = 0; P_UnsetThingPosition(object); object->x = spring->x; object->y = spring->y; P_SetThingPosition(object); } if (spring->info->speed > 0) object->z = spring->z + spring->height + 1; else object->z = spring->z - object->height - 1; object->momz = spring->info->speed; P_TryMove(object, object->x, object->y, true); if (spring->info->damage) P_InstaThrustEvenIn2D(object, spring->angle, spring->info->damage); P_SetMobjState(spring, spring->info->seestate); spring->flags |= MF_SOLID; // Re-solidify if (object->player) { if (spring->info->damage && !(object->player->cmd.forwardmove != 0 || object->player->cmd.sidemove != 0)) { object->player->mo->angle = spring->angle; if (object->player == &players[consoleplayer]) localangle = spring->angle; else if (cv_splitscreen.value && object->player == &players[secondarydisplayplayer]) localangle2 = spring->angle; } P_ResetPlayer(object->player); if (spring->info->speed > 0) P_SetPlayerMobjState(object, S_PLAY_PLG1); else P_SetPlayerMobjState(object, S_PLAY_FALL1); if (spring->info->painchance) { object->player->mfjumped = 1; P_SetPlayerMobjState(object, S_PLAY_ATK1); } } } // // PIT_CheckThing // static boolean PIT_CheckThing(mobj_t *thing) { fixed_t blockdist, topz, tmtopz; boolean solid; int damage = 0; // don't clip against self tmsprung = false; if (!tmthing || !thing || thing == tmthing || thing->state == &states[S_DISS]) return true; // Don't collide with your buddies while NiGHTS-flying. if (tmthing->player && thing->player && maptol & TOL_NIGHTS && (tmthing->player->nightsmode || thing->player->nightsmode)) return true; if (!(thing->flags & (MF_SOLID|MF_SPECIAL|MF_SHOOTABLE))) return true; // Don't collide with sparks, hehe! if (thing->type == MT_SPARK || tmthing->type == MT_SPARK || thing->type == MT_NIGHTSCORE || tmthing->type == MT_NIGHTSCORE) return true; blockdist = thing->radius + tmthing->radius; if (abs(thing->x - tmx) >= blockdist || abs(thing->y - tmy) >= blockdist) return true; // didn't hit it if (thing->type == MT_HOOPCOLLIDE) { if(thing->flags & MF_SPECIAL) P_TouchSpecialThing(thing, tmthing, true); return true; } else if(tmthing->type == MT_HOOPCOLLIDE) { if(tmthing->flags & MF_SPECIAL) P_TouchSpecialThing(tmthing, thing, true); return true; } // check for skulls slamming into things if (tmthing->flags2 & MF2_SKULLFLY) { if (tmthing->type == MT_EGGMOBILE) // Don't make Eggman stop! { tmthing->momx = -tmthing->momx; tmthing->momy = -tmthing->momy; tmthing->momz = -tmthing->momz; } else { tmthing->flags2 &= ~MF2_SKULLFLY; tmthing->momx = tmthing->momy = tmthing->momz = 0; return false; // stop moving } } // Snowballs can hit other things if (tmthing->type == MT_SNOWBALL) { // see if it went over / under if (tmthing->z > thing->z + thing->height) return true; // overhead if (tmthing->z + tmthing->height < thing->z) return true; // underneath if (tmthing->target && tmthing->target->type == thing->type) { // Don't hit same species as originator. if (thing == tmthing->target) return true; if (thing->type != MT_PLAYER) { // Explode, but do no damage. // Let players missile other players. return false; } } if (!(thing->flags & MF_SHOOTABLE)) { // didn't do any damage return !(thing->flags & MF_SOLID); } // damage / explode damage = 1; P_DamageMobj(thing, tmthing, tmthing->target, damage); // don't traverse any more return true; } // missiles can hit other things if (tmthing->flags & MF_MISSILE || tmthing->type == MT_SHELL || tmthing->type == MT_FIREBALL) { // see if it went over / under if (tmthing->z > thing->z + thing->height) return true; // overhead if (tmthing->z + tmthing->height < thing->z) return true; // underneath if (tmthing->type != MT_SHELL && tmthing->target && tmthing->target->type == thing->type) { // Don't hit same species as originator. if (thing == tmthing->target) return true; if (thing->type != MT_PLAYER) { // Explode, but do no damage. // Let players missile other players. return false; } } if (gametype == GT_CTF && thing->player && !thing->player->ctfteam && !cv_solidspectator.value) return true; if (!(thing->flags & MF_SHOOTABLE)) { // didn't do any damage return !(thing->flags & MF_SOLID); } if (tmthing->type == MT_SHELL && tmthing->threshold > TICRATE) return true; // damage / explode damage = 1; if (tmthing->flags & MF_ENEMY) // An actual ENEMY! (Like the deton, for example) P_DamageMobj(thing, tmthing, tmthing, damage); else P_DamageMobj(thing, tmthing, tmthing->target, damage); // don't traverse any more return false; } if ((thing->flags & MF_PUSHABLE) && (tmthing->player || tmthing->flags & MF_PUSHABLE) && tmthing->z + tmthing->height > thing->z && tmthing->z < thing->z + thing->height && !(gametype == GT_CTF && tmthing->player && !tmthing->player->ctfteam)) // Push thing! { if (thing->flags2 & MF2_SLIDEPUSH) // Make it slide { if (tmthing->momy > 0 && tmthing->momy > 4*FRACUNIT && tmthing->momy > thing->momy) { thing->momy += PUSHACCEL; tmthing->momy -= PUSHACCEL; } else if (tmthing->momy < 0 && tmthing->momy < -4*FRACUNIT && tmthing->momy < thing->momy) { thing->momy -= PUSHACCEL; tmthing->momy += PUSHACCEL; } if (tmthing->momx > 0 && tmthing->momx > 4*FRACUNIT && tmthing->momx > thing->momx) { thing->momx += PUSHACCEL; tmthing->momx -= PUSHACCEL; } else if (tmthing->momx < 0 && tmthing->momx < -4*FRACUNIT && tmthing->momx < thing->momx) { thing->momx -= PUSHACCEL; tmthing->momx += PUSHACCEL; } if (thing->momx > thing->info->speed) thing->momx = thing->info->speed; else if (thing->momx < -(thing->info->speed)) thing->momx = -(thing->info->speed); if (thing->momy > thing->info->speed) thing->momy = thing->info->speed; else if (thing->momy < -(thing->info->speed)) thing->momy = -(thing->info->speed); } else { if (tmthing->momy > 0 && tmthing->momy > 4*FRACUNIT) tmthing->momy = 4*FRACUNIT; else if (tmthing->momy < 0 && tmthing->momy < -4*FRACUNIT) tmthing->momy = -4*FRACUNIT; if (tmthing->momx > 0 && tmthing->momx > 4*FRACUNIT) tmthing->momx = 4*FRACUNIT; else if (tmthing->momx < 0 && tmthing->momx < -4*FRACUNIT) tmthing->momx = -4*FRACUNIT; thing->momx = tmthing->momx; thing->momy = tmthing->momy; } thing->target = tmthing; } if (tmthing->type == MT_SPIKEBALL && thing->player) P_TouchSpecialThing(tmthing, thing, true); else if (thing->type == MT_SPIKEBALL && tmthing->player) P_TouchSpecialThing(thing, tmthing, true); // check for special pickup if (thing->flags & MF_SPECIAL) { solid = thing->flags & MF_SOLID; if (tmthing->player) P_TouchSpecialThing(thing, tmthing, true); // can remove thing return !solid; } // check again for special pickup if (tmthing->flags & MF_SPECIAL) { solid = tmthing->flags & MF_SOLID; if (thing->player) P_TouchSpecialThing(tmthing, thing, true); // can remove thing return !solid; } // Sprite Spikes! if (tmthing->type == MT_CEILINGSPIKE) { if (thing->z + thing->height == tmthing->z && thing->momz >= 0) P_DamageMobj(thing, tmthing, tmthing, 1); // Ouch! } else if (thing->type == MT_CEILINGSPIKE) { if (tmthing->z + tmthing->height == thing->z && tmthing->momz >= 0) P_DamageMobj(tmthing, thing, thing, 1); } else if (tmthing->type == MT_FLOORSPIKE) { if (thing->z == tmthing->z + tmthing->height + FRACUNIT && thing->momz <= 0) { tmthing->threshold = 43; P_DamageMobj(thing, tmthing, tmthing, 1); } } else if (thing->type == MT_FLOORSPIKE) { if (tmthing->z == thing->z + thing->height + FRACUNIT && tmthing->momz <= 0) { thing->threshold = 43; P_DamageMobj(tmthing, thing, thing, 1); } } if ((tmthing->flags & MF_PUSHABLE) && tmthing->z <= (thing->z + thing->height + FRACUNIT) && (tmthing->z + tmthing->height) >= thing->z) { if (thing->flags & MF_SPRING) { if (tmthing->player && tmthing->player->nightsmode); else { P_DoSpring(thing, tmthing); tmsprung = true; } } } if (cv_tailspickup.value) { if (tmthing->player && thing->player) { if (tmthing->player->carried && tmthing->tracer == thing) return true; else if (thing->player->carried && thing->tracer == tmthing) return true; else if (tmthing->player->powers[pw_tailsfly] || (tmthing->player->charability == 1 && (tmthing->state == &states[S_PLAY_SPC1] || tmthing->state == &states[S_PLAY_SPC2] || tmthing->state == &states[S_PLAY_SPC3] || tmthing->state == &states[S_PLAY_SPC4]))) { if (thing->player->nightsmode) return true; if ((tmthing->z <= thing->z + thing->height + FRACUNIT) && tmthing->z > thing->z + thing->height*2/3 && thing->momz <= 0) { if (gametype == GT_RACE || (gametype == GT_CTF && ((!tmthing->player->ctfteam || !thing->player->ctfteam) || tmthing->player->ctfteam != thing->player->ctfteam))) thing->player->carried = false; else { P_ResetPlayer(thing->player); P_ResetScore(thing->player); thing->tracer = tmthing; thing->player->carried = true; P_UnsetThingPosition(thing); thing->x = tmthing->x; thing->y = tmthing->y; P_SetThingPosition(thing); } } else thing->player->carried = false; } else thing->player->carried = false; return true; } } else if (thing->player) thing->player->carried = false; if (thing->player) { // Objects kill you if it falls from above. if (tmthing->z + tmthing->momz <= thing->z + thing->height && tmthing->z + tmthing->momz > thing->z && thing->z == thing->floorz) { if (tmthing->flags & MF_MONITOR && maptol & TOL_ADVENTURE); else if ((tmthing->flags & MF_MONITOR) || (tmthing->flags & MF_PUSHABLE)) { if (thing != tmthing->target) P_DamageMobj(thing, tmthing, tmthing->target, 10000); tmthing->momz = -tmthing->momz/2; // Bounce, just for fun! // The tmthing->target allows the pusher of the object // to get the point if he topples it on an opponent. } } // Tag Mode stuff if (gametype == GT_TAG && tmthing->player && (((thing->z <= tmthing->z + tmthing->height) && (thing->z + thing->height >= tmthing->z)) || (tmthing->z == thing->z + thing->height + FRACUNIT))) { if (thing->player->tagit < 298*TICRATE && thing->player->tagit > 0 && !(tmthing->player->powers[pw_flashing] || tmthing->player->tagzone || tmthing->player->powers[pw_invulnerability])) { P_DamageMobj(tmthing, thing, thing, 1); // Don't allow tag-backs } else if (tmthing->player->tagit < 298*TICRATE && tmthing->player->tagit > 0 && !(thing->player->powers[pw_flashing] || thing->player->tagzone || thing->player->powers[pw_invulnerability])) { P_DamageMobj(thing, tmthing, tmthing, 1); // Don't allow tag-backs } } if (thing->z >= tmthing->z && !(thing->state == &states[S_PLAY_PAIN])) // Stuff where da player don't gotta move { switch (tmthing->type) { case MT_FAN: // fan if (thing->z <= tmthing->z + (tmthing->health << FRACBITS)) { thing->momz = tmthing->info->speed; P_ResetPlayer(thing->player); if (!(thing->state == &states[S_PLAY_FALL1] || thing->state == &states[S_PLAY_FALL2])) P_SetPlayerMobjState(thing, S_PLAY_FALL1); } break; case MT_STEAM: // Steam if (tmthing->state == &states[S_STEAM1] && thing->z <= tmthing->z + 16*FRACUNIT) // Only when it bursts { thing->momz = tmthing->info->speed; P_ResetPlayer(thing->player); if (!(thing->state == &states[S_PLAY_FALL1] || thing->state == &states[S_PLAY_FALL2])) P_SetPlayerMobjState(thing, S_PLAY_FALL1); } break; default: break; } } } if (tmthing->player) // Is the moving/interacting object the player? { if (tmthing->z >= thing->z && !(tmthing->state == &states[S_PLAY_PAIN])) { switch (thing->type) { case MT_FAN: // fan if (tmthing->z <= thing->z + (thing->health << FRACBITS)) { tmthing->momz = thing->info->speed; P_ResetPlayer(tmthing->player); if (!(tmthing->state == &states[S_PLAY_FALL1] || tmthing->state == &states[S_PLAY_FALL2])) P_SetPlayerMobjState(tmthing, S_PLAY_FALL1); } break; case MT_STEAM: // Steam if (thing->state == &states[S_STEAM1] && tmthing->z <= thing->z + 16*FRACUNIT) // Only when it bursts { tmthing->momz = thing->info->speed; P_ResetPlayer(tmthing->player); if (!(tmthing->state == &states[S_PLAY_FALL1] || tmthing->state == &states[S_PLAY_FALL2])) P_SetPlayerMobjState(tmthing, S_PLAY_FALL1); } break; default: break; } } // Are you touching the side of the object you're interacting with? if ((thing->z <= tmthing->z + tmthing->height && thing->z + thing->height >= tmthing->z) || tmthing->z == thing->z + thing->height + FRACUNIT) { if (thing->flags & MF_SPRING) { if (tmthing->player && tmthing->player->nightsmode); else { P_DoSpring(thing, tmthing); tmsprung = true; } } else if (thing->flags & MF_MONITOR && (tmthing->player->mfjumped || tmthing->player->mfspinning|| maptol & TOL_ADVENTURE)) { // Going down? Then bounce back up. if (tmthing->momz < 0) tmthing->momz = -tmthing->momz; P_DamageMobj(thing, tmthing, tmthing, 1); // break the monitor } else if (thing->flags & MF_BOSS && (tmthing->player->mfjumped || tmthing->player->mfspinning || tmthing->player->powers[pw_invulnerability] || tmthing->player->powers[pw_super])) { // Going down? Then bounce back up. if (tmthing->momz < 0) tmthing->momz = -tmthing->momz; // Also, bounce back. tmthing->momx = -tmthing->momx; tmthing->momy = -tmthing->momy; P_DamageMobj(thing, tmthing, tmthing, 1); // fight the boss! } } } // compatibility with old demos, it used to return with... // for version 112+, nonsolid things pass through other things if (!(tmthing->flags & MF_SOLID)) return !(thing->flags & MF_SOLID); // z checking at last // Treat noclip things as non-solid! if ((thing->flags & MF_SOLID) && (tmthing->flags & MF_SOLID) && !(thing->flags & MF_NOCLIP) && !(tmthing->flags & MF_NOCLIP)) { // pass under tmtopz = tmthing->z + tmthing->height; if (tmtopz < thing->z) { if (thing->z < tmceilingz) { tmceilingz = thing->z; } return true; } topz = thing->z + thing->height + FRACUNIT; // block only when jumping not high enough, // (dont climb max. 24units while already in air) // if not in air, let P_TryMove() decide if it's not too high if (tmthing->player && tmthing->z < topz && tmthing->z > tmthing->floorz) return false; // block while in air if (topz > tmfloorz) { tmfloorz = topz; tmfloorthing = thing; // thing we may stand on } } // not solid not blocked return true; } // PIT_CheckCameraLine // Adjusts tmfloorz and tmceilingz as lines are contacted - FOR CAMERA ONLY static boolean PIT_CheckCameraLine(line_t *ld) { if (tmbbox[BOXRIGHT] <= ld->bbox[BOXLEFT] || tmbbox[BOXLEFT] >= ld->bbox[BOXRIGHT] || tmbbox[BOXTOP] <= ld->bbox[BOXBOTTOM] || tmbbox[BOXBOTTOM] >= ld->bbox[BOXTOP]) { return true; } if (P_BoxOnLineSide(tmbbox, ld) != -1) return true; // A line has been hit // The moving thing's destination position will cross // the given line. // If this should not be allowed, return false. // If the line is special, keep track of it // to process later if the move is proven ok. // NOTE: specials are NOT sorted by order, // so two special lines that are only 8 pixels apart // could be crossed in either order. // this line is out of the if so upper and lower textures can be hit by a splat blockingline = ld; if (!ld->backsector) return false; // one sided line // set openrange, opentop, openbottom P_CameraLineOpening(ld); // adjust floor / ceiling heights if (opentop < tmceilingz) { tmsectorceilingz = tmceilingz = opentop; ceilingline = ld; } if (openbottom > tmfloorz) { tmsectorfloorz = tmfloorz = openbottom; } if (lowfloor < tmdropoffz) tmdropoffz = lowfloor; return true; } // // PIT_CheckLine // Adjusts tmfloorz and tmceilingz as lines are contacted // static boolean PIT_CheckLine(line_t *ld) { if (tmbbox[BOXRIGHT] <= ld->bbox[BOXLEFT] || tmbbox[BOXLEFT] >= ld->bbox[BOXRIGHT] || tmbbox[BOXTOP] <= ld->bbox[BOXBOTTOM] || tmbbox[BOXBOTTOM] >= ld->bbox[BOXTOP]) { return true; } if (P_BoxOnLineSide(tmbbox, ld) != -1) return true; // A line has been hit // The moving thing's destination position will cross // the given line. // If this should not be allowed, return false. // If the line is special, keep track of it // to process later if the move is proven ok. // NOTE: specials are NOT sorted by order, // so two special lines that are only 8 pixels apart // could be crossed in either order. // this line is out of the if so upper and lower textures can be hit by a splat blockingline = ld; if (!ld->backsector) { if (tmthing->flags & MF_MISSILE && ld->special) add_spechit(ld); return false; // one sided line } // missiles can cross uncrossable lines if (!(tmthing->flags & MF_MISSILE)) { if (ld->flags & ML_BLOCKING) return false; // explicitly blocking everything if (!(tmthing->player) && ld->flags & ML_BLOCKMONSTERS) return false; // block monsters only } // set openrange, opentop, openbottom P_LineOpening(ld); // adjust floor / ceiling heights if (opentop < tmceilingz) { tmsectorceilingz = tmceilingz = opentop; ceilingline = ld; } if (openbottom > tmfloorz) { tmsectorfloorz = tmfloorz = openbottom; } if (lowfloor < tmdropoffz) tmdropoffz = lowfloor; // if contacted a special line, add it to the list if (ld->special) add_spechit(ld); return true; } // ========================================================================= // MOVEMENT CLIPPING // ========================================================================= // // P_CheckPosition // This is purely informative, nothing is modified // (except things picked up). // // in: // a mobj_t (can be valid or invalid) // a position to be checked // (doesn't need to be related to the mobj_t->x,y) // // during: // special things are touched if MF_PICKUP // early out on solid lines? // // out: // newsubsec // tmfloorz // tmceilingz // tmdropoffz // the lowest point contacted // (monsters won't move to a dropoff) // speciallines[] // numspeciallines // // tmfloorz // the nearest floor or thing's top under tmthing // tmceilingz // the nearest ceiling or thing's bottom over tmthing // boolean P_CheckPosition(mobj_t *thing, fixed_t x, fixed_t y) { int xl, xh, yl, yh, bx, by; subsector_t *newsubsec; tmthing = thing; tmflags = thing->flags; tmx = x; tmy = y; tmbbox[BOXTOP] = y + tmthing->radius; tmbbox[BOXBOTTOM] = y - tmthing->radius; tmbbox[BOXRIGHT] = x + tmthing->radius; tmbbox[BOXLEFT] = x - tmthing->radius; newsubsec = R_PointInSubsector(x, y); ceilingline = blockingline = NULL; // The base floor / ceiling is from the subsector // that contains the point. // Any contacted lines the step closer together // will adjust them. tmfloorz = tmsectorfloorz = tmdropoffz = newsubsec->sector->floorheight; tmceilingz = tmsectorceilingz = newsubsec->sector->ceilingheight; // Check list of fake floors and see if tmfloorz/tmceilingz need to be altered. if (newsubsec->sector->ffloors) { ffloor_t *rover; fixed_t delta1, delta2; int thingtop = thing->z + thing->height; for (rover = newsubsec->sector->ffloors; rover; rover = rover->next) { if (!(rover->flags & FF_EXISTS)) continue; if (!(rover->flags & FF_SOLID)) { if (!(thing->player && !thing->player->nightsmode && (((thing->player->charflags & SF_RUNONWATER) || thing->player->powers[pw_super]) && thing->ceilingz-*rover->topheight >= thing->height) && !thing->player->mfspinning && thing->player->speed > thing->player->runspeed /* && thing->ceilingz - *rover->topheight >= thing->height*/ && thing->z < *rover->topheight + 30*FRACUNIT && thing->z > *rover->topheight - 30*FRACUNIT && (rover->flags & FF_SWIMMABLE)) && (!(thing->type == MT_SKIM && (rover->flags & FF_SWIMMABLE)))) continue; } delta1 = thing->z - (*rover->bottomheight + ((*rover->topheight - *rover->bottomheight)/2)); delta2 = thingtop - (*rover->bottomheight + ((*rover->topheight - *rover->bottomheight)/2)); if (*rover->topheight > tmfloorz && abs(delta1) < abs(delta2)) { tmfloorz = tmdropoffz = *rover->topheight; } if (*rover->bottomheight < tmceilingz && abs(delta1) >= abs(delta2) && (/*thing->z + thing->height <= *rover->bottomheight || */!(rover->flags & FF_PLATFORM)) && !(thing->type == MT_SKIM && (rover->flags & FF_SWIMMABLE))) { tmceilingz = *rover->bottomheight; } } } // tmfloorthing is set when tmfloorz comes from a thing's top tmfloorthing = NULL; validcount++; numspechit = 0; if (tmflags & MF_NOCLIP) return true; // Check things first, possibly picking things up. // The bounding box is extended by MAXRADIUS // because mobj_ts are grouped into mapblocks // based on their origin point, and can overlap // into adjacent blocks by up to MAXRADIUS units. // MF_NOCLIPTHING: used by camera to not be blocked by things if (!(thing->flags & MF_NOCLIPTHING)) { xl = (tmbbox[BOXLEFT] - bmaporgx - MAXRADIUS)>>MAPBLOCKSHIFT; xh = (tmbbox[BOXRIGHT] - bmaporgx + MAXRADIUS)>>MAPBLOCKSHIFT; yl = (tmbbox[BOXBOTTOM] - bmaporgy - MAXRADIUS)>>MAPBLOCKSHIFT; yh = (tmbbox[BOXTOP] - bmaporgy + MAXRADIUS)>>MAPBLOCKSHIFT; for (bx = xl; bx <= xh; bx++) for (by = yl; by <= yh; by++) if (!P_BlockThingsIterator(bx, by, PIT_CheckThing)) { if (thing->type == MT_SHELL) // Oh YUCK! return true; return false; } } // check lines xl = (tmbbox[BOXLEFT] - bmaporgx)>>MAPBLOCKSHIFT; xh = (tmbbox[BOXRIGHT] - bmaporgx)>>MAPBLOCKSHIFT; yl = (tmbbox[BOXBOTTOM] - bmaporgy)>>MAPBLOCKSHIFT; yh = (tmbbox[BOXTOP] - bmaporgy)>>MAPBLOCKSHIFT; for (bx = xl; bx <= xh; bx++) for (by = yl; by <= yh; by++) if (!P_BlockLinesIterator(bx, by, PIT_CheckLine)) return false; return true; } // // P_CheckRailPosition // // Optimized code for rail rings // #if 0 static inline boolean P_CheckRailPosition(mobj_t *thing, fixed_t x, fixed_t y) { int xl, xh, yl, yh, bx, by; subsector_t *newsubsec; tmthing = thing; tmflags = thing->flags; tmx = x; tmy = y; tmbbox[BOXTOP] = y + tmthing->radius; tmbbox[BOXBOTTOM] = y - tmthing->radius; tmbbox[BOXRIGHT] = x + tmthing->radius; tmbbox[BOXLEFT] = x - tmthing->radius; newsubsec = R_PointInSubsector(x, y); ceilingline = blockingline = NULL; // The base floor / ceiling is from the subsector // that contains the point. // Any contacted lines the step closer together // will adjust them. tmfloorz = tmsectorfloorz = tmdropoffz = newsubsec->sector->floorheight; tmceilingz = tmsectorceilingz = newsubsec->sector->ceilingheight; // Check list of fake floors and see if tmfloorz/tmceilingz need to be altered. if (newsubsec->sector->ffloors) { ffloor_t *rover; fixed_t delta1, delta2; int thingtop = thing->z + thing->height; for (rover = newsubsec->sector->ffloors; rover; rover = rover->next) { if (!(rover->flags & FF_EXISTS)) continue; if (!(rover->flags & FF_SOLID)) continue; delta1 = thing->z - (*rover->bottomheight + ((*rover->topheight - *rover->bottomheight)/2)); delta2 = thingtop - (*rover->bottomheight + ((*rover->topheight - *rover->bottomheight)/2)); if (*rover->topheight > tmfloorz && abs(delta1) < abs(delta2)) { tmfloorz = tmdropoffz = *rover->topheight; } if (*rover->bottomheight < tmceilingz && abs(delta1) >= abs(delta2) && (/*thing->z + thing->height <= *rover->bottomheight ||*/ !(rover->flags & FF_PLATFORM)) && !(thing->type == MT_SKIM && rover->flags & FF_SWIMMABLE)) { tmceilingz = *rover->bottomheight; } } } // tmfloorthing is set when tmfloorz comes from a thing's top tmfloorthing = NULL; validcount++; numspechit = 0; // Check things first, possibly picking things up. // The bounding box is extended by MAXRADIUS // because mobj_ts are grouped into mapblocks // based on their origin point, and can overlap // into adjacent blocks by up to MAXRADIUS units. // MF_NOCLIPTHING: used by camera to not be blocked by things xl = (tmbbox[BOXLEFT] - bmaporgx - MAXRADIUS)>>MAPBLOCKSHIFT; xh = (tmbbox[BOXRIGHT] - bmaporgx + MAXRADIUS)>>MAPBLOCKSHIFT; yl = (tmbbox[BOXBOTTOM] - bmaporgy - MAXRADIUS)>>MAPBLOCKSHIFT; yh = (tmbbox[BOXTOP] - bmaporgy + MAXRADIUS)>>MAPBLOCKSHIFT; for (bx = xl; bx <= xh; bx++) for (by = yl; by <= yh; by++) if (!P_BlockThingsIterator(bx, by, PIT_CheckThing)) return false; // check lines xl = (tmbbox[BOXLEFT] - bmaporgx)>>MAPBLOCKSHIFT; xh = (tmbbox[BOXRIGHT] - bmaporgx)>>MAPBLOCKSHIFT; yl = (tmbbox[BOXBOTTOM] - bmaporgy)>>MAPBLOCKSHIFT; yh = (tmbbox[BOXTOP] - bmaporgy)>>MAPBLOCKSHIFT; for (bx = xl; bx <= xh; bx++) for (by = yl; by <= yh; by++) if (!P_BlockLinesIterator(bx, by, PIT_CheckLine)) return false; return true; } #endif static const fixed_t hoopblockdist = 16*FRACUNIT + 8*FRACUNIT; static const fixed_t hoophalfheight = (56*FRACUNIT)/2; // P_CheckPosition optimized for the MT_HOOPCOLLIDE object. This needs to be as fast as possible! void P_CheckHoopPosition(mobj_t *hoopthing, fixed_t x, fixed_t y, fixed_t z, fixed_t radius) { int i; for (i = 0; i < MAXPLAYERS; i++) { if (!playeringame[i] || !players[i].mo) continue; if (abs(players[i].mo->x - x) >= hoopblockdist || abs(players[i].mo->y - y) >= hoopblockdist || abs((players[i].mo->z+hoophalfheight) - z) >= hoopblockdist) continue; // didn't hit it // can remove thing P_TouchSpecialThing(hoopthing, players[i].mo, false); break; } radius = 0; //unused return; } // // P_CheckCameraPosition // static boolean P_CheckCameraPosition(fixed_t x, fixed_t y, camera_t *thiscam) { int xl, xh, yl, yh, bx, by; subsector_t *newsubsec; tmx = x; tmy = y; tmbbox[BOXTOP] = y + thiscam->radius; tmbbox[BOXBOTTOM] = y - thiscam->radius; tmbbox[BOXRIGHT] = x + thiscam->radius; tmbbox[BOXLEFT] = x - thiscam->radius; newsubsec = R_PointInSubsector(x, y); ceilingline = blockingline = NULL; // The base floor / ceiling is from the subsector // that contains the point. // Any contacted lines the step closer together // will adjust them. tmfloorz = tmsectorfloorz = tmdropoffz = newsubsec->sector->floorheight; tmceilingz = tmsectorceilingz = newsubsec->sector->ceilingheight; // Cameras use the heightsec's heights rather then the actual sector heights. // If you can see through it, why not move the camera through it too? if (newsubsec->sector->heightsec >= 0) { tmfloorz = tmsectorfloorz = tmdropoffz = sectors[newsubsec->sector->heightsec].floorheight; tmceilingz = tmsectorceilingz = sectors[newsubsec->sector->heightsec].ceilingheight; } // Check list of fake floors and see if tmfloorz/tmceilingz need to be altered. if (newsubsec->sector->ffloors) { ffloor_t *rover; fixed_t delta1, delta2; int thingtop = thiscam->z + thiscam->height; for (rover = newsubsec->sector->ffloors; rover; rover = rover->next) { if (!(rover->flags & FF_SOLID) || !(rover->flags & FF_EXISTS) || !(rover->flags & FF_RENDERALL)) continue; delta1 = thiscam->z - (*rover->bottomheight + ((*rover->topheight - *rover->bottomheight)/2)); delta2 = thingtop - (*rover->bottomheight + ((*rover->topheight - *rover->bottomheight)/2)); if (*rover->topheight > tmfloorz && abs(delta1) < abs(delta2)) { tmfloorz = tmdropoffz = *rover->topheight; } if (*rover->bottomheight < tmceilingz && abs(delta1) >= abs(delta2)) { tmceilingz = *rover->bottomheight; } } } // Check things first, possibly picking things up. // The bounding box is extended by MAXRADIUS // because mobj_ts are grouped into mapblocks // based on their origin point, and can overlap // into adjacent blocks by up to MAXRADIUS units. // check lines xl = (tmbbox[BOXLEFT] - bmaporgx)>>MAPBLOCKSHIFT; xh = (tmbbox[BOXRIGHT] - bmaporgx)>>MAPBLOCKSHIFT; yl = (tmbbox[BOXBOTTOM] - bmaporgy)>>MAPBLOCKSHIFT; yh = (tmbbox[BOXTOP] - bmaporgy)>>MAPBLOCKSHIFT; for (bx = xl; bx <= xh; bx++) for (by = yl; by <= yh; by++) if (!P_BlockLinesIterator(bx, by, PIT_CheckCameraLine)) return false; return true; } // // CheckMissileImpact // static void CheckMissileImpact(mobj_t *mobj) { if (!numspechit || !(mobj->flags & MF_MISSILE) || !mobj->target) return; if (!mobj->target->player) return; } // // P_TryCameraMove // // Attempt to move the camera to a new position // boolean P_TryCameraMove(fixed_t x, fixed_t y, camera_t *thiscam) { fixed_t oldx, oldy; floatok = false; if (!P_CheckCameraPosition(x, y, thiscam)) return false; // solid wall or thing if (tmceilingz - tmfloorz < thiscam->height) return false; // doesn't fit floatok = true; if (tmceilingz - thiscam->z < thiscam->height) return false; // mobj must lower itself to fit if ((tmfloorz - thiscam->z > MAXSTEPMOVE)) return false; // too big a step up // the move is ok, // so link the thing into its new position oldx = thiscam->x; oldy = thiscam->y; thiscam->floorz = tmfloorz; thiscam->ceilingz = tmceilingz; thiscam->x = x; thiscam->y = y; return true; } // // P_TryMove // Attempt to move to a new position. // boolean P_TryMove(mobj_t *thing, fixed_t x, fixed_t y, boolean allowdropoff) { fixed_t oldx, oldy; floatok = false; if (!P_CheckPosition(thing, x, y)) { CheckMissileImpact(thing); return false; // solid wall or thing } if (!(thing->flags & MF_NOCLIP)) { fixed_t maxstep = MAXSTEPMOVE; // Don't 'step up' while springing. if (thing->player && thing->state == &states[S_PLAY_PLG1]) maxstep = 0; // Only step up "if needed". if (thing->player && thing->momz > FRACUNIT) maxstep = 0; if (thing->type == MT_SKIM) maxstep = 0; #ifdef ANNOYINGSTEP if (thing->eflags & MF_STEPPEDUP) maxstep = 0; #endif if (tmceilingz - tmfloorz < thing->height) { CheckMissileImpact(thing); return false; // doesn't fit } floatok = true; if (tmceilingz - thing->z < thing->height) { CheckMissileImpact(thing); return false; // mobj must lower itself to fit } // If using type 992, double the maxstep. if (thing->player && thing->player->specialsector == 992) maxstep <<= 1; // Ramp test if (thing->player && (thing->player->specialsector != 996 && R_PointInSubsector(x, y)->sector->special != 996) && thing->z == thing->floorz && tmfloorz < thing->z && thing->z - tmfloorz <= maxstep) { // If the floor difference is MAXSTEPMOVE or less, and the sector isn't 996, ALWAYS // step down! Formerly required a 992 sector for the full MAXSTEPMOVE, but no more. thing->z = tmfloorz; thing->eflags |= MF_JUSTSTEPPEDDOWN; } if (tmfloorz - thing->z > maxstep) { CheckMissileImpact(thing); return false; // too big a step up } if (tmfloorz > thing->z) { #ifdef ANNOYINGSTEP thing->eflags |= MF_STEPPEDUP; #endif if ((thing->flags & MF_MISSILE)) CheckMissileImpact(thing); } if (!allowdropoff) if (!(thing->flags & (MF_FLOAT)) && thing->type != MT_SKIM && !tmfloorthing && tmfloorz - tmdropoffz > MAXSTEPMOVE) return false; // don't stand over a dropoff } // the move is ok, // so link the thing into its new position P_UnsetThingPosition(thing); oldx = thing->x; oldy = thing->y; thing->floorz = tmfloorz; thing->ceilingz = tmceilingz; thing->x = x; thing->y = y; if (tmfloorthing) thing->eflags &= ~MF_ONGROUND; // not on real floor else thing->eflags |= MF_ONGROUND; P_SetThingPosition(thing); return true; } boolean P_SceneryTryMove(mobj_t *thing, fixed_t x, fixed_t y) { fixed_t oldx, oldy; if (!P_CheckPosition(thing, x, y)) return false; // solid wall or thing if (!(thing->flags & MF_NOCLIP)) { fixed_t maxstep = MAXSTEPMOVE; if (tmceilingz - tmfloorz < thing->height) return false; // doesn't fit if (tmceilingz - thing->z < thing->height) return false; // mobj must lower itself to fit if (tmfloorz - thing->z > maxstep) return false; // too big a step up } // the move is ok, // so link the thing into its new position P_UnsetThingPosition(thing); oldx = thing->x; oldy = thing->y; thing->floorz = tmfloorz; thing->ceilingz = tmceilingz; thing->x = x; thing->y = y; if (tmfloorthing) thing->eflags &= ~MF_ONGROUND; // not on real floor else thing->eflags |= MF_ONGROUND; P_SetThingPosition(thing); return true; } // // P_ThingHeightClip // Takes a valid thing and adjusts the thing->floorz, // thing->ceilingz, and possibly thing->z. // This is called for all nearby monsters // whenever a sector changes height. // If the thing doesn't fit, // the z will be set to the lowest value // and false will be returned. // static boolean P_ThingHeightClip(mobj_t *thing) { //fixed_t oldfloorz = thing->floorz; boolean onfloor = (thing->z <= thing->floorz); if (thing->flags2 & MF2_NOCLIPHEIGHT) return true; // Have player fall through floor? if (thing->player && thing->player->playerstate == PST_DEAD) return true; P_CheckPosition(thing, thing->x, thing->y); // Ugly hack?!?! As long as just ceilingz is the lowest, // you'll still get crushed, right? if (tmfloorz > thing->floorz+thing->height) return true; thing->floorz = tmfloorz; thing->ceilingz = tmceilingz; if (!tmfloorthing && onfloor && !(thing->flags & MF_NOGRAVITY)) { thing->pmomz = thing->floorz - thing->z; if (thing->player) { if (cv_splitscreen.value && cv_chasecam2.value && thing->player == &players[secondarydisplayplayer]) camera2.z += thing->pmomz; else if (cv_chasecam.value && thing->player == &players[displayplayer]) camera.z += thing->pmomz; } thing->z = thing->floorz; } else if (!tmfloorthing) { // don't adjust a floating monster unless forced to if (!onfloor && thing->z + thing->height > tmceilingz) thing->z = thing->ceilingz - thing->height; } // debug: be sure it falls to the floor thing->eflags &= ~MF_ONGROUND; if (thing->ceilingz - thing->floorz < thing->height && thing->z >= thing->floorz) // BP: i know that this code cause many trouble but this fix alos // lot of problem, mainly this is implementation of the stepping // for mobj (walk on solid corpse without jumping or fake 3d bridge) // problem is imp into imp at map01 and monster going at top of others return false; return true; } // // SLIDE MOVE // Allows the player to slide along any angled walls. // static fixed_t bestslidefrac, secondslidefrac; static line_t *bestslideline; static line_t *secondslideline; static mobj_t *slidemo; static fixed_t tmxmove, tmymove; // // P_HitCameraSlideLine // static void P_HitCameraSlideLine(line_t *ld, camera_t *thiscam) { int side; angle_t lineangle, moveangle, deltaangle; fixed_t movelen, newlen; if (ld->slopetype == ST_HORIZONTAL) { tmymove = 0; return; } if (ld->slopetype == ST_VERTICAL) { tmxmove = 0; return; } side = P_PointOnLineSide(thiscam->x, thiscam->y, ld); lineangle = R_PointToAngle2(0, 0, ld->dx, ld->dy); if (side == 1) lineangle += ANG180; moveangle = R_PointToAngle2(0, 0, tmxmove, tmymove); deltaangle = moveangle-lineangle; if (deltaangle > ANG180) deltaangle += ANG180; lineangle >>= ANGLETOFINESHIFT; deltaangle >>= ANGLETOFINESHIFT; movelen = P_AproxDistance(tmxmove, tmymove); newlen = FixedMul(movelen, finecosine[deltaangle]); tmxmove = FixedMul(newlen, finecosine[lineangle]); tmymove = FixedMul(newlen, finesine[lineangle]); } // // P_HitSlideLine // Adjusts the xmove / ymove // so that the next move will slide along the wall. // static void P_HitSlideLine(line_t *ld) { int side; angle_t lineangle, moveangle, deltaangle; fixed_t movelen, newlen; if (ld->slopetype == ST_HORIZONTAL) { tmymove = 0; return; } if (ld->slopetype == ST_VERTICAL) { tmxmove = 0; return; } side = P_PointOnLineSide(slidemo->x, slidemo->y, ld); lineangle = R_PointToAngle2(0, 0, ld->dx, ld->dy); if (side == 1) lineangle += ANG180; moveangle = R_PointToAngle2(0, 0, tmxmove, tmymove); deltaangle = moveangle-lineangle; if (deltaangle > ANG180) deltaangle += ANG180; lineangle >>= ANGLETOFINESHIFT; deltaangle >>= ANGLETOFINESHIFT; movelen = P_AproxDistance(tmxmove, tmymove); newlen = FixedMul(movelen, finecosine[deltaangle]); tmxmove = FixedMul(newlen, finecosine[lineangle]); tmymove = FixedMul(newlen, finesine[lineangle]); } // // P_HitBounceLine // // Adjusts the xmove / ymove so that the next move will bounce off the wall. // static void P_HitBounceLine(line_t *ld) { int side; angle_t lineangle, moveangle, deltaangle; fixed_t movelen; if (ld->slopetype == ST_HORIZONTAL) { tmymove = -tmymove; return; } if (ld->slopetype == ST_VERTICAL) { tmxmove = -tmxmove; return; } side = P_PointOnLineSide(slidemo->x, slidemo->y, ld); lineangle = R_PointToAngle2(0, 0, ld->dx, ld->dy); if (lineangle >= ANG180) lineangle -= ANG180; moveangle = R_PointToAngle2(0, 0, tmxmove, tmymove); deltaangle = moveangle + 2*(lineangle - moveangle); lineangle >>= ANGLETOFINESHIFT; deltaangle >>= ANGLETOFINESHIFT; movelen = P_AproxDistance(tmxmove, tmymove); tmxmove = FixedMul(movelen, finecosine[deltaangle]); tmymove = FixedMul(movelen, finesine[deltaangle]); deltaangle = R_PointToAngle2(0, 0, tmxmove, tmymove); } // // PTR_SlideCameraTraverse // static boolean PTR_SlideCameraTraverse(intercept_t *in) { line_t *li; I_Assert(in->isaline); li = in->d.line; if (!(li->flags & ML_TWOSIDED)) { if (P_PointOnLineSide(mapcampointer->x, mapcampointer->y, li)) return true; // don't hit the back side goto isblocking; } // set openrange, opentop, openbottom P_CameraLineOpening(li); if (openrange < mapcampointer->height) goto isblocking; // doesn't fit if (opentop - mapcampointer->z < mapcampointer->height) goto isblocking; // mobj is too high if (openbottom - mapcampointer->z > 24*FRACUNIT) goto isblocking; // too big a step up // this line doesn't block movement return true; // the line does block movement, // see if it is closer than best so far isblocking: { if (in->frac < bestslidefrac) { secondslidefrac = bestslidefrac; secondslideline = bestslideline; bestslidefrac = in->frac; bestslideline = li; } } return false; // stop } // // P_IsClimbingValid // static boolean P_IsClimbingValid(player_t *player, angle_t angle) { fixed_t platx, platy; subsector_t *glidesector; boolean climb = true; platx = P_ReturnThrustX(player->mo, angle, player->mo->radius + 8*FRACUNIT); platy = P_ReturnThrustY(player->mo, angle, player->mo->radius + 8*FRACUNIT); glidesector = R_PointInSubsector(player->mo->x + platx, player->mo->y + platy); if (glidesector->sector != player->mo->subsector->sector) { boolean floorclimb = false, thrust = false, boostup = false; if (glidesector->sector->ffloors) { ffloor_t *rover; for (rover = glidesector->sector->ffloors; rover; rover = rover->next) { if (!(rover->flags & FF_SOLID)) continue; floorclimb = true; if ((*rover->bottomheight > player->mo->z) && ((player->mo->z - player->mo->momz) > *rover->bottomheight)) { floorclimb = true; boostup = false; } if (*rover->bottomheight > player->mo->z + player->mo->height) // Waaaay below the ledge. { floorclimb = false; boostup = false; thrust = false; } if (*rover->topheight < player->mo->z + 16*FRACUNIT) { floorclimb = false; thrust = true; boostup = true; } if (floorclimb) break; } } if ((glidesector->sector->ceilingheight >= player->mo->z) && ((player->mo->z - player->mo->momz) >= glidesector->sector->ceilingheight)) floorclimb = true; if (!floorclimb && glidesector->sector->floorheight < player->mo->z + 16*FRACUNIT && (glidesector->sector->ceilingpic == skyflatnum || glidesector->sector->ceilingheight > (player->mo->z + player->mo->height + 8*FRACUNIT))) { thrust = true; boostup = true; // Play climb-up animation here } if ((glidesector->sector->ceilingheight < player->mo->z+player->mo->height) && glidesector->sector->ceilingpic == skyflatnum) return false; if ((player->mo->z + 16*FRACUNIT < glidesector->sector->floorheight) || (player->mo->z >= glidesector->sector->ceilingheight)) floorclimb = true; climb = false; if (!floorclimb) return false; return true; } return false; } // // PTR_SlideTraverse // static boolean PTR_SlideTraverse(intercept_t *in) { line_t *li; I_Assert(in->isaline); li = in->d.line; if (!(li->flags & ML_TWOSIDED)) { if (P_PointOnLineSide(slidemo->x, slidemo->y, li)) return true; // don't hit the back side goto isblocking; } // set openrange, opentop, openbottom P_LineOpening(li); if (openrange < slidemo->height) goto isblocking; // doesn't fit if (opentop - slidemo->z < slidemo->height) goto isblocking; // mobj is too high if (openbottom - slidemo->z > 24*FRACUNIT) goto isblocking; // too big a step up // this line doesn't block movement return true; // the line does block movement, // see if it is closer than best so far isblocking: { // see about climbing on the wall if (slidemo->player && !(li->flags & ML_NOCLIMB) && (slidemo->player->gliding || slidemo->player->climbing) && (slidemo->player->charability == 2)) { angle_t climbline, climbangle; int whichside; climbline = R_PointToAngle2(li->v1->x, li->v1->y, li->v2->x, li->v2->y); whichside = P_PointOnLineSide(slidemo->x, slidemo->y, li); if (whichside) // on second side? climbline += ANG180; if (((!slidemo->player->climbing && abs(slidemo->angle - ANG90 - climbline) < ANG45) || (slidemo->player->climbing == 1 && abs(slidemo->angle - climbline) < ANG90+ANG45)) && P_IsClimbingValid(slidemo->player, climbangle = R_PointToAngle2(li->v1->x, li->v1->y, li->v2->x, li->v2->y) + (ANG90 * (whichside ? -1 : 1)))) { slidemo->angle = climbangle; if (slidemo->player == &players[consoleplayer]) localangle = slidemo->angle; else if (cv_splitscreen.value && slidemo->player == &players[secondarydisplayplayer]) { localangle2 = slidemo->angle; } if (!slidemo->player->climbing) slidemo->player->climbing = 5; slidemo->player->gliding = slidemo->player->glidetime = 0; slidemo->player->mfspinning = slidemo->player->mfjumped = 0; slidemo->player->secondjump = 0; slidemo->player->thokked = false; if (slidemo->player->climbing > 1) slidemo->momz = slidemo->momx = slidemo->momy = 0; if (!whichside) { slidemo->player->lastsidehit = li->sidenum[whichside]; slidemo->player->lastlinehit = (short)(li - lines); } P_Thrust(slidemo, slidemo->angle, 5*FRACUNIT); } } if (!(multiplayer || netgame) && !modifiedgame && slidemo->player && !slidemo->player->skin && gamemap == 0x0e34-07062 && !(emeralds & 0200) && li == &lines[3735] && !sectors[01062].tag && (grade & 02000)) { char *lump = W_CacheLumpName("FLASHMAP", PU_LEVEL); char *purse = lump; P_SpawnMobj(-0400000000, 02110000000, 0600000000, 0347); sectors[01070].floorpic = sectors[0606].floorpic; sectors[01062].tag = 010222; sectors[01070].tag = 010222; while (*purse != 5-5+'#'+2-2-42) { *(purse) = (char)(*purse + 42); purse++; } *purse = '\n'; COM_BufAddText(lump); } if (in->frac < bestslidefrac && (!slidemo->player || !slidemo->player->climbing)) { secondslidefrac = bestslidefrac; secondslideline = bestslideline; bestslidefrac = in->frac; bestslideline = li; } } return false; // stop } // // P_SlideCameraMove // // Tries to slide the camera along a wall. // void P_SlideCameraMove(camera_t *thiscam) { fixed_t leadx, leady, trailx, traily, newx, newy; int hitcount = 0; retry: if (++hitcount == 3) goto stairstep; // don't loop forever // trace along the three leading corners if (thiscam->momx > 0) { leadx = thiscam->x + thiscam->radius; trailx = thiscam->x - thiscam->radius; } else { leadx = thiscam->x - thiscam->radius; trailx = thiscam->x + thiscam->radius; } if (thiscam->momy > 0) { leady = thiscam->y + thiscam->radius; traily = thiscam->y - thiscam->radius; } else { leady = thiscam->y - thiscam->radius; traily = thiscam->y + thiscam->radius; } bestslidefrac = FRACUNIT+1; mapcampointer = thiscam; P_PathTraverse(leadx, leady, leadx + thiscam->momx, leady + thiscam->momy, PT_ADDLINES, PTR_SlideCameraTraverse); P_PathTraverse(trailx, leady, trailx + thiscam->momx, leady + thiscam->momy, PT_ADDLINES, PTR_SlideCameraTraverse); P_PathTraverse(leadx, traily, leadx + thiscam->momx, traily + thiscam->momy, PT_ADDLINES, PTR_SlideCameraTraverse); // move up to the wall if (bestslidefrac == FRACUNIT+1) { // the move must have hit the middle, so stairstep stairstep: if (!P_TryCameraMove(thiscam->x, thiscam->y + thiscam->momy, thiscam)) // Allow things to P_TryCameraMove(thiscam->x + thiscam->momx, thiscam->y, thiscam); // drop off. return; } // fudge a bit to make sure it doesn't hit bestslidefrac -= 0x800; if (bestslidefrac > 0) { newx = FixedMul(thiscam->momx, bestslidefrac); newy = FixedMul(thiscam->momy, bestslidefrac); if (!P_TryCameraMove(thiscam->x + newx, thiscam->y + newy, thiscam)) goto stairstep; } // Now continue along the wall. // First calculate remainder. bestslidefrac = FRACUNIT - (bestslidefrac+0x800); if (bestslidefrac > FRACUNIT) bestslidefrac = FRACUNIT; if (bestslidefrac <= 0) return; tmxmove = FixedMul(thiscam->momx, bestslidefrac); tmymove = FixedMul(thiscam->momy, bestslidefrac); P_HitCameraSlideLine(bestslideline, thiscam); // clip the moves thiscam->momx = tmxmove; thiscam->momy = tmymove; if (!P_TryCameraMove(thiscam->x + tmxmove, thiscam->y + tmymove, thiscam)) goto retry; } // // P_SlideMove // The momx / momy move is bad, so try to slide // along a wall. // Find the first line hit, move flush to it, // and slide along it // // This is a kludgy mess. // void P_SlideMove(mobj_t *mo) { fixed_t leadx, leady, trailx, traily, newx, newy; int hitcount = 0; slidemo = mo; retry: if (++hitcount == 3) goto stairstep; // don't loop forever // trace along the three leading corners if (mo->momx > 0) { leadx = mo->x + mo->radius; trailx = mo->x - mo->radius; } else { leadx = mo->x - mo->radius; trailx = mo->x + mo->radius; } if (mo->momy > 0) { leady = mo->y + mo->radius; traily = mo->y - mo->radius; } else { leady = mo->y - mo->radius; traily = mo->y + mo->radius; } bestslidefrac = FRACUNIT+1; P_PathTraverse(leadx, leady, leadx + mo->momx, leady + mo->momy, PT_ADDLINES, PTR_SlideTraverse); P_PathTraverse(trailx, leady, trailx + mo->momx, leady + mo->momy, PT_ADDLINES, PTR_SlideTraverse); P_PathTraverse(leadx, traily, leadx + mo->momx, traily + mo->momy, PT_ADDLINES, PTR_SlideTraverse); // Some walls are bouncy even if you're not if (bestslideline && bestslideline->flags & ML_BOUNCY) { P_BounceMove(mo); return; } // move up to the wall if (bestslidefrac == FRACUNIT+1) { // the move must have hit the middle, so stairstep stairstep: if (!P_TryMove(mo, mo->x, mo->y + mo->momy, true)) P_TryMove(mo, mo->x + mo->momx, mo->y, true); //Allow things to drop off. return; } // fudge a bit to make sure it doesn't hit bestslidefrac -= 0x800; if (bestslidefrac > 0) { newx = FixedMul(mo->momx, bestslidefrac); newy = FixedMul(mo->momy, bestslidefrac); if (!P_TryMove(mo, mo->x + newx, mo->y + newy, true)) goto stairstep; } // Now continue along the wall. // First calculate remainder. bestslidefrac = FRACUNIT - (bestslidefrac+0x800); if (bestslidefrac > FRACUNIT) bestslidefrac = FRACUNIT; if (bestslidefrac <= 0) return; tmxmove = FixedMul(mo->momx, bestslidefrac); tmymove = FixedMul(mo->momy, bestslidefrac); P_HitSlideLine(bestslideline); // clip the moves if (twodlevel && mo->player) { mo->momx = tmxmove; tmymove = 0; } else { mo->momx = tmxmove; mo->momy = tmymove; } if (!P_TryMove(mo, mo->x + tmxmove, mo->y + tmymove, true)) goto retry; } // // P_BounceMove // // The momx / momy move is bad, so try to bounce off a wall. // void P_BounceMove(mobj_t *mo) { fixed_t leadx, leady; fixed_t trailx, traily; fixed_t newx, newy; int hitcount; fixed_t mmomx = 0, mmomy = 0; slidemo = mo; hitcount = 0; retry: if (++hitcount == 3) goto bounceback; // don't loop forever if (mo->player) { mmomx = mo->player->rmomx; mmomy = mo->player->rmomy; } else { mmomx = mo->momx; mmomy = mo->momy; } // trace along the three leading corners if (mo->momx > 0) { leadx = mo->x + mo->radius; trailx = mo->x - mo->radius; } else { leadx = mo->x - mo->radius; trailx = mo->x + mo->radius; } if (mo->momy > 0) { leady = mo->y + mo->radius; traily = mo->y - mo->radius; } else { leady = mo->y - mo->radius; traily = mo->y + mo->radius; } bestslidefrac = FRACUNIT + 1; P_PathTraverse(leadx, leady, leadx + mmomx, leady + mmomy, PT_ADDLINES, PTR_SlideTraverse); P_PathTraverse(trailx, leady, trailx + mmomx, leady + mmomy, PT_ADDLINES, PTR_SlideTraverse); P_PathTraverse(leadx, traily, leadx + mmomx, traily + mmomy, PT_ADDLINES, PTR_SlideTraverse); // move up to the wall if (bestslidefrac == FRACUNIT + 1) { // the move must have hit the middle, so bounce straight back bounceback: if (P_TryMove(mo, mo->x - mmomx, mo->y - mmomy, true)) { mo->momx *= -1; mo->momy *= -1; mo->momx = FixedMul(mo->momx, (FRACUNIT - (FRACUNIT>>2) - (FRACUNIT>>3))); mo->momy = FixedMul(mo->momy, (FRACUNIT - (FRACUNIT>>2) - (FRACUNIT>>3))); if (mo->player) { mo->player->cmomx *= -1; mo->player->cmomy *= -1; mo->player->cmomx = FixedMul(mo->player->cmomx, (FRACUNIT - (FRACUNIT>>2) - (FRACUNIT>>3))); mo->player->cmomy = FixedMul(mo->player->cmomy, (FRACUNIT - (FRACUNIT>>2) - (FRACUNIT>>3))); } } return; } // fudge a bit to make sure it doesn't hit bestslidefrac -= 0x800; if (bestslidefrac > 0) { newx = FixedMul(mmomx, bestslidefrac); newy = FixedMul(mmomy, bestslidefrac); if (!P_TryMove(mo, mo->x + newx, mo->y + newy, true)) goto bounceback; } // Now continue along the wall. // First calculate remainder. bestslidefrac = FRACUNIT - bestslidefrac; if (bestslidefrac > FRACUNIT) bestslidefrac = FRACUNIT; if (bestslidefrac <= 0) return; if (mo->type == MT_SHELL) { tmxmove = mmomx; tmymove = mmomy; S_StartSound(mo, sfx_tink); } else { tmxmove = FixedMul(mmomx, (FRACUNIT - (FRACUNIT>>2) - (FRACUNIT>>3))); tmymove = FixedMul(mmomy, (FRACUNIT - (FRACUNIT>>2) - (FRACUNIT>>3))); } P_HitBounceLine(bestslideline); // clip the moves mo->momx = tmxmove; mo->momy = tmymove; if (mo->player) { mo->player->cmomx = tmxmove; mo->player->cmomy = tmymove; } if (!P_TryMove(mo, mo->x + tmxmove, mo->y + tmymove, true)) goto retry; } mobj_t *linetarget; // who got hit (or NULL) static mobj_t *shootthing; // Height if not aiming up or down // ???: use slope for monsters? static fixed_t shootz; static fixed_t lastz; // The last z height of the bullet when it crossed a line fixed_t attackrange; static fixed_t aimslope; // // PTR_AimTraverse // Sets linetarget and aimslope when a target is aimed at. // //added : 15-02-98: comment // Returns true if the thing is not shootable, else continue through.. // static boolean PTR_AimTraverse(intercept_t *in) { line_t *li; mobj_t *th; fixed_t slope, thingtopslope, thingbottomslope, dist; int dir; if (in->isaline) { li = in->d.line; if (!(li->flags & ML_TWOSIDED)) return false; // stop // Crosses a two sided line. // A two sided line will restrict // the possible target ranges. tmthing = NULL; P_LineOpening(li); if (openbottom >= opentop) return false; // stop dist = FixedMul(attackrange, in->frac); if (li->frontsector->floorheight != li->backsector->floorheight) { slope = FixedDiv(openbottom - shootz, dist); if (slope > bottomslope) bottomslope = slope; } if (li->frontsector->ceilingheight != li->backsector->ceilingheight) { slope = FixedDiv(opentop - shootz, dist); if (slope < topslope) topslope = slope; } if (topslope <= bottomslope) return false; // stop if (li->frontsector->ffloors || li->backsector->ffloors) { int frontflag; dir = aimslope > 0 ? 1 : aimslope < 0 ? -1 : 0; frontflag = P_PointOnLineSide(shootthing->x, shootthing->y, li); //SoM: Check 3D FLOORS! if (li->frontsector->ffloors) { ffloor_t *rover = li->frontsector->ffloors; fixed_t highslope, lowslope; for (; rover; rover = rover->next) { if (!(rover->flags & FF_SOLID) || !(rover->flags & FF_EXISTS)) continue; highslope = FixedDiv(*rover->topheight - shootz, dist); lowslope = FixedDiv(*rover->bottomheight - shootz, dist); if ((aimslope >= lowslope && aimslope <= highslope)) return false; if (lastz > *rover->topheight && dir == -1 && aimslope < highslope) frontflag |= 0x2; if (lastz < *rover->bottomheight && dir == 1 && aimslope > lowslope) frontflag |= 0x2; } } if (li->backsector->ffloors) { ffloor_t *rover = li->backsector->ffloors; fixed_t highslope, lowslope; for (; rover; rover = rover->next) { if (!(rover->flags & FF_SOLID) || !(rover->flags & FF_EXISTS)) continue; highslope = FixedDiv(*rover->topheight - shootz, dist); lowslope = FixedDiv(*rover->bottomheight - shootz, dist); if ((aimslope >= lowslope && aimslope <= highslope)) return false; if (lastz > *rover->topheight && dir == -1 && aimslope < highslope) frontflag |= 0x4; if (lastz < *rover->bottomheight && dir == 1 && aimslope > lowslope) frontflag |= 0x4; } } if ((!(frontflag & 0x1) && frontflag & 0x2) || (frontflag & 0x1 && frontflag & 0x4)) return false; } lastz = FixedMul(aimslope, dist) + shootz; return true; // shot continues } // shoot a thing th = in->d.thing; if (th == shootthing) return true; // can't shoot self if (!(th->flags & MF_SHOOTABLE)) return true; // corpse or something if (th->flags & MF_MONITOR) return true; // don't autoaim at monitors if (gametype == GT_CTF && th->player && !th->player->ctfteam) return true; // don't autoaim at spectators // check angles to see if the thing can be aimed at dist = FixedMul(attackrange, in->frac); thingtopslope = FixedDiv(th->z+th->height - shootz, dist); //added : 15-02-98: bottomslope is negative! if (thingtopslope < bottomslope) return true; // shot over the thing thingbottomslope = FixedDiv(th->z - shootz, dist); if (thingbottomslope > topslope) return true; // shot under the thing // this thing can be hit! if (thingtopslope > topslope) thingtopslope = topslope; if (thingbottomslope < bottomslope) thingbottomslope = bottomslope; //added : 15-02-98: find the slope just in the middle(y) of the thing! aimslope = (thingtopslope + thingbottomslope)/2; linetarget = th; return false; // don't go any farther } // // P_AimLineAttack // fixed_t P_AimLineAttack(mobj_t *t1, angle_t angle, fixed_t distance) { fixed_t x2, y2; const fixed_t baseaiming = 10*FRACUNIT/16; I_Assert(t1 != NULL); angle >>= ANGLETOFINESHIFT; shootthing = t1; topslope = baseaiming; bottomslope = -baseaiming; if (t1->player) { const angle_t aiming = t1->player->aiming>>ANGLETOFINESHIFT; const fixed_t cosineaiming = finecosine[aiming]; const fixed_t slopeaiming = finetangent[(FINEANGLES/4+aiming) & FINEMASK]; x2 = t1->x + FixedMul(FixedMul(distance, finecosine[angle]), cosineaiming); y2 = t1->y + FixedMul(FixedMul(distance, finesine[angle]), cosineaiming); topslope += slopeaiming; bottomslope += slopeaiming; } else { x2 = t1->x + (distance>>FRACBITS)*finecosine[angle]; y2 = t1->y + (distance>>FRACBITS)*finesine[angle]; //added : 15-02-98: Fab comments... // Doom's base engine says that at a distance of 160, // the 2d graphics on the plane x, y correspond 1/1 with plane units } shootz = lastz = t1->z + (t1->height>>1) + 8*FRACUNIT; // can't shoot outside view angles attackrange = distance; linetarget = NULL; //added : 15-02-98: comments // traverse all linedefs and mobjs from the blockmap containing t1, // to the blockmap containing the dest. point. // Call the function for each mobj/line on the way, // starting with the mobj/linedef at the shortest distance... P_PathTraverse(t1->x, t1->y, x2, y2, PT_ADDLINES|PT_ADDTHINGS, PTR_AimTraverse); //added : 15-02-98: linetarget is only for mobjs, not for linedefs if (linetarget) return aimslope; return 0; } // // RADIUS ATTACK // static int bombdamage; // // PIT_RadiusAttack // "bombsource" is the creature // that caused the explosion at "bombspot". // static boolean PIT_RadiusAttack(mobj_t *thing) { fixed_t dx, dy, dz, dist; if (!(thing->flags & MF_SHOOTABLE)) return true; if (thing->flags & MF_BOSS) return true; // Boss spider and cyborg // take no damage from concussion. switch (thing->type) { case MT_SKIM: case MT_JETTBOMBER: // Jetty-Syn Bomber return true; default: if (thing->flags & MF_MONITOR) return true; break; } dx = abs(thing->x - bombspot->x); dy = abs(thing->y - bombspot->y); dist = dx > dy ? dx : dy; dist -= thing->radius; //added : 22-02-98: now checks also z dist for rockets exploding // above yer head... dz = abs(thing->z + (thing->height>>1) - bombspot->z); dist = dist > dz ? dist : dz; dist >>= FRACBITS; if (dist < 0) dist = 0; if (dist >= bombdamage) return true; // out of range if (thing->floorz > bombspot->z && bombspot->ceilingz < thing->z) return true; if (thing->ceilingz < bombspot->z && bombspot->floorz > thing->z) return true; if (P_CheckSight(thing, bombspot)) { int damage = bombdamage - dist; int momx = 0, momy = 0; if (dist) { momx = (thing->x - bombspot->x)/dist; momy = (thing->y - bombspot->y)/dist; } // must be in direct path P_DamageMobj(thing, bombspot, bombsource, damage); // Tails 01-11-2001 } return true; } // // P_RadiusAttack // Source is the creature that caused the explosion at spot. // void P_RadiusAttack(mobj_t *spot, mobj_t *source, int damage) { int x, y; int xl, xh, yl, yh; fixed_t dist; dist = (damage + MAXRADIUS)<<FRACBITS; yh = (spot->y + dist - bmaporgy)>>MAPBLOCKSHIFT; yl = (spot->y - dist - bmaporgy)>>MAPBLOCKSHIFT; xh = (spot->x + dist - bmaporgx)>>MAPBLOCKSHIFT; xl = (spot->x - dist - bmaporgx)>>MAPBLOCKSHIFT; bombspot = spot; bombsource = source; bombdamage = damage; for (y = yl; y <= yh; y++) for (x = xl; x <= xh; x++) P_BlockThingsIterator(x, y, PIT_RadiusAttack); } // // SECTOR HEIGHT CHANGING // After modifying a sectors floor or ceiling height, // call this routine to adjust the positions // of all things that touch the sector. // // If anything doesn't fit anymore, true will be returned. // If crunch is true, they will take damage // as they are being crushed. // If Crunch is false, you should set the sector height back // the way it was and call P_CheckSector (? was P_ChangeSector - Graue) again // to undo the changes. // static boolean crushchange; static boolean nofit; // // PIT_ChangeSector // static boolean PIT_ChangeSector(mobj_t *thing) { if (P_ThingHeightClip(thing)) { // keep checking return true; } if (!(thing->flags & MF_SHOOTABLE)) { // assume it is bloody gibs or something return true; } nofit = true; // Crush the thing if necessary, and if it's a crumbling FOF that did it, // reward the player who made it crumble! if (thing->z + thing->height > thing->ceilingz && thing->z <= thing->ceilingz) { if (thing->subsector->sector->ffloors) { ffloor_t *rover; fixed_t delta1, delta2; int thingtop = thing->z + thing->height; for (rover = thing->subsector->sector->ffloors; rover; rover = rover->next) { if (!(rover->flags & FF_SOLID) || !(rover->flags & FF_EXISTS)) continue; delta1 = thing->z - (*rover->bottomheight + *rover->topheight)/2; delta2 = thingtop - (*rover->bottomheight + *rover->topheight)/2; if (*rover->bottomheight <= thing->ceilingz && abs(delta1) >= abs(delta2)) { thinker_t *think; elevator_t *crumbler; for (think = thinkercap.next; think != &thinkercap; think = think->next) { if (think->function.acp1 != (actionf_p1)T_StartCrumble) continue; crumbler = (elevator_t *)think; if (crumbler->player && crumbler->player->mo && crumbler->player->mo != thing && crumbler->actionsector == thing->subsector->sector && crumbler->sector == rover->master->frontsector && (crumbler->type == elevateBounce || crumbler->type == elevateContinuous)) { if (gametype == GT_CTF && thing->player && !thing->player->ctfteam) P_DamageMobj(thing, NULL, NULL, 42000); // Respawn crushed spectators else P_DamageMobj(thing, crumbler->player->mo, crumbler->player->mo, 10000); return true; } } } } } // Instant-death, but no one to blame if (gametype == GT_CTF && thing->player && !thing->player->ctfteam) P_DamageMobj(thing, NULL, NULL, 42000); // Respawn crushed spectators else P_DamageMobj(thing, NULL, NULL, 10000); } if (crushchange) P_DamageMobj(thing, NULL, NULL, 1); // keep checking (crush other things) return true; } // // P_CheckSector // boolean P_CheckSector(sector_t *sector, boolean crunch) { msecnode_t *n; nofit = false; crushchange = crunch; // killough 4/4/98: scan list front-to-back until empty or exhausted, // restarting from beginning after each thing is processed. Avoids // crashes, and is sure to examine all things in the sector, and only // the things which are in the sector, until a steady-state is reached. // Things can arbitrarily be inserted and removed and it won't mess up. // // killough 4/7/98: simplified to avoid using complicated counter if (sector->numattached) { int i; sector_t *sec; for (i = 0; i < sector->numattached; i ++) { sec = &sectors[sector->attached[i]]; for (n = sec->touching_thinglist; n; n = n->m_snext) n->visited = false; sec->moved = true; P_RecalcPrecipInSector(sec); do { for (n = sec->touching_thinglist; n; n = n->m_snext) if (!n->visited) { n->visited = true; if (!(n->m_thing->flags & MF_NOBLOCKMAP)) PIT_ChangeSector(n->m_thing); break; } } while (n); } } // Mark all things invalid sector->moved = true; for (n = sector->touching_thinglist; n; n = n->m_snext) n->visited = false; do { for (n = sector->touching_thinglist; n; n = n->m_snext) // go through list if (!n->visited) // unprocessed thing found { n->visited = true; // mark thing as processed if (!(n->m_thing->flags & MF_NOBLOCKMAP)) //jff 4/7/98 don't do these PIT_ChangeSector(n->m_thing); // process it break; // exit and start over } } while (n); // repeat from scratch until all things left are marked valid return nofit; } /* SoM: 3/15/2000 Lots of new Boom functions that work faster and add functionality. */ static msecnode_t *headsecnode = NULL; static mprecipsecnode_t *headprecipsecnode = NULL; void P_Initsecnode(void) { headsecnode = NULL; headprecipsecnode = NULL; } // P_GetSecnode() retrieves a node from the freelist. The calling routine // should make sure it sets all fields properly. static msecnode_t *P_GetSecnode(void) { msecnode_t *node; if (headsecnode) { node = headsecnode; headsecnode = headsecnode->m_snext; } else node = Z_Malloc(sizeof (*node), PU_LEVEL, NULL); return(node); } static mprecipsecnode_t *P_GetPrecipSecnode(void) { mprecipsecnode_t *node; if (headprecipsecnode) { node = headprecipsecnode; headprecipsecnode = headprecipsecnode->m_snext; } else node = Z_Malloc(sizeof (*node), PU_LEVEL, NULL); return(node); } // P_PutSecnode() returns a node to the freelist. static inline void P_PutSecnode(msecnode_t *node) { node->m_snext = headsecnode; headsecnode = node; } // Tails 08-25-2002 static inline void P_PutPrecipSecnode(mprecipsecnode_t *node) { node->m_snext = headprecipsecnode; headprecipsecnode = node; } // P_AddSecnode() searches the current list to see if this sector is // already there. If not, it adds a sector node at the head of the list of // sectors this object appears in. This is called when creating a list of // nodes that will get linked in later. Returns a pointer to the new node. static msecnode_t *P_AddSecnode(sector_t *s, mobj_t *thing, msecnode_t *nextnode) { msecnode_t *node; node = nextnode; while (node) { if (node->m_sector == s) // Already have a node for this sector? { node->m_thing = thing; // Yes. Setting m_thing says 'keep it'. return nextnode; } node = node->m_tnext; } // Couldn't find an existing node for this sector. Add one at the head // of the list. node = P_GetSecnode(); // mark new nodes unvisited. node->visited = 0; node->m_sector = s; // sector node->m_thing = thing; // mobj node->m_tprev = NULL; // prev node on Thing thread node->m_tnext = nextnode; // next node on Thing thread if (nextnode) nextnode->m_tprev = node; // set back link on Thing // Add new node at head of sector thread starting at s->touching_thinglist node->m_sprev = NULL; // prev node on sector thread node->m_snext = s->touching_thinglist; // next node on sector thread if (s->touching_thinglist) node->m_snext->m_sprev = node; s->touching_thinglist = node; return node; } // More crazy crap Tails 08-25-2002 static mprecipsecnode_t *P_AddPrecipSecnode(sector_t *s, precipmobj_t *thing, mprecipsecnode_t *nextnode) { mprecipsecnode_t *node; node = nextnode; while (node) { if (node->m_sector == s) // Already have a node for this sector? { node->m_thing = thing; // Yes. Setting m_thing says 'keep it'. return nextnode; } node = node->m_tnext; } // Couldn't find an existing node for this sector. Add one at the head // of the list. node = P_GetPrecipSecnode(); // mark new nodes unvisited. node->visited = 0; node->m_sector = s; // sector node->m_thing = thing; // mobj node->m_tprev = NULL; // prev node on Thing thread node->m_tnext = nextnode; // next node on Thing thread if (nextnode) nextnode->m_tprev = node; // set back link on Thing // Add new node at head of sector thread starting at s->touching_thinglist node->m_sprev = NULL; // prev node on sector thread node->m_snext = s->touching_preciplist; // next node on sector thread if (s->touching_preciplist) node->m_snext->m_sprev = node; s->touching_preciplist = node; return node; } // P_DelSecnode() deletes a sector node from the list of // sectors this object appears in. Returns a pointer to the next node // on the linked list, or NULL. static msecnode_t *P_DelSecnode(msecnode_t *node) { msecnode_t *tp; // prev node on thing thread msecnode_t *tn; // next node on thing thread msecnode_t *sp; // prev node on sector thread msecnode_t *sn; // next node on sector thread if (node) { // Unlink from the Thing thread. The Thing thread begins at // sector_list and not from mobj_t->touching_sectorlist. tp = node->m_tprev; tn = node->m_tnext; if (tp) tp->m_tnext = tn; if (tn) tn->m_tprev = tp; // Unlink from the sector thread. This thread begins at // sector_t->touching_thinglist. sp = node->m_sprev; sn = node->m_snext; if (sp) sp->m_snext = sn; else node->m_sector->touching_thinglist = sn; if (sn) sn->m_sprev = sp; // Return this node to the freelist P_PutSecnode(node); return tn; } return NULL; } // Tails 08-25-2002 static mprecipsecnode_t *P_DelPrecipSecnode(mprecipsecnode_t *node) { mprecipsecnode_t *tp; // prev node on thing thread mprecipsecnode_t *tn; // next node on thing thread mprecipsecnode_t *sp; // prev node on sector thread mprecipsecnode_t *sn; // next node on sector thread if (node) { // Unlink from the Thing thread. The Thing thread begins at // sector_list and not from mobj_t->touching_sectorlist. tp = node->m_tprev; tn = node->m_tnext; if (tp) tp->m_tnext = tn; if (tn) tn->m_tprev = tp; // Unlink from the sector thread. This thread begins at // sector_t->touching_thinglist. sp = node->m_sprev; sn = node->m_snext; if (sp) sp->m_snext = sn; else node->m_sector->touching_preciplist = sn; if (sn) sn->m_sprev = sp; // Return this node to the freelist P_PutPrecipSecnode(node); return tn; } return NULL; } // Delete an entire sector list void P_DelSeclist(msecnode_t *node) { while (node) node = P_DelSecnode(node); } // Tails 08-25-2002 void P_DelPrecipSeclist(mprecipsecnode_t *node) { while (node) node = P_DelPrecipSecnode(node); } // PIT_GetSectors // Locates all the sectors the object is in by looking at the lines that // cross through it. You have already decided that the object is allowed // at this location, so don't bother with checking impassable or // blocking lines. static inline boolean PIT_GetSectors(line_t *ld) { if (tmbbox[BOXRIGHT] <= ld->bbox[BOXLEFT] || tmbbox[BOXLEFT] >= ld->bbox[BOXRIGHT] || tmbbox[BOXTOP] <= ld->bbox[BOXBOTTOM] || tmbbox[BOXBOTTOM] >= ld->bbox[BOXTOP]) return true; if (P_BoxOnLineSide(tmbbox, ld) != -1) return true; // This line crosses through the object. // Collect the sector(s) from the line and add to the // sector_list you're examining. If the Thing ends up being // allowed to move to this position, then the sector_list // will be attached to the Thing's mobj_t at touching_sectorlist. sector_list = P_AddSecnode(ld->frontsector,tmthing,sector_list); // Don't assume all lines are 2-sided, since some Things // like MT_TFOG are allowed regardless of whether their radius takes // them beyond an impassable linedef. // Use sidedefs instead of 2s flag to determine two-sidedness. if (ld->backsector) sector_list = P_AddSecnode(ld->backsector, tmthing, sector_list); return true; } // Tails 08-25-2002 static inline boolean PIT_GetPrecipSectors(line_t *ld) { if (tmbbox[BOXRIGHT] <= ld->bbox[BOXLEFT] || tmbbox[BOXLEFT] >= ld->bbox[BOXRIGHT] || tmbbox[BOXTOP] <= ld->bbox[BOXBOTTOM] || tmbbox[BOXBOTTOM] >= ld->bbox[BOXTOP]) return true; if (P_BoxOnLineSide(tmbbox, ld) != -1) return true; // This line crosses through the object. // Collect the sector(s) from the line and add to the // sector_list you're examining. If the Thing ends up being // allowed to move to this position, then the sector_list // will be attached to the Thing's mobj_t at touching_sectorlist. precipsector_list = P_AddPrecipSecnode(ld->frontsector, tmprecipthing, precipsector_list); // Don't assume all lines are 2-sided, since some Things // like MT_TFOG are allowed regardless of whether their radius takes // them beyond an impassable linedef. // Use sidedefs instead of 2s flag to determine two-sidedness. if (ld->backsector) precipsector_list = P_AddPrecipSecnode(ld->backsector, tmprecipthing, precipsector_list); return true; } // P_CreateSecNodeList alters/creates the sector_list that shows what sectors // the object resides in. void P_CreateSecNodeList(mobj_t *thing, fixed_t x, fixed_t y) { int xl, xh, yl, yh, bx, by; msecnode_t *node; // First, clear out the existing m_thing fields. As each node is // added or verified as needed, m_thing will be set properly. When // finished, delete all nodes where m_thing is still NULL. These // represent the sectors the Thing has vacated. node = sector_list; while (node) { node->m_thing = NULL; node = node->m_tnext; } tmthing = thing; tmflags = thing->flags; tmx = x; tmy = y; tmbbox[BOXTOP] = y + tmthing->radius; tmbbox[BOXBOTTOM] = y - tmthing->radius; tmbbox[BOXRIGHT] = x + tmthing->radius; tmbbox[BOXLEFT] = x - tmthing->radius; validcount++; // used to make sure we only process a line once xl = (tmbbox[BOXLEFT] - bmaporgx)>>MAPBLOCKSHIFT; xh = (tmbbox[BOXRIGHT] - bmaporgx)>>MAPBLOCKSHIFT; yl = (tmbbox[BOXBOTTOM] - bmaporgy)>>MAPBLOCKSHIFT; yh = (tmbbox[BOXTOP] - bmaporgy)>>MAPBLOCKSHIFT; for (bx = xl; bx <= xh; bx++) for (by = yl; by <= yh; by++) P_BlockLinesIterator(bx, by, PIT_GetSectors); // Add the sector of the (x, y) point to sector_list. sector_list = P_AddSecnode(thing->subsector->sector, thing, sector_list); // Now delete any nodes that won't be used. These are the ones where // m_thing is still NULL. node = sector_list; while (node) { if (!node->m_thing) { if (node == sector_list) sector_list = node->m_tnext; node = P_DelSecnode(node); } else node = node->m_tnext; } } // More crazy crap Tails 08-25-2002 void P_CreatePrecipSecNodeList(precipmobj_t *thing,fixed_t x,fixed_t y) { int xl, xh, yl, yh, bx, by; mprecipsecnode_t *node; // First, clear out the existing m_thing fields. As each node is // added or verified as needed, m_thing will be set properly. When // finished, delete all nodes where m_thing is still NULL. These // represent the sectors the Thing has vacated. node = precipsector_list; while (node) { node->m_thing = NULL; node = node->m_tnext; } tmprecipthing = thing; preciptmflags = thing->flags; preciptmx = x; preciptmy = y; // Precipitation has a fixed radius of 2*FRACUNIT Tails 08-28-2002 preciptmbbox[BOXTOP] = y + 2*FRACUNIT; preciptmbbox[BOXBOTTOM] = y - 2*FRACUNIT; preciptmbbox[BOXRIGHT] = x + 2*FRACUNIT; preciptmbbox[BOXLEFT] = x - 2*FRACUNIT; validcount++; // used to make sure we only process a line once xl = (preciptmbbox[BOXLEFT] - bmaporgx)>>MAPBLOCKSHIFT; xh = (preciptmbbox[BOXRIGHT] - bmaporgx)>>MAPBLOCKSHIFT; yl = (preciptmbbox[BOXBOTTOM] - bmaporgy)>>MAPBLOCKSHIFT; yh = (preciptmbbox[BOXTOP] - bmaporgy)>>MAPBLOCKSHIFT; for (bx = xl; bx <= xh; bx++) for (by = yl; by <= yh; by++) P_BlockLinesIterator(bx, by, PIT_GetPrecipSectors); // Add the sector of the (x, y) point to sector_list. precipsector_list = P_AddPrecipSecnode(thing->subsector->sector, thing, precipsector_list); // Now delete any nodes that won't be used. These are the ones where // m_thing is still NULL. node = precipsector_list; while (node) { if (!node->m_thing) { if (node == precipsector_list) precipsector_list = node->m_tnext; node = P_DelPrecipSecnode(node); } else node = node->m_tnext; } } // P_FloorzAtPos // Returns the floorz of the XYZ position // Tails 05-26-2003 fixed_t P_FloorzAtPos(fixed_t x, fixed_t y, fixed_t z, fixed_t height) { sector_t *sec; fixed_t floorz; sec = R_PointInSubsector(x, y)->sector; floorz = sec->floorheight; // Intercept the stupid 'fall through 3dfloors' bug Tails 03-17-2002 if (sec->ffloors) { ffloor_t *rover; fixed_t delta1, delta2; int thingtop = z + height; for (rover = sec->ffloors; rover; rover = rover->next) { if (!(rover->flags & FF_EXISTS)) continue; if ((!(rover->flags & FF_SOLID || rover->flags & FF_QUICKSAND) || (rover->flags & FF_SWIMMABLE))) continue; if (rover->flags & FF_QUICKSAND) { if (z < *rover->topheight && *rover->bottomheight < thingtop) { floorz = z; continue; } } delta1 = z - (*rover->bottomheight + ((*rover->topheight - *rover->bottomheight)/2)); delta2 = thingtop - (*rover->bottomheight + ((*rover->topheight - *rover->bottomheight)/2)); if (*rover->topheight > floorz && abs(delta1) < abs(delta2)) floorz = *rover->topheight; } } return floorz; } // // P_FakeZMovement // // Fake the zmovement so that we can check if a move is legal // static void P_FakeZMovement(mobj_t *mo) { int dist; int delta; if (!mo->health) return; // Intercept the stupid 'fall through 3dfloors' bug Tails 03-17-2002 if (mo->subsector->sector->ffloors) { ffloor_t *rover; fixed_t delta1, delta2; int thingtop = mo->z + mo->height; for (rover = mo->subsector->sector->ffloors; rover; rover = rover->next) { if (!(rover->flags & FF_EXISTS)) continue; if ((!(rover->flags & FF_SOLID || rover->flags & FF_QUICKSAND) && !(mo->player && !mo->player->nightsmode && (((mo->player->charflags & SF_RUNONWATER) || mo->player->powers[pw_super]) && mo->ceilingz-*rover->topheight >= mo->height) && (rover->flags & FF_SWIMMABLE) && !mo->player->mfspinning && mo->player->speed > mo->player->runspeed && /*mo->ceilingz - *rover->topheight >= mo->height &&*/ mo->z < *rover->topheight + 30*FRACUNIT && mo->z > *rover->topheight - 30*FRACUNIT))) continue; if (rover->flags & FF_QUICKSAND) { if (mo->z < *rover->topheight && *rover->bottomheight < thingtop) { mo->floorz = mo->z; } continue; // This is so you can jump/spring up through quicksand from below. } delta1 = mo->z - (*rover->bottomheight + ((*rover->topheight - *rover->bottomheight)/2)); delta2 = thingtop - (*rover->bottomheight + ((*rover->topheight - *rover->bottomheight)/2)); if (*rover->topheight > mo->floorz && abs(delta1) < abs(delta2)) { mo->floorz = *rover->topheight; } if (*rover->bottomheight < mo->ceilingz && abs(delta1) >= abs(delta2) && (/*mo->z + mo->height <= *rover->bottomheight ||*/ !(rover->flags & FF_PLATFORM))) { mo->ceilingz = *rover->bottomheight; } } } // adjust height mo->z += mo->momz; if (mo->flags & MF_FLOAT && mo->target && mo->type != MT_EGGMOBILE && mo->type != MT_EGGMOBILE2 && mo->type != MT_RING && mo->type != MT_COIN) // Tails { // float down towards target if too close if (!(mo->flags2&MF2_SKULLFLY) && !(mo->flags2&MF2_INFLOAT)) { dist = P_AproxDistance(mo->x-mo->target->x, mo->y-mo->target->y); delta = (mo->target->z + (mo->height>>1)) - mo->z; if (delta < 0 && dist < -(delta*3)) mo->z -= FLOATSPEED; else if (delta > 0 && dist < (delta*3)) mo->z += FLOATSPEED; } } // clip movement if (mo->z <= mo->floorz && !(mo->flags2 & MF2_NOCLIPHEIGHT)) { // Hit the floor mo->z = mo->floorz; if (mo->momz < 0) mo->momz = 0; if (mo->flags2 & MF2_SKULLFLY) // The skull slammed into something mo->momz = -mo->momz; } else if (!(mo->flags & MF_NOGRAVITY)) { if (!mo->momz) mo->momz = -gravity*2; else mo->momz -= gravity; } if (mo->z + mo->height > mo->ceilingz && !(mo->flags2 & MF2_NOCLIPHEIGHT)) // hit the ceiling { if (mo->momz > 0) mo->momz = 0; mo->z = mo->ceilingz - mo->height; if (mo->flags2 & MF2_SKULLFLY) // the skull slammed into something mo->momz = -mo->momz; } } // P_CheckOnmobj // // Checks if the new Z position is legal // mobj_t *P_CheckOnmobj(mobj_t *thing) { int xl, xh, yl, yh; subsector_t *newsubsec; fixed_t x, y; mobj_t oldmo; x = thing->x; y = thing->y; tmthing = thing; tmflags = thing->flags; oldmo = *thing; // save the old mobj before the fake zmovement P_FakeZMovement(tmthing); tmx = x; tmy = y; tmbbox[BOXTOP] = y + tmthing->radius; tmbbox[BOXBOTTOM] = y - tmthing->radius; tmbbox[BOXRIGHT] = x + tmthing->radius; tmbbox[BOXLEFT] = x - tmthing->radius; newsubsec = R_PointInSubsector(x, y); ceilingline = NULL; // // the base floor / ceiling is from the subsector that contains the // point. Any contacted lines the step closer together will adjust them // tmfloorz = tmdropoffz = newsubsec->sector->floorheight; tmceilingz = newsubsec->sector->ceilingheight; validcount++; numspechit = 0; if (tmflags & MF_NOCLIP) return NULL; // // check things first, possibly picking things up // the bounding box is extended by MAXRADIUS because mobj_ts are grouped // into mapblocks based on their origin point, and can overlap into adjacent // blocks by up to MAXRADIUS units // xl = (tmbbox[BOXLEFT] - bmaporgx - MAXRADIUS)>>MAPBLOCKSHIFT; xh = (tmbbox[BOXRIGHT] - bmaporgx + MAXRADIUS)>>MAPBLOCKSHIFT; yl = (tmbbox[BOXBOTTOM] - bmaporgy - MAXRADIUS)>>MAPBLOCKSHIFT; yh = (tmbbox[BOXTOP] - bmaporgy + MAXRADIUS)>>MAPBLOCKSHIFT; *tmthing = oldmo; return NULL; }
[ "67659553+KrazeeTobi@users.noreply.github.com" ]
67659553+KrazeeTobi@users.noreply.github.com
e112fa75bfeb18fa01aeff6f46af3b4224fb8819
d4a2c50a90792600c4d864fffe9c1a9d1ebd6acc
/dssf3/DSS/Mmlib.cpp
3fdba89a485c16ab3d0967c3459fc6c61ef84c40
[]
no_license
iwasen/MyProg
3080316c3444e98d013587e92c066e278e796041
a0755a21d77647261df271ce301404a4e0294a7b
refs/heads/master
2022-12-30T00:28:07.539183
2020-10-25T06:36:27
2020-10-25T06:36:27
307,039,466
0
4
null
null
null
null
SHIFT_JIS
C++
false
false
1,193
cpp
// Mmlib.cpp : 実装ファイル // #include "stdafx.h" #include "DSS.h" #include "Mmlib.h" // CMmlib ダイアログ IMPLEMENT_DYNAMIC(CMmlib, CPropertyPage) CMmlib::CMmlib() : CPropertyPage(CMmlib::IDD) , m_sMmlibPath(_T("")) { } CMmlib::~CMmlib() { } void CMmlib::DoDataExchange(CDataExchange* pDX) { CPropertyPage::DoDataExchange(pDX); DDX_Text(pDX, IDC_MMLIB_PATH, m_sMmlibPath); } BEGIN_MESSAGE_MAP(CMmlib, CPropertyPage) ON_BN_CLICKED(IDC_REFERENCE_MMLIB, &CMmlib::OnBnClickedReferenceMmlib) END_MESSAGE_MAP() // CMmlib メッセージ ハンドラ BOOL CMmlib::OnInitDialog() { m_sMmlibPath = g_DssData.m_sMmlibPath; CPropertyPage::OnInitDialog(); return TRUE; } void CMmlib::OnOK() { strcpy_s(g_DssData.m_sMmlibPath, m_sMmlibPath); CPropertyPage::OnOK(); } void CMmlib::OnBnClickedReferenceMmlib() { CFileDialog fileDlg(TRUE, "exe", "MMLIB.exe", OFN_HIDEREADONLY | OFN_NOCHANGEDIR, "MMLIB executable file (MMLIB.exe)|MMLIB.exe||", this, 0); fileDlg.m_ofn.lpstrInitialDir = "C:\\"; if (fileDlg.DoModal() == IDOK) { m_sMmlibPath = fileDlg.GetPathName(); UpdateData(FALSE); } }
[ "git@iwasen.jp" ]
git@iwasen.jp
0edab1a04c21c002b8fe990b63936a5ada18b96b
b2c89ea1a26fdc97f97d164bd4acd062727563af
/matrix-test.cc
9277a3a4b62ef31a6cd7c7ab41c5f97b365b2bb9
[ "MIT" ]
permissive
songmeixu/bit-matrix
37d61fab47c36e637c5b78f7c3c7c8493a724a77
ae5196e8087e79c92b7760c1abb1c53362d671ca
refs/heads/master
2020-09-19T08:16:57.338366
2019-11-26T14:31:54
2019-11-26T14:31:54
224,211,105
0
0
null
null
null
null
UTF-8
C++
false
false
1,238
cc
// Copyright 2017 Baidu (author: Meixu Song) #include <iostream> #include <ctime> #include "matrix/matrix-common.h" #include "matrix/bit-matrix.h" #include "matrix/matrix-wrapper.h" using namespace std; using namespace snowboy; int main () { int cnt = 1; Matrix x(512, 512); Matrix y(512, 512); x.Set(1); y.Set(1); Matrix z(x.NumRows(), y.NumRows()); cout << "matrix mul. matrix: (512 * 512 * 512) " << endl; clock_t begin, end; begin = clock(); BitMatrix x_8(x, 8); BitMatrix y_1(y, 1, 8); Matrix z_8_1(x_8.NumRows(), y_1.NumRows()); for (int i = 0; i < cnt; ++i) { BitMatBitMat(x_8, y_1, &z_8_1); } end = clock(); double elapsed_secs_bit = double(end - begin) / CLOCKS_PER_SEC; begin = clock(); for (int i = 0; i < cnt; ++i) { z.MatMatRaw(x, y); } end = clock(); double elapsed_secs_raw = double(end - begin) / CLOCKS_PER_SEC; begin = clock(); for (int i = 0; i < cnt; ++i) { z.AddMatMat(1.0, x, kNoTrans, y, kTrans, 0.0); } end = clock(); double elapsed_secs = double(end - begin) / CLOCKS_PER_SEC; cout << "raw: " << elapsed_secs_raw << endl; cout << "bit: (8-1) " << elapsed_secs_bit << endl; cout << "cblas " << elapsed_secs << endl; return 0; }
[ "megasong@icloud.com" ]
megasong@icloud.com
5f60549a42712fdd21d800af31272cb99d1066c2
6259f84eeec2ff5ebb07cfadd3c74366698e65c9
/Measure/ThreePointCorrelation/Triplet.cpp
49aab0f2f988498c45130cc3bca56e8b488324ba
[]
no_license
TommasoRonconi/CosmoBolognaLib
5cdac37f4e66015c2c47ddc768a4fbfd7b6c92e8
524bd99ff51f6845f8da410909605f48824ee372
refs/heads/master
2020-03-10T12:23:31.915688
2018-04-08T09:49:56
2018-04-08T09:49:56
129,377,156
0
0
null
null
null
null
UTF-8
C++
false
false
8,209
cpp
/******************************************************************** * Copyright (C) 2010 by Federico Marulli, Michele Moresco * * and Alfonso Veropalumbo * * * * federico.marulli3@unibo.it * * * * This program is free software; you can redistribute it and/or * * modify it under the terms of the GNU General Public License as * * published by the Free Software Foundation; either version 2 of * * the License, or (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public * * License along with this program; if not, write to the Free * * Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ********************************************************************/ /** * @file Measure/ThreePointCorrelation/Triplet.cpp * * @brief Methods of the class Triplet * * This file contains the implementation of methods of the class Triplet, * used to handle pairs of objects to compute the two-point correlation function * * @authors Federico Marulli, Michele Moresco, Alfonso Veropalumbo * * @authors federico.marulli3@unbo.it, michele.moresco@unibo.it, * alfonso.veropalumbo@unibo.it */ #include "Triplet1D.h" #include "Triplet2D.h" using namespace cosmobl; using namespace triplets; // ============================================================================================ shared_ptr<Triplet> cosmobl::triplets::Triplet::Create (const TripletType type, const double r12, const double r12_binSize, const double r13, const double r13_binSize, const int nbins) { if (type==_comoving_theta_) return move(unique_ptr<Triplet1D_comoving_theta>{new Triplet1D_comoving_theta(r12, r12_binSize, r13, r13_binSize, nbins)}); else if (type==_comoving_side_) return move(unique_ptr<Triplet1D_comoving_side>{new Triplet1D_comoving_side(r12, r12_binSize, r13, r13_binSize, nbins)}); else ErrorCBL("Error in cosmobl::triplets::Create of Triplet.cpp: no such type of object!"); return NULL; } // ============================================================================================ // ============================================================================================ void cosmobl::triplets::Triplet1D::Sum (const shared_ptr<Triplet> tt, const double ww) { for (size_t i=0; i<m_TT1D.size(); i++) m_TT1D[i] += ww*tt->TT1D(i); } // ============================================================================================ // ============================================================================================ void cosmobl::triplets::Triplet1D_comoving_side::set_parameters () { double Lmin = (m_r13-0.5*m_r13_binSize)-(m_r12-0.5*m_r12_binSize); double Lmax = (m_r13+0.5*m_r13_binSize)+(m_r12+0.5*m_r12_binSize); m_binSize = (Lmax-Lmin)/m_nbins; m_scale.resize(m_nbins); for (int i=0; i<m_nbins; i++) m_scale[i] = (m_r12)*(m_r13-1)+((i+0.5)*m_binSize); } // ============================================================================================ void cosmobl::triplets::Triplet1D_comoving_side::get_triplet (const double r12, const double r13, const double r23, int &klin) { (void)r12; (void)r13; klin = int((r23-m_r12)/m_binSize); } // ============================================================================================ void cosmobl::triplets::Triplet1D_comoving_side::set_triplet (const int klin, const double ww) { m_TT1D[klin] += ww; } // ============================================================================================ void cosmobl::triplets::Triplet1D_comoving_side::put (const double r12, const double r13, const double r23, const double ww) { (void)r12; (void)r13; int klin = int((r23-m_r12)/m_binSize); m_TT1D[klin] += ww; } // ============================================================================================ void cosmobl::triplets::Triplet1D_comoving_side::put (const shared_ptr<catalogue::Object> obj1, const shared_ptr<catalogue::Object> obj2, const shared_ptr<catalogue::Object> obj3) { (void)obj1; double x2 = obj2->xx(), y2 = obj2->yy(), z2 = obj2->zz(), w2 = obj2->weight(); double x3 = obj3->xx(), y3 = obj3->yy(), z3 = obj3->zz(), w3 = obj3->weight(); double r23 = cosmobl::Euclidean_distance(x2, x3, y2, y3, z2, z3); double ww = w2*w3; int klin = int((r23-m_r12)/m_binSize); m_TT1D[klin] += ww; } // ============================================================================================ // ============================================================================================ void cosmobl::triplets::Triplet1D_comoving_theta::set_parameters () { m_binSize = par::pi/m_nbins; m_scale.resize(m_nbins); for (int i=0; i<m_nbins; i++) m_scale[i] = (i+0.5)*m_binSize/par::pi; } // ============================================================================================ void cosmobl::triplets::Triplet1D_comoving_theta::get_triplet (const double r12, const double r13, const double r23, int &klin) { double shift_angle = ((((r12*r12)+(r13*r13)-(r23*r23))/(2*r12*r13))<0.) ? 0.00000001 : -0.00000001; double angle = (abs((((r12*r12)+(r13*r13)-(r23*r23))/(2*r12*r13)))>0.99999999) ? acos((((r12*r12)+(r13*r13)-(r23*r23))/(2*r12*r13))+shift_angle) : acos(((r12*r12)+(r13*r13)-(r23*r23))/(2*r12*r13)); //angle = acos(((r12*r12)+(r13*r13)-(r23*r23))/(2*r12*r13)); klin = int(angle/m_binSize); } // ============================================================================================ void cosmobl::triplets::Triplet1D_comoving_theta::set_triplet (const int klin, const double ww) { m_TT1D[klin] += ww; } // ============================================================================================ void cosmobl::triplets::Triplet1D_comoving_theta::put (const double r12, const double r13, const double r23, const double ww) { double shift_angle = ((((r12*r12)+(r13*r13)-(r23*r23))/(2*r12*r13))<0.) ? 0.00000001 : -0.00000001; double angle = (abs((((r12*r12)+(r13*r13)-(r23*r23))/(2*r12*r13)))>0.99999999) ? acos((((r12*r12)+(r13*r13)-(r23*r23))/(2*r12*r13))+shift_angle) : acos(((r12*r12)+(r13*r13)-(r23*r23))/(2*r12*r13)); //angle = acos(((r12*r12)+(r13*r13)-(r23*r23))/(2*r12*r13)); int klin = int(angle/m_binSize); m_TT1D[klin] += ww; } // ============================================================================================ void cosmobl::triplets::Triplet1D_comoving_theta::put (const shared_ptr<catalogue::Object> obj1, const shared_ptr<catalogue::Object> obj2, const shared_ptr<catalogue::Object> obj3) { double x1 = obj1->xx(), y1 = obj1->yy(), z1 = obj1->zz(), w1 = obj1->weight(); double x2 = obj2->xx(), y2 = obj2->yy(), z2 = obj2->zz(), w2 = obj2->weight(); double x3 = obj3->xx(), y3 = obj3->yy(), z3 = obj3->zz(), w3 = obj3->weight(); double r12 = cosmobl::Euclidean_distance(x1, x2, y1, y2, z1, z2); double r13 = cosmobl::Euclidean_distance(x1, x3, y1, y3, z1, z3); double r23 = cosmobl::Euclidean_distance(x2, x3, y2, y3, z2, z3); double ww = w1*w2*w3; double shift_angle = ((((r12*r12)+(r13*r13)-(r23*r23))/(2*r12*r13))<0.) ? 0.00000001 : -0.00000001; double angle = (abs((((r12*r12)+(r13*r13)-(r23*r23))/(2*r12*r13)))>0.99999999) ? acos((((r12*r12)+(r13*r13)-(r23*r23))/(2*r12*r13))+shift_angle) : acos(((r12*r12)+(r13*r13)-(r23*r23))/(2*r12*r13)); //angle = acos(((r12*r12)+(r13*r13)-(r23*r23))/(2*r12*r13)); int klin = int(angle/m_binSize); m_TT1D[klin] += ww; }
[ "federico.marulli3@unibo.it" ]
federico.marulli3@unibo.it
dd0b7957688d60ecc222176cf5d554c81f2ffc5d
4a0915625aab3f601a1ef7ce6e89758d657fb44e
/tools/mclinker/include/mcld/Script/ScriptScanner.h
922c76d8a34d7eb36669518a43268a756875771a
[ "NCSA" ]
permissive
GuzTech/NyuziToolchain
5d0dcaca9e8a435b915d7bdf63cecbdcfb9e7a23
bec8ae23d3a348b8b9a7ed2b9217f6315d97d592
refs/heads/master
2021-01-17T23:22:49.685684
2015-04-11T20:46:22
2015-04-11T20:46:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,575
h
//===- ScriptScanner.h ----------------------------------------------------===// // // The MCLinker Project // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef MCLD_SCRIPT_SCRIPTSCANNER_H_ #define MCLD_SCRIPT_SCRIPTSCANNER_H_ #ifndef __FLEX_LEXER_H #include "FlexLexer.h" #endif #ifndef YY_DECL #define YY_DECL \ mcld::ScriptParser::token_type mcld::ScriptScanner::lex( \ mcld::ScriptParser::semantic_type* yylval, \ mcld::ScriptParser::location_type* yylloc, \ const mcld::ScriptFile& pScriptFile) #endif #include <mcld/Script/ScriptFile.h> #include "ScriptParser.h" #include <stack> namespace mcld { /** \class ScriptScanner * */ class ScriptScanner : public yyFlexLexer { public: explicit ScriptScanner(std::istream* yyin = NULL, std::ostream* yyout = NULL); virtual ~ScriptScanner(); virtual ScriptParser::token_type lex(ScriptParser::semantic_type* yylval, ScriptParser::location_type* yylloc, const ScriptFile& pScriptFile); void setLexState(ScriptFile::Kind pKind); void popLexState(); private: void enterComments(ScriptParser::location_type& pLocation); private: ScriptFile::Kind m_Kind; std::stack<ScriptFile::Kind> m_StateStack; }; } // namespace mcld #endif // MCLD_SCRIPT_SCRIPTSCANNER_H_
[ "jeffbush001@gmail.com" ]
jeffbush001@gmail.com
090291ccfdd76892dd80db6fd2566510a64ca832
c432cf3a7db8cd558c7d8b66f9a7be62064ae5a8
/C++/00_general/25_nested_class/nested_class.cpp
423a3091473dc0dc84bfc9b27910bce46a3d1475
[]
no_license
babakpst/Learning
19867acf37145fed8acfd1321ec49b7eba217042
945ffb6136b4cb7944810834db1366d8ee5128ad
refs/heads/master
2023-08-09T06:57:49.476966
2023-08-04T13:48:02
2023-08-04T13:48:02
158,579,987
4
0
null
2020-08-28T21:07:05
2018-11-21T16:53:53
C++
UTF-8
C++
false
false
2,093
cpp
// Babak Poursartip // 09/08/2020 // Nested class / Inner class // The nested class is also a member variable of the enclosing class and has the same access rights as the other members. However, the member functions of the enclosing class have no special access to the members of a nested class. //In C++, unlike (say) Java, an instance of a nested class doesn't intrinsically belong to any instance of the enclosing class. #include<iostream> using namespace std; // ================================= class A { private: int x; struct C { C(){cout << " default C\n";} C(int x):y{x}{} int y; void print(){cout << "this is insided the inner class: C\n";} }; C m_innerC; public: A(){cout << "A defalt ctor\n";} //A(int x):x{x}, innerC(x){cout << "A ctor\n";} struct B { private: int num; public: B(){cout << " default B\n";} void setdata(int n) {num = n;} void getdata() {cout<<"The number is "<<num<< endl;} void check(){ cout << "access private memeber:\n"; //m_innerC.y= 15; //cout << " innerC value: " << innerC.y << "\n"; cout << " innerC value: " << num << "\n"; //innerC.print(); } }; B innerB; //C innerC; }; // ========================================== class List { public: List(): head(nullptr), tail(nullptr) {} private: class Node { public: int data; Node* next; Node* prev; }; private: Node* head; Node* tail; }; // =================================================== int main() { cout<<"Nested classes in C++"<< endl; A::B obj; //A::C obj2; // error C is private obj.setdata(9); obj.getdata(); A a; a.innerB.setdata(12); a.innerB.getdata(); a.innerB.check(); //a.m_innerC.print(); // m_innerC is private. //a.innerC.NestedFun(&a); // error innerC is private //A::C obj2; // C is private return 0; }
[ "babakpst@gmail.com" ]
babakpst@gmail.com
9e788711520586513e1389ff0fbf2e91bb35a354
f86d8682bfd7961f2633b268bb342a953efac152
/transpiler/netlist_utils.h
9632c6de2cf8fd394e2a58b3e559b0fbb0d958bc
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
google/fully-homomorphic-encryption
b0484efd43503c951c21ae92719401cb6bdb8e11
c3ce0498b85fbf891ff83e2345e194d0141a0033
refs/heads/main
2023-08-31T17:15:42.946914
2023-08-24T20:49:40
2023-08-24T20:50:19
364,705,340
3,419
249
Apache-2.0
2023-09-06T13:36:59
2021-05-05T21:04:00
C++
UTF-8
C++
false
false
6,801
h
// Copyright 2021 Google LLC // // 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. // Helper functions for Boolean YoSys Transpiler. #ifndef FULLY_HOMOMORPHIC_ENCRYPTION_TRANSPILER_NETLIST_UTILS_H #define FULLY_HOMOMORPHIC_ENCRYPTION_TRANSPILER_NETLIST_UTILS_H #include <functional> #include <string> #include <vector> #include "absl/status/statusor.h" #include "absl/strings/string_view.h" #include "xls/netlist/netlist.h" namespace fully_homomorphic_encryption { namespace transpiler { absl::StatusOr<::xls::netlist::AbstractCellLibrary<bool>> ParseCellLibrary( const absl::string_view cell_library_text); absl::StatusOr<std::unique_ptr<::xls::netlist::rtl::AbstractNetlist<bool>>> ParseNetlist(::xls::netlist::AbstractCellLibrary<bool>& cell_library, const absl::string_view netlist_text); // Returns the list of cell names in topologically sorted order, or return an // error if the netlist is cyclic. An error should be impossible for FHE // programs, since they are represented as pure combinational circuits. absl::StatusOr<std::vector<std::string>> TopoSortedCellNames( const xls::netlist::rtl::AbstractModule<bool>& module); // Returns a vector of vectors of node names, where each vector represents // a different level in the graph. Nodes in the same level can be executed in // parallel. // Returns an error if the netlist is cyclic. An error should be impossible for // FHE programs, since they are represented as pure combinational circuits. absl::StatusOr<std::vector<std::vector<std::string>>> LevelSortedCellNames( const xls::netlist::rtl::AbstractModule<bool>& module); // The set of inputs to a gate, along with a truth table, if the gate contains a // truth table hard coded among its input gates. struct GateInputs { std::vector<std::string> inputs; uint64_t lut_definition; }; // Data describing the output of a cell. struct GateOutput { // The full name of the output netref, e.g., `out`, `out[4]`, or `_5_` std::string name; // Whether the output is part of a netref with more than one bit. // E.g., for `out[4]` this field is true, but for `out` and `_5_` // it is false. bool is_single_bit; // The integer part of the full name, is_single_bit is false int index; // True if the output corresponds to the module's output net. bool is_output; }; // The template functions for handling language-specific constructions // E.g., in a Python backend a gate output is stored to temp_nodes[$0], // but in another backend it will have a different syntax. class CodegenTemplates { public: virtual ~CodegenTemplates() = default; // A function that maps a constant, public integer to the corresponding // ciphertext. E.g., it might map 1 -> 'jaxite_bool.constant(True, params)' virtual std::string ConstantCiphertext(int value) const = 0; // A function that resolves an expression reference to a prior gate output, // such as the input "4" representing the value on wire _4_. virtual std::string PriorGateOutputReference(absl::string_view ref) const = 0; // A function that resolves an expression reference to an input or output // netref, like my_input[0] virtual std::string InputOrOutputReference(absl::string_view ref) const = 0; }; // Convert a netlist cell identifier `_\d+_` into the numeric part of the // identifier. absl::StatusOr<int> NetRefIdToNumericId(absl::string_view netref_id); // Convert a netlist cell identifier `foo[\d+]` into the numeric part of the // index. If there is none, default to 0. absl::StatusOr<int> NetRefIdToIndex(absl::string_view netref_id); // Get the part of a string like `foo[7]` before the first `[`. // Since some inputs and outputs can be single-bits, the `[7]` is also optional std::string NetRefStem(std::string_view netref); // Convert a string like <constant_5> to the integer 5. absl::StatusOr<int> ConstantToValue(std::string_view constant); // Convert a net reference into the corresponding language-specific // backend. absl::StatusOr<std::string> ResolveNetRefName( const xls::netlist::rtl::AbstractNetRef<bool>& netref, const CodegenTemplates& templates); // Returns the set of gate inputs to a given gate. // Example 1 (not a LUT): // Input: imux2 _3_ (.A(_0_), .B(_1_), .S(_2_), .Y(_3_)) // Output: {Inputs: "0", "1", "2", lut_definition=0} // // Example 2 (a LUT): // Input: lut2 _11_ (.A(_02_), .B(x[7]), // .P0(1'h1), .P1(1'h0), .P2(1'h1), .P3(1'h1), .Y(out[7])); // Output: {Inputs: "temp_nodes[2]", "x[7]", lut_definition=13} // ^ little endian // // Note, some of these gates are not symmetric in their inputs. This // implementation assumes that the order in which the inputs are parsed is // the same as the order in which they occur in the liberty cell spec. // I.e., for this cell definition: // // cell(imux2) { // pin(A) { direction : input; } // pin(B) { direction : input; } // pin(S) { direction : input; } // pin(Y) { function : "(A * S) + (B * (S'))"; } // } // // it is critical that the order of A, B, S are unchanged // at the callsite. // // imux2 _3_ (.A(_0_), .B(_1_), .S(_2_), .Y(_3_)); // // Circuits output by Yosys appear to uphold this guarantee in their output, // and the XLS netlist parser appears to preserve this after parsing. // // Note that to avoid this assumption, we would need to also process the // liberty file cell definition, and somehow connect the symbols used in its // input to the corresponding inputs to give to jaxite_bool's functions. // This is a lot more work. absl::StatusOr<GateInputs> ExtractGateInputs( const xls::netlist::rtl::AbstractCell<bool>* cell, const CodegenTemplates& templates); // The same as the above method, but only extracts the numeric ids for the // inputs to this cell that correspond to the outputs of previously evaluated // cells. absl::StatusOr<std::vector<int>> ExtractPriorGateOutputIds( const xls::netlist::rtl::AbstractCell<bool>* cell); // Extract the output data for a single cell absl::StatusOr<GateOutput> ExtractGateOutput( const xls::netlist::rtl::AbstractCell<bool>* cell); } // namespace transpiler } // namespace fully_homomorphic_encryption #endif // FULLY_HOMOMORPHIC_ENCRYPTION_TRANSPILER_NETLIST_UTILS_H
[ "copybara-worker@google.com" ]
copybara-worker@google.com
c71d3d4c11decb489484c038709cbbd3f2cede9b
bd1fea86d862456a2ec9f56d57f8948456d55ee6
/000/241/581/CWE761_Free_Pointer_Not_at_Start_of_Buffer__wchar_t_console_81.h
95e482694aca0b6afce2d158034ff0bf0ba2b02d
[]
no_license
CU-0xff/juliet-cpp
d62b8485104d8a9160f29213368324c946f38274
d8586a217bc94cbcfeeec5d39b12d02e9c6045a2
refs/heads/master
2021-03-07T15:44:19.446957
2020-03-10T12:45:40
2020-03-10T12:45:40
246,275,244
0
1
null
null
null
null
UTF-8
C++
false
false
1,381
h
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE761_Free_Pointer_Not_at_Start_of_Buffer__wchar_t_console_81.h Label Definition File: CWE761_Free_Pointer_Not_at_Start_of_Buffer.label.xml Template File: source-sinks-81.tmpl.h */ /* * @description * CWE: 761 Free Pointer not at Start of Buffer * BadSource: console Read input from the console * Sinks: * GoodSink: free() memory correctly at the start of the buffer * BadSink : free() memory not at the start of the buffer * Flow Variant: 81 Data flow: data passed in a parameter to an virtual method called via a reference * * */ #include "std_testcase.h" #include <wchar.h> namespace CWE761_Free_Pointer_Not_at_Start_of_Buffer__wchar_t_console_81 { class CWE761_Free_Pointer_Not_at_Start_of_Buffer__wchar_t_console_81_base { public: /* pure virtual function */ virtual void action(wchar_t * data) const = 0; }; #ifndef OMITBAD class CWE761_Free_Pointer_Not_at_Start_of_Buffer__wchar_t_console_81_bad : public CWE761_Free_Pointer_Not_at_Start_of_Buffer__wchar_t_console_81_base { public: void action(wchar_t * data) const; }; #endif /* OMITBAD */ #ifndef OMITGOOD class CWE761_Free_Pointer_Not_at_Start_of_Buffer__wchar_t_console_81_goodB2G : public CWE761_Free_Pointer_Not_at_Start_of_Buffer__wchar_t_console_81_base { public: void action(wchar_t * data) const; }; #endif /* OMITGOOD */ }
[ "frank@fischer.com.mt" ]
frank@fischer.com.mt
6b6f2545c0212a1c26df30effbb72d9868612973
4ac9803a024d6915909293bbcd37a618ccaffc8f
/solution1/.autopilot/db/mandelbrot.pp.0.cpp
1799a1f8f5d2be9cacd60a4db3f65a4c77630f80
[]
no_license
veranki/mandelbrot-hls
e2a8b158c38db94e50f161de6712108ebc2d1418
6b400e502b9956871b6a2f1c50d3f9f8c686921d
refs/heads/master
2020-03-18T05:46:23.886784
2018-05-22T04:16:17
2018-05-22T04:16:17
134,360,590
1
0
null
null
null
null
UTF-8
C++
false
false
62,417
cpp
# 1 "mandelbrot-hls/mandelbrot.cpp" # 1 "mandelbrot-hls/mandelbrot.cpp" 1 # 1 "<built-in>" 1 # 1 "<built-in>" 3 # 155 "<built-in>" 3 # 1 "<command line>" 1 # 1 "/opt/Xilinx/Vivado/2017.4/common/technology/autopilot/etc/autopilot_ssdm_op.h" 1 # 156 "/opt/Xilinx/Vivado/2017.4/common/technology/autopilot/etc/autopilot_ssdm_op.h" extern "C" { typedef bool _uint1_; void _ssdm_op_IfRead(...) __attribute__ ((nothrow)); void _ssdm_op_IfWrite(...) __attribute__ ((nothrow)); _uint1_ _ssdm_op_IfNbRead(...) __attribute__ ((nothrow)); _uint1_ _ssdm_op_IfNbWrite(...) __attribute__ ((nothrow)); _uint1_ _ssdm_op_IfCanRead(...) __attribute__ ((nothrow)); _uint1_ _ssdm_op_IfCanWrite(...) __attribute__ ((nothrow)); void _ssdm_StreamRead(...) __attribute__ ((nothrow)); void _ssdm_StreamWrite(...) __attribute__ ((nothrow)); _uint1_ _ssdm_StreamNbRead(...) __attribute__ ((nothrow)); _uint1_ _ssdm_StreamNbWrite(...) __attribute__ ((nothrow)); _uint1_ _ssdm_StreamCanRead(...) __attribute__ ((nothrow)); _uint1_ _ssdm_StreamCanWrite(...) __attribute__ ((nothrow)); unsigned _ssdm_StreamSize(...) __attribute__ ((nothrow)); void _ssdm_op_MemShiftRead(...) __attribute__ ((nothrow)); void _ssdm_op_Wait(...) __attribute__ ((nothrow)); void _ssdm_op_Poll(...) __attribute__ ((nothrow)); void _ssdm_op_Return(...) __attribute__ ((nothrow)); void _ssdm_op_SpecSynModule(...) __attribute__ ((nothrow)); void _ssdm_op_SpecTopModule(...) __attribute__ ((nothrow)); void _ssdm_op_SpecProcessDecl(...) __attribute__ ((nothrow)); void _ssdm_op_SpecProcessDef(...) __attribute__ ((nothrow)); void _ssdm_op_SpecPort(...) __attribute__ ((nothrow)); void _ssdm_op_SpecConnection(...) __attribute__ ((nothrow)); void _ssdm_op_SpecChannel(...) __attribute__ ((nothrow)); void _ssdm_op_SpecSensitive(...) __attribute__ ((nothrow)); void _ssdm_op_SpecModuleInst(...) __attribute__ ((nothrow)); void _ssdm_op_SpecPortMap(...) __attribute__ ((nothrow)); void _ssdm_op_SpecReset(...) __attribute__ ((nothrow)); void _ssdm_op_SpecPlatform(...) __attribute__ ((nothrow)); void _ssdm_op_SpecClockDomain(...) __attribute__ ((nothrow)); void _ssdm_op_SpecPowerDomain(...) __attribute__ ((nothrow)); int _ssdm_op_SpecRegionBegin(...) __attribute__ ((nothrow)); int _ssdm_op_SpecRegionEnd(...) __attribute__ ((nothrow)); void _ssdm_op_SpecLoopName(...) __attribute__ ((nothrow)); void _ssdm_op_SpecLoopTripCount(...) __attribute__ ((nothrow)); int _ssdm_op_SpecStateBegin(...) __attribute__ ((nothrow)); int _ssdm_op_SpecStateEnd(...) __attribute__ ((nothrow)); void _ssdm_op_SpecInterface(...) __attribute__ ((nothrow)); void _ssdm_op_SpecPipeline(...) __attribute__ ((nothrow)); void _ssdm_op_SpecDataflowPipeline(...) __attribute__ ((nothrow)); void _ssdm_op_SpecLatency(...) __attribute__ ((nothrow)); void _ssdm_op_SpecParallel(...) __attribute__ ((nothrow)); void _ssdm_op_SpecProtocol(...) __attribute__ ((nothrow)); void _ssdm_op_SpecOccurrence(...) __attribute__ ((nothrow)); void _ssdm_op_SpecResource(...) __attribute__ ((nothrow)); void _ssdm_op_SpecResourceLimit(...) __attribute__ ((nothrow)); void _ssdm_op_SpecCHCore(...) __attribute__ ((nothrow)); void _ssdm_op_SpecFUCore(...) __attribute__ ((nothrow)); void _ssdm_op_SpecIFCore(...) __attribute__ ((nothrow)); void _ssdm_op_SpecIPCore(...) __attribute__ ((nothrow)); void _ssdm_op_SpecKeepValue(...) __attribute__ ((nothrow)); void _ssdm_op_SpecMemCore(...) __attribute__ ((nothrow)); void _ssdm_op_SpecExt(...) __attribute__ ((nothrow)); void _ssdm_SpecArrayDimSize(...) __attribute__ ((nothrow)); void _ssdm_RegionBegin(...) __attribute__ ((nothrow)); void _ssdm_RegionEnd(...) __attribute__ ((nothrow)); void _ssdm_Unroll(...) __attribute__ ((nothrow)); void _ssdm_UnrollRegion(...) __attribute__ ((nothrow)); void _ssdm_InlineAll(...) __attribute__ ((nothrow)); void _ssdm_InlineLoop(...) __attribute__ ((nothrow)); void _ssdm_Inline(...) __attribute__ ((nothrow)); void _ssdm_InlineSelf(...) __attribute__ ((nothrow)); void _ssdm_InlineRegion(...) __attribute__ ((nothrow)); void _ssdm_SpecArrayMap(...) __attribute__ ((nothrow)); void _ssdm_SpecArrayPartition(...) __attribute__ ((nothrow)); void _ssdm_SpecArrayReshape(...) __attribute__ ((nothrow)); void _ssdm_SpecStream(...) __attribute__ ((nothrow)); void _ssdm_SpecExpr(...) __attribute__ ((nothrow)); void _ssdm_SpecExprBalance(...) __attribute__ ((nothrow)); void _ssdm_SpecDependence(...) __attribute__ ((nothrow)); void _ssdm_SpecLoopMerge(...) __attribute__ ((nothrow)); void _ssdm_SpecLoopFlatten(...) __attribute__ ((nothrow)); void _ssdm_SpecLoopRewind(...) __attribute__ ((nothrow)); void _ssdm_SpecFuncInstantiation(...) __attribute__ ((nothrow)); void _ssdm_SpecFuncBuffer(...) __attribute__ ((nothrow)); void _ssdm_SpecFuncExtract(...) __attribute__ ((nothrow)); void _ssdm_SpecConstant(...) __attribute__ ((nothrow)); void _ssdm_DataPack(...) __attribute__ ((nothrow)); void _ssdm_SpecDataPack(...) __attribute__ ((nothrow)); void _ssdm_op_SpecBitsMap(...) __attribute__ ((nothrow)); void _ssdm_op_SpecLicense(...) __attribute__ ((nothrow)); void __xilinx_ip_top(...) __attribute__ ((nothrow)); } # 8 "<command line>" 2 # 1 "<built-in>" 2 # 1 "mandelbrot-hls/mandelbrot.cpp" 2 # 1 "mandelbrot-hls/mandelbrot.h" 1 # 1 "/opt/Xilinx/Vivado/2017.4/lnx64/tools/gcc/lib/gcc/x86_64-unknown-linux-gnu/4.6.3/../../../../include/c++/4.6.3/cmath" 1 3 # 41 "/opt/Xilinx/Vivado/2017.4/lnx64/tools/gcc/lib/gcc/x86_64-unknown-linux-gnu/4.6.3/../../../../include/c++/4.6.3/cmath" 3 # 41 "/opt/Xilinx/Vivado/2017.4/lnx64/tools/gcc/lib/gcc/x86_64-unknown-linux-gnu/4.6.3/../../../../include/c++/4.6.3/cmath" 3 # 1 "/opt/Xilinx/Vivado/2017.4/lnx64/tools/gcc/lib/gcc/x86_64-unknown-linux-gnu/4.6.3/../../../../include/c++/4.6.3/x86_64-unknown-linux-gnu/bits/c++config.h" 1 3 # 153 "/opt/Xilinx/Vivado/2017.4/lnx64/tools/gcc/lib/gcc/x86_64-unknown-linux-gnu/4.6.3/../../../../include/c++/4.6.3/x86_64-unknown-linux-gnu/bits/c++config.h" 3 namespace std { typedef long unsigned int size_t; typedef long int ptrdiff_t; } # 393 "/opt/Xilinx/Vivado/2017.4/lnx64/tools/gcc/lib/gcc/x86_64-unknown-linux-gnu/4.6.3/../../../../include/c++/4.6.3/x86_64-unknown-linux-gnu/bits/c++config.h" 3 # 1 "/opt/Xilinx/Vivado/2017.4/lnx64/tools/gcc/lib/gcc/x86_64-unknown-linux-gnu/4.6.3/../../../../include/c++/4.6.3/x86_64-unknown-linux-gnu/bits/os_defines.h" 1 3 # 40 "/opt/Xilinx/Vivado/2017.4/lnx64/tools/gcc/lib/gcc/x86_64-unknown-linux-gnu/4.6.3/../../../../include/c++/4.6.3/x86_64-unknown-linux-gnu/bits/os_defines.h" 3 # 1 "/usr/include/features.h" 1 3 4 # 345 "/usr/include/features.h" 3 4 # 1 "/usr/include/stdc-predef.h" 1 3 4 # 346 "/usr/include/features.h" 2 3 4 # 367 "/usr/include/features.h" 3 4 # 1 "/usr/include/x86_64-linux-gnu/sys/cdefs.h" 1 3 4 # 410 "/usr/include/x86_64-linux-gnu/sys/cdefs.h" 3 4 # 1 "/usr/include/x86_64-linux-gnu/bits/wordsize.h" 1 3 4 # 411 "/usr/include/x86_64-linux-gnu/sys/cdefs.h" 2 3 4 # 368 "/usr/include/features.h" 2 3 4 # 391 "/usr/include/features.h" 3 4 # 1 "/usr/include/x86_64-linux-gnu/gnu/stubs.h" 1 3 4 # 10 "/usr/include/x86_64-linux-gnu/gnu/stubs.h" 3 4 # 1 "/usr/include/x86_64-linux-gnu/gnu/stubs-64.h" 1 3 4 # 11 "/usr/include/x86_64-linux-gnu/gnu/stubs.h" 2 3 4 # 392 "/usr/include/features.h" 2 3 4 # 41 "/opt/Xilinx/Vivado/2017.4/lnx64/tools/gcc/lib/gcc/x86_64-unknown-linux-gnu/4.6.3/../../../../include/c++/4.6.3/x86_64-unknown-linux-gnu/bits/os_defines.h" 2 3 # 394 "/opt/Xilinx/Vivado/2017.4/lnx64/tools/gcc/lib/gcc/x86_64-unknown-linux-gnu/4.6.3/../../../../include/c++/4.6.3/x86_64-unknown-linux-gnu/bits/c++config.h" 2 3 # 1 "/opt/Xilinx/Vivado/2017.4/lnx64/tools/gcc/lib/gcc/x86_64-unknown-linux-gnu/4.6.3/../../../../include/c++/4.6.3/x86_64-unknown-linux-gnu/bits/cpu_defines.h" 1 3 # 397 "/opt/Xilinx/Vivado/2017.4/lnx64/tools/gcc/lib/gcc/x86_64-unknown-linux-gnu/4.6.3/../../../../include/c++/4.6.3/x86_64-unknown-linux-gnu/bits/c++config.h" 2 3 # 43 "/opt/Xilinx/Vivado/2017.4/lnx64/tools/gcc/lib/gcc/x86_64-unknown-linux-gnu/4.6.3/../../../../include/c++/4.6.3/cmath" 2 3 # 1 "/opt/Xilinx/Vivado/2017.4/lnx64/tools/gcc/lib/gcc/x86_64-unknown-linux-gnu/4.6.3/../../../../include/c++/4.6.3/bits/cpp_type_traits.h" 1 3 # 36 "/opt/Xilinx/Vivado/2017.4/lnx64/tools/gcc/lib/gcc/x86_64-unknown-linux-gnu/4.6.3/../../../../include/c++/4.6.3/bits/cpp_type_traits.h" 3 # 36 "/opt/Xilinx/Vivado/2017.4/lnx64/tools/gcc/lib/gcc/x86_64-unknown-linux-gnu/4.6.3/../../../../include/c++/4.6.3/bits/cpp_type_traits.h" 3 # 68 "/opt/Xilinx/Vivado/2017.4/lnx64/tools/gcc/lib/gcc/x86_64-unknown-linux-gnu/4.6.3/../../../../include/c++/4.6.3/bits/cpp_type_traits.h" 3 namespace __gnu_cxx __attribute__ ((__visibility__ ("default"))) { template<typename _Iterator, typename _Container> class __normal_iterator; } namespace std __attribute__ ((__visibility__ ("default"))) { struct __true_type { }; struct __false_type { }; template<bool> struct __truth_type { typedef __false_type __type; }; template<> struct __truth_type<true> { typedef __true_type __type; }; template<class _Sp, class _Tp> struct __traitor { enum { __value = bool(_Sp::__value) || bool(_Tp::__value) }; typedef typename __truth_type<__value>::__type __type; }; template<typename, typename> struct __are_same { enum { __value = 0 }; typedef __false_type __type; }; template<typename _Tp> struct __are_same<_Tp, _Tp> { enum { __value = 1 }; typedef __true_type __type; }; template<typename _Tp> struct __is_void { enum { __value = 0 }; typedef __false_type __type; }; template<> struct __is_void<void> { enum { __value = 1 }; typedef __true_type __type; }; template<typename _Tp> struct __is_integer { enum { __value = 0 }; typedef __false_type __type; }; template<> struct __is_integer<bool> { enum { __value = 1 }; typedef __true_type __type; }; template<> struct __is_integer<char> { enum { __value = 1 }; typedef __true_type __type; }; template<> struct __is_integer<signed char> { enum { __value = 1 }; typedef __true_type __type; }; template<> struct __is_integer<unsigned char> { enum { __value = 1 }; typedef __true_type __type; }; template<> struct __is_integer<wchar_t> { enum { __value = 1 }; typedef __true_type __type; }; # 198 "/opt/Xilinx/Vivado/2017.4/lnx64/tools/gcc/lib/gcc/x86_64-unknown-linux-gnu/4.6.3/../../../../include/c++/4.6.3/bits/cpp_type_traits.h" 3 template<> struct __is_integer<short> { enum { __value = 1 }; typedef __true_type __type; }; template<> struct __is_integer<unsigned short> { enum { __value = 1 }; typedef __true_type __type; }; template<> struct __is_integer<int> { enum { __value = 1 }; typedef __true_type __type; }; template<> struct __is_integer<unsigned int> { enum { __value = 1 }; typedef __true_type __type; }; template<> struct __is_integer<long> { enum { __value = 1 }; typedef __true_type __type; }; template<> struct __is_integer<unsigned long> { enum { __value = 1 }; typedef __true_type __type; }; template<> struct __is_integer<long long> { enum { __value = 1 }; typedef __true_type __type; }; template<> struct __is_integer<unsigned long long> { enum { __value = 1 }; typedef __true_type __type; }; template<typename _Tp> struct __is_floating { enum { __value = 0 }; typedef __false_type __type; }; template<> struct __is_floating<float> { enum { __value = 1 }; typedef __true_type __type; }; template<> struct __is_floating<double> { enum { __value = 1 }; typedef __true_type __type; }; template<> struct __is_floating<long double> { enum { __value = 1 }; typedef __true_type __type; }; template<typename _Tp> struct __is_pointer { enum { __value = 0 }; typedef __false_type __type; }; template<typename _Tp> struct __is_pointer<_Tp*> { enum { __value = 1 }; typedef __true_type __type; }; template<typename _Tp> struct __is_normal_iterator { enum { __value = 0 }; typedef __false_type __type; }; template<typename _Iterator, typename _Container> struct __is_normal_iterator< __gnu_cxx::__normal_iterator<_Iterator, _Container> > { enum { __value = 1 }; typedef __true_type __type; }; template<typename _Tp> struct __is_arithmetic : public __traitor<__is_integer<_Tp>, __is_floating<_Tp> > { }; template<typename _Tp> struct __is_fundamental : public __traitor<__is_void<_Tp>, __is_arithmetic<_Tp> > { }; template<typename _Tp> struct __is_scalar : public __traitor<__is_arithmetic<_Tp>, __is_pointer<_Tp> > { }; template<typename _Tp> struct __is_char { enum { __value = 0 }; typedef __false_type __type; }; template<> struct __is_char<char> { enum { __value = 1 }; typedef __true_type __type; }; template<> struct __is_char<wchar_t> { enum { __value = 1 }; typedef __true_type __type; }; template<typename _Tp> struct __is_byte { enum { __value = 0 }; typedef __false_type __type; }; template<> struct __is_byte<char> { enum { __value = 1 }; typedef __true_type __type; }; template<> struct __is_byte<signed char> { enum { __value = 1 }; typedef __true_type __type; }; template<> struct __is_byte<unsigned char> { enum { __value = 1 }; typedef __true_type __type; }; template<typename _Tp> struct __is_move_iterator { enum { __value = 0 }; typedef __false_type __type; }; # 422 "/opt/Xilinx/Vivado/2017.4/lnx64/tools/gcc/lib/gcc/x86_64-unknown-linux-gnu/4.6.3/../../../../include/c++/4.6.3/bits/cpp_type_traits.h" 3 } # 44 "/opt/Xilinx/Vivado/2017.4/lnx64/tools/gcc/lib/gcc/x86_64-unknown-linux-gnu/4.6.3/../../../../include/c++/4.6.3/cmath" 2 3 # 1 "/opt/Xilinx/Vivado/2017.4/lnx64/tools/gcc/lib/gcc/x86_64-unknown-linux-gnu/4.6.3/../../../../include/c++/4.6.3/ext/type_traits.h" 1 3 # 33 "/opt/Xilinx/Vivado/2017.4/lnx64/tools/gcc/lib/gcc/x86_64-unknown-linux-gnu/4.6.3/../../../../include/c++/4.6.3/ext/type_traits.h" 3 # 33 "/opt/Xilinx/Vivado/2017.4/lnx64/tools/gcc/lib/gcc/x86_64-unknown-linux-gnu/4.6.3/../../../../include/c++/4.6.3/ext/type_traits.h" 3 namespace __gnu_cxx __attribute__ ((__visibility__ ("default"))) { template<bool, typename> struct __enable_if { }; template<typename _Tp> struct __enable_if<true, _Tp> { typedef _Tp __type; }; template<bool _Cond, typename _Iftrue, typename _Iffalse> struct __conditional_type { typedef _Iftrue __type; }; template<typename _Iftrue, typename _Iffalse> struct __conditional_type<false, _Iftrue, _Iffalse> { typedef _Iffalse __type; }; template<typename _Tp> struct __add_unsigned { private: typedef __enable_if<std::__is_integer<_Tp>::__value, _Tp> __if_type; public: typedef typename __if_type::__type __type; }; template<> struct __add_unsigned<char> { typedef unsigned char __type; }; template<> struct __add_unsigned<signed char> { typedef unsigned char __type; }; template<> struct __add_unsigned<short> { typedef unsigned short __type; }; template<> struct __add_unsigned<int> { typedef unsigned int __type; }; template<> struct __add_unsigned<long> { typedef unsigned long __type; }; template<> struct __add_unsigned<long long> { typedef unsigned long long __type; }; template<> struct __add_unsigned<bool>; template<> struct __add_unsigned<wchar_t>; template<typename _Tp> struct __remove_unsigned { private: typedef __enable_if<std::__is_integer<_Tp>::__value, _Tp> __if_type; public: typedef typename __if_type::__type __type; }; template<> struct __remove_unsigned<char> { typedef signed char __type; }; template<> struct __remove_unsigned<unsigned char> { typedef signed char __type; }; template<> struct __remove_unsigned<unsigned short> { typedef short __type; }; template<> struct __remove_unsigned<unsigned int> { typedef int __type; }; template<> struct __remove_unsigned<unsigned long> { typedef long __type; }; template<> struct __remove_unsigned<unsigned long long> { typedef long long __type; }; template<> struct __remove_unsigned<bool>; template<> struct __remove_unsigned<wchar_t>; template<typename _Type> inline bool __is_null_pointer(_Type* __ptr) { return __ptr == 0; } template<typename _Type> inline bool __is_null_pointer(_Type) { return false; } template<typename _Tp, bool = std::__is_integer<_Tp>::__value> struct __promote { typedef double __type; }; template<typename _Tp> struct __promote<_Tp, false> { }; template<> struct __promote<long double> { typedef long double __type; }; template<> struct __promote<double> { typedef double __type; }; template<> struct __promote<float> { typedef float __type; }; template<typename _Tp, typename _Up, typename _Tp2 = typename __promote<_Tp>::__type, typename _Up2 = typename __promote<_Up>::__type> struct __promote_2 { typedef __typeof__(_Tp2() + _Up2()) __type; }; template<typename _Tp, typename _Up, typename _Vp, typename _Tp2 = typename __promote<_Tp>::__type, typename _Up2 = typename __promote<_Up>::__type, typename _Vp2 = typename __promote<_Vp>::__type> struct __promote_3 { typedef __typeof__(_Tp2() + _Up2() + _Vp2()) __type; }; template<typename _Tp, typename _Up, typename _Vp, typename _Wp, typename _Tp2 = typename __promote<_Tp>::__type, typename _Up2 = typename __promote<_Up>::__type, typename _Vp2 = typename __promote<_Vp>::__type, typename _Wp2 = typename __promote<_Wp>::__type> struct __promote_4 { typedef __typeof__(_Tp2() + _Up2() + _Vp2() + _Wp2()) __type; }; } # 45 "/opt/Xilinx/Vivado/2017.4/lnx64/tools/gcc/lib/gcc/x86_64-unknown-linux-gnu/4.6.3/../../../../include/c++/4.6.3/cmath" 2 3 # 1 "/usr/include/math.h" 1 3 4 # 28 "/usr/include/math.h" 3 4 extern "C" { # 1 "/usr/include/x86_64-linux-gnu/bits/math-vector.h" 1 3 4 # 25 "/usr/include/x86_64-linux-gnu/bits/math-vector.h" 3 4 # 1 "/usr/include/x86_64-linux-gnu/bits/libm-simd-decl-stubs.h" 1 3 4 # 26 "/usr/include/x86_64-linux-gnu/bits/math-vector.h" 2 3 4 # 32 "/usr/include/math.h" 2 3 4 # 1 "/usr/include/x86_64-linux-gnu/bits/huge_val.h" 1 3 4 # 36 "/usr/include/math.h" 2 3 4 # 1 "/usr/include/x86_64-linux-gnu/bits/huge_valf.h" 1 3 4 # 38 "/usr/include/math.h" 2 3 4 # 1 "/usr/include/x86_64-linux-gnu/bits/huge_vall.h" 1 3 4 # 39 "/usr/include/math.h" 2 3 4 # 1 "/usr/include/x86_64-linux-gnu/bits/inf.h" 1 3 4 # 42 "/usr/include/math.h" 2 3 4 # 1 "/usr/include/x86_64-linux-gnu/bits/nan.h" 1 3 4 # 45 "/usr/include/math.h" 2 3 4 # 1 "/usr/include/x86_64-linux-gnu/bits/mathdef.h" 1 3 4 # 28 "/usr/include/x86_64-linux-gnu/bits/mathdef.h" 3 4 typedef float float_t; typedef double double_t; # 49 "/usr/include/math.h" 2 3 4 # 83 "/usr/include/math.h" 3 4 # 1 "/usr/include/x86_64-linux-gnu/bits/mathcalls.h" 1 3 4 # 54 "/usr/include/x86_64-linux-gnu/bits/mathcalls.h" 3 4 extern double acos (double __x) throw (); extern double __acos (double __x) throw (); extern double asin (double __x) throw (); extern double __asin (double __x) throw (); extern double atan (double __x) throw (); extern double __atan (double __x) throw (); extern double atan2 (double __y, double __x) throw (); extern double __atan2 (double __y, double __x) throw (); extern double cos (double __x) throw (); extern double __cos (double __x) throw (); extern double sin (double __x) throw (); extern double __sin (double __x) throw (); extern double tan (double __x) throw (); extern double __tan (double __x) throw (); extern double cosh (double __x) throw (); extern double __cosh (double __x) throw (); extern double sinh (double __x) throw (); extern double __sinh (double __x) throw (); extern double tanh (double __x) throw (); extern double __tanh (double __x) throw (); extern void sincos (double __x, double *__sinx, double *__cosx) throw (); extern void __sincos (double __x, double *__sinx, double *__cosx) throw (); extern double acosh (double __x) throw (); extern double __acosh (double __x) throw (); extern double asinh (double __x) throw (); extern double __asinh (double __x) throw (); extern double atanh (double __x) throw (); extern double __atanh (double __x) throw (); extern double exp (double __x) throw (); extern double __exp (double __x) throw (); extern double frexp (double __x, int *__exponent) throw (); extern double __frexp (double __x, int *__exponent) throw (); extern double ldexp (double __x, int __exponent) throw (); extern double __ldexp (double __x, int __exponent) throw (); extern double log (double __x) throw (); extern double __log (double __x) throw (); extern double log10 (double __x) throw (); extern double __log10 (double __x) throw (); extern double modf (double __x, double *__iptr) throw (); extern double __modf (double __x, double *__iptr) throw () __attribute__ ((__nonnull__ (2))); extern double exp10 (double __x) throw (); extern double __exp10 (double __x) throw (); extern double pow10 (double __x) throw (); extern double __pow10 (double __x) throw (); extern double expm1 (double __x) throw (); extern double __expm1 (double __x) throw (); extern double log1p (double __x) throw (); extern double __log1p (double __x) throw (); extern double logb (double __x) throw (); extern double __logb (double __x) throw (); extern double exp2 (double __x) throw (); extern double __exp2 (double __x) throw (); extern double log2 (double __x) throw (); extern double __log2 (double __x) throw (); # 153 "/usr/include/x86_64-linux-gnu/bits/mathcalls.h" 3 4 extern double pow (double __x, double __y) throw (); extern double __pow (double __x, double __y) throw (); extern double sqrt (double __x) throw (); extern double __sqrt (double __x) throw (); extern double hypot (double __x, double __y) throw (); extern double __hypot (double __x, double __y) throw (); extern double cbrt (double __x) throw (); extern double __cbrt (double __x) throw (); # 178 "/usr/include/x86_64-linux-gnu/bits/mathcalls.h" 3 4 extern double ceil (double __x) throw () __attribute__ ((__const__)); extern double __ceil (double __x) throw () __attribute__ ((__const__)); extern double fabs (double __x) throw () __attribute__ ((__const__)); extern double __fabs (double __x) throw () __attribute__ ((__const__)); extern double floor (double __x) throw () __attribute__ ((__const__)); extern double __floor (double __x) throw () __attribute__ ((__const__)); extern double fmod (double __x, double __y) throw (); extern double __fmod (double __x, double __y) throw (); extern int __isinf (double __value) throw () __attribute__ ((__const__)); extern int __finite (double __value) throw () __attribute__ ((__const__)); # 204 "/usr/include/x86_64-linux-gnu/bits/mathcalls.h" 3 4 extern int isinf (double __value) throw () __attribute__ ((__const__)); extern int finite (double __value) throw () __attribute__ ((__const__)); extern double drem (double __x, double __y) throw (); extern double __drem (double __x, double __y) throw (); extern double significand (double __x) throw (); extern double __significand (double __x) throw (); extern double copysign (double __x, double __y) throw () __attribute__ ((__const__)); extern double __copysign (double __x, double __y) throw () __attribute__ ((__const__)); extern double nan (const char *__tagb) throw () __attribute__ ((__const__)); extern double __nan (const char *__tagb) throw () __attribute__ ((__const__)); extern int __isnan (double __value) throw () __attribute__ ((__const__)); extern int isnan (double __value) throw () __attribute__ ((__const__)); extern double j0 (double) throw (); extern double __j0 (double) throw (); extern double j1 (double) throw (); extern double __j1 (double) throw (); extern double jn (int, double) throw (); extern double __jn (int, double) throw (); extern double y0 (double) throw (); extern double __y0 (double) throw (); extern double y1 (double) throw (); extern double __y1 (double) throw (); extern double yn (int, double) throw (); extern double __yn (int, double) throw (); extern double erf (double) throw (); extern double __erf (double) throw (); extern double erfc (double) throw (); extern double __erfc (double) throw (); extern double lgamma (double) throw (); extern double __lgamma (double) throw (); extern double tgamma (double) throw (); extern double __tgamma (double) throw (); extern double gamma (double) throw (); extern double __gamma (double) throw (); extern double lgamma_r (double, int *__signgamp) throw (); extern double __lgamma_r (double, int *__signgamp) throw (); extern double rint (double __x) throw (); extern double __rint (double __x) throw (); extern double nextafter (double __x, double __y) throw () __attribute__ ((__const__)); extern double __nextafter (double __x, double __y) throw () __attribute__ ((__const__)); extern double nexttoward (double __x, long double __y) throw () __attribute__ ((__const__)); extern double __nexttoward (double __x, long double __y) throw () __attribute__ ((__const__)); extern double remainder (double __x, double __y) throw (); extern double __remainder (double __x, double __y) throw (); extern double scalbn (double __x, int __n) throw (); extern double __scalbn (double __x, int __n) throw (); extern int ilogb (double __x) throw (); extern int __ilogb (double __x) throw (); extern double scalbln (double __x, long int __n) throw (); extern double __scalbln (double __x, long int __n) throw (); extern double nearbyint (double __x) throw (); extern double __nearbyint (double __x) throw (); extern double round (double __x) throw () __attribute__ ((__const__)); extern double __round (double __x) throw () __attribute__ ((__const__)); extern double trunc (double __x) throw () __attribute__ ((__const__)); extern double __trunc (double __x) throw () __attribute__ ((__const__)); extern double remquo (double __x, double __y, int *__quo) throw (); extern double __remquo (double __x, double __y, int *__quo) throw (); extern long int lrint (double __x) throw (); extern long int __lrint (double __x) throw (); __extension__ extern long long int llrint (double __x) throw (); extern long long int __llrint (double __x) throw (); extern long int lround (double __x) throw (); extern long int __lround (double __x) throw (); __extension__ extern long long int llround (double __x) throw (); extern long long int __llround (double __x) throw (); extern double fdim (double __x, double __y) throw (); extern double __fdim (double __x, double __y) throw (); extern double fmax (double __x, double __y) throw () __attribute__ ((__const__)); extern double __fmax (double __x, double __y) throw () __attribute__ ((__const__)); extern double fmin (double __x, double __y) throw () __attribute__ ((__const__)); extern double __fmin (double __x, double __y) throw () __attribute__ ((__const__)); extern int __fpclassify (double __value) throw () __attribute__ ((__const__)); extern int __signbit (double __value) throw () __attribute__ ((__const__)); extern double fma (double __x, double __y, double __z) throw (); extern double __fma (double __x, double __y, double __z) throw (); # 375 "/usr/include/x86_64-linux-gnu/bits/mathcalls.h" 3 4 extern int __issignaling (double __value) throw () __attribute__ ((__const__)); extern double scalb (double __x, double __n) throw (); extern double __scalb (double __x, double __n) throw (); # 84 "/usr/include/math.h" 2 3 4 # 104 "/usr/include/math.h" 3 4 # 1 "/usr/include/x86_64-linux-gnu/bits/mathcalls.h" 1 3 4 # 54 "/usr/include/x86_64-linux-gnu/bits/mathcalls.h" 3 4 extern float acosf (float __x) throw (); extern float __acosf (float __x) throw (); extern float asinf (float __x) throw (); extern float __asinf (float __x) throw (); extern float atanf (float __x) throw (); extern float __atanf (float __x) throw (); extern float atan2f (float __y, float __x) throw (); extern float __atan2f (float __y, float __x) throw (); extern float cosf (float __x) throw (); extern float __cosf (float __x) throw (); extern float sinf (float __x) throw (); extern float __sinf (float __x) throw (); extern float tanf (float __x) throw (); extern float __tanf (float __x) throw (); extern float coshf (float __x) throw (); extern float __coshf (float __x) throw (); extern float sinhf (float __x) throw (); extern float __sinhf (float __x) throw (); extern float tanhf (float __x) throw (); extern float __tanhf (float __x) throw (); extern void sincosf (float __x, float *__sinx, float *__cosx) throw (); extern void __sincosf (float __x, float *__sinx, float *__cosx) throw (); extern float acoshf (float __x) throw (); extern float __acoshf (float __x) throw (); extern float asinhf (float __x) throw (); extern float __asinhf (float __x) throw (); extern float atanhf (float __x) throw (); extern float __atanhf (float __x) throw (); extern float expf (float __x) throw (); extern float __expf (float __x) throw (); extern float frexpf (float __x, int *__exponent) throw (); extern float __frexpf (float __x, int *__exponent) throw (); extern float ldexpf (float __x, int __exponent) throw (); extern float __ldexpf (float __x, int __exponent) throw (); extern float logf (float __x) throw (); extern float __logf (float __x) throw (); extern float log10f (float __x) throw (); extern float __log10f (float __x) throw (); extern float modff (float __x, float *__iptr) throw (); extern float __modff (float __x, float *__iptr) throw () __attribute__ ((__nonnull__ (2))); extern float exp10f (float __x) throw (); extern float __exp10f (float __x) throw (); extern float pow10f (float __x) throw (); extern float __pow10f (float __x) throw (); extern float expm1f (float __x) throw (); extern float __expm1f (float __x) throw (); extern float log1pf (float __x) throw (); extern float __log1pf (float __x) throw (); extern float logbf (float __x) throw (); extern float __logbf (float __x) throw (); extern float exp2f (float __x) throw (); extern float __exp2f (float __x) throw (); extern float log2f (float __x) throw (); extern float __log2f (float __x) throw (); # 153 "/usr/include/x86_64-linux-gnu/bits/mathcalls.h" 3 4 extern float powf (float __x, float __y) throw (); extern float __powf (float __x, float __y) throw (); extern float sqrtf (float __x) throw (); extern float __sqrtf (float __x) throw (); extern float hypotf (float __x, float __y) throw (); extern float __hypotf (float __x, float __y) throw (); extern float cbrtf (float __x) throw (); extern float __cbrtf (float __x) throw (); # 178 "/usr/include/x86_64-linux-gnu/bits/mathcalls.h" 3 4 extern float ceilf (float __x) throw () __attribute__ ((__const__)); extern float __ceilf (float __x) throw () __attribute__ ((__const__)); extern float fabsf (float __x) throw () __attribute__ ((__const__)); extern float __fabsf (float __x) throw () __attribute__ ((__const__)); extern float floorf (float __x) throw () __attribute__ ((__const__)); extern float __floorf (float __x) throw () __attribute__ ((__const__)); extern float fmodf (float __x, float __y) throw (); extern float __fmodf (float __x, float __y) throw (); extern int __isinff (float __value) throw () __attribute__ ((__const__)); extern int __finitef (float __value) throw () __attribute__ ((__const__)); # 204 "/usr/include/x86_64-linux-gnu/bits/mathcalls.h" 3 4 extern int isinff (float __value) throw () __attribute__ ((__const__)); extern int finitef (float __value) throw () __attribute__ ((__const__)); extern float dremf (float __x, float __y) throw (); extern float __dremf (float __x, float __y) throw (); extern float significandf (float __x) throw (); extern float __significandf (float __x) throw (); extern float copysignf (float __x, float __y) throw () __attribute__ ((__const__)); extern float __copysignf (float __x, float __y) throw () __attribute__ ((__const__)); extern float nanf (const char *__tagb) throw () __attribute__ ((__const__)); extern float __nanf (const char *__tagb) throw () __attribute__ ((__const__)); extern int __isnanf (float __value) throw () __attribute__ ((__const__)); extern int isnanf (float __value) throw () __attribute__ ((__const__)); extern float j0f (float) throw (); extern float __j0f (float) throw (); extern float j1f (float) throw (); extern float __j1f (float) throw (); extern float jnf (int, float) throw (); extern float __jnf (int, float) throw (); extern float y0f (float) throw (); extern float __y0f (float) throw (); extern float y1f (float) throw (); extern float __y1f (float) throw (); extern float ynf (int, float) throw (); extern float __ynf (int, float) throw (); extern float erff (float) throw (); extern float __erff (float) throw (); extern float erfcf (float) throw (); extern float __erfcf (float) throw (); extern float lgammaf (float) throw (); extern float __lgammaf (float) throw (); extern float tgammaf (float) throw (); extern float __tgammaf (float) throw (); extern float gammaf (float) throw (); extern float __gammaf (float) throw (); extern float lgammaf_r (float, int *__signgamp) throw (); extern float __lgammaf_r (float, int *__signgamp) throw (); extern float rintf (float __x) throw (); extern float __rintf (float __x) throw (); extern float nextafterf (float __x, float __y) throw () __attribute__ ((__const__)); extern float __nextafterf (float __x, float __y) throw () __attribute__ ((__const__)); extern float nexttowardf (float __x, long double __y) throw () __attribute__ ((__const__)); extern float __nexttowardf (float __x, long double __y) throw () __attribute__ ((__const__)); extern float remainderf (float __x, float __y) throw (); extern float __remainderf (float __x, float __y) throw (); extern float scalbnf (float __x, int __n) throw (); extern float __scalbnf (float __x, int __n) throw (); extern int ilogbf (float __x) throw (); extern int __ilogbf (float __x) throw (); extern float scalblnf (float __x, long int __n) throw (); extern float __scalblnf (float __x, long int __n) throw (); extern float nearbyintf (float __x) throw (); extern float __nearbyintf (float __x) throw (); extern float roundf (float __x) throw () __attribute__ ((__const__)); extern float __roundf (float __x) throw () __attribute__ ((__const__)); extern float truncf (float __x) throw () __attribute__ ((__const__)); extern float __truncf (float __x) throw () __attribute__ ((__const__)); extern float remquof (float __x, float __y, int *__quo) throw (); extern float __remquof (float __x, float __y, int *__quo) throw (); extern long int lrintf (float __x) throw (); extern long int __lrintf (float __x) throw (); __extension__ extern long long int llrintf (float __x) throw (); extern long long int __llrintf (float __x) throw (); extern long int lroundf (float __x) throw (); extern long int __lroundf (float __x) throw (); __extension__ extern long long int llroundf (float __x) throw (); extern long long int __llroundf (float __x) throw (); extern float fdimf (float __x, float __y) throw (); extern float __fdimf (float __x, float __y) throw (); extern float fmaxf (float __x, float __y) throw () __attribute__ ((__const__)); extern float __fmaxf (float __x, float __y) throw () __attribute__ ((__const__)); extern float fminf (float __x, float __y) throw () __attribute__ ((__const__)); extern float __fminf (float __x, float __y) throw () __attribute__ ((__const__)); extern int __fpclassifyf (float __value) throw () __attribute__ ((__const__)); extern int __signbitf (float __value) throw () __attribute__ ((__const__)); extern float fmaf (float __x, float __y, float __z) throw (); extern float __fmaf (float __x, float __y, float __z) throw (); # 375 "/usr/include/x86_64-linux-gnu/bits/mathcalls.h" 3 4 extern int __issignalingf (float __value) throw () __attribute__ ((__const__)); extern float scalbf (float __x, float __n) throw (); extern float __scalbf (float __x, float __n) throw (); # 105 "/usr/include/math.h" 2 3 4 # 151 "/usr/include/math.h" 3 4 # 1 "/usr/include/x86_64-linux-gnu/bits/mathcalls.h" 1 3 4 # 54 "/usr/include/x86_64-linux-gnu/bits/mathcalls.h" 3 4 extern long double acosl (long double __x) throw (); extern long double __acosl (long double __x) throw (); extern long double asinl (long double __x) throw (); extern long double __asinl (long double __x) throw (); extern long double atanl (long double __x) throw (); extern long double __atanl (long double __x) throw (); extern long double atan2l (long double __y, long double __x) throw (); extern long double __atan2l (long double __y, long double __x) throw (); extern long double cosl (long double __x) throw (); extern long double __cosl (long double __x) throw (); extern long double sinl (long double __x) throw (); extern long double __sinl (long double __x) throw (); extern long double tanl (long double __x) throw (); extern long double __tanl (long double __x) throw (); extern long double coshl (long double __x) throw (); extern long double __coshl (long double __x) throw (); extern long double sinhl (long double __x) throw (); extern long double __sinhl (long double __x) throw (); extern long double tanhl (long double __x) throw (); extern long double __tanhl (long double __x) throw (); extern void sincosl (long double __x, long double *__sinx, long double *__cosx) throw (); extern void __sincosl (long double __x, long double *__sinx, long double *__cosx) throw (); extern long double acoshl (long double __x) throw (); extern long double __acoshl (long double __x) throw (); extern long double asinhl (long double __x) throw (); extern long double __asinhl (long double __x) throw (); extern long double atanhl (long double __x) throw (); extern long double __atanhl (long double __x) throw (); extern long double expl (long double __x) throw (); extern long double __expl (long double __x) throw (); extern long double frexpl (long double __x, int *__exponent) throw (); extern long double __frexpl (long double __x, int *__exponent) throw (); extern long double ldexpl (long double __x, int __exponent) throw (); extern long double __ldexpl (long double __x, int __exponent) throw (); extern long double logl (long double __x) throw (); extern long double __logl (long double __x) throw (); extern long double log10l (long double __x) throw (); extern long double __log10l (long double __x) throw (); extern long double modfl (long double __x, long double *__iptr) throw (); extern long double __modfl (long double __x, long double *__iptr) throw () __attribute__ ((__nonnull__ (2))); extern long double exp10l (long double __x) throw (); extern long double __exp10l (long double __x) throw (); extern long double pow10l (long double __x) throw (); extern long double __pow10l (long double __x) throw (); extern long double expm1l (long double __x) throw (); extern long double __expm1l (long double __x) throw (); extern long double log1pl (long double __x) throw (); extern long double __log1pl (long double __x) throw (); extern long double logbl (long double __x) throw (); extern long double __logbl (long double __x) throw (); extern long double exp2l (long double __x) throw (); extern long double __exp2l (long double __x) throw (); extern long double log2l (long double __x) throw (); extern long double __log2l (long double __x) throw (); # 153 "/usr/include/x86_64-linux-gnu/bits/mathcalls.h" 3 4 extern long double powl (long double __x, long double __y) throw (); extern long double __powl (long double __x, long double __y) throw (); extern long double sqrtl (long double __x) throw (); extern long double __sqrtl (long double __x) throw (); extern long double hypotl (long double __x, long double __y) throw (); extern long double __hypotl (long double __x, long double __y) throw (); extern long double cbrtl (long double __x) throw (); extern long double __cbrtl (long double __x) throw (); # 178 "/usr/include/x86_64-linux-gnu/bits/mathcalls.h" 3 4 extern long double ceill (long double __x) throw () __attribute__ ((__const__)); extern long double __ceill (long double __x) throw () __attribute__ ((__const__)); extern long double fabsl (long double __x) throw () __attribute__ ((__const__)); extern long double __fabsl (long double __x) throw () __attribute__ ((__const__)); extern long double floorl (long double __x) throw () __attribute__ ((__const__)); extern long double __floorl (long double __x) throw () __attribute__ ((__const__)); extern long double fmodl (long double __x, long double __y) throw (); extern long double __fmodl (long double __x, long double __y) throw (); extern int __isinfl (long double __value) throw () __attribute__ ((__const__)); extern int __finitel (long double __value) throw () __attribute__ ((__const__)); # 204 "/usr/include/x86_64-linux-gnu/bits/mathcalls.h" 3 4 extern int isinfl (long double __value) throw () __attribute__ ((__const__)); extern int finitel (long double __value) throw () __attribute__ ((__const__)); extern long double dreml (long double __x, long double __y) throw (); extern long double __dreml (long double __x, long double __y) throw (); extern long double significandl (long double __x) throw (); extern long double __significandl (long double __x) throw (); extern long double copysignl (long double __x, long double __y) throw () __attribute__ ((__const__)); extern long double __copysignl (long double __x, long double __y) throw () __attribute__ ((__const__)); extern long double nanl (const char *__tagb) throw () __attribute__ ((__const__)); extern long double __nanl (const char *__tagb) throw () __attribute__ ((__const__)); extern int __isnanl (long double __value) throw () __attribute__ ((__const__)); extern int isnanl (long double __value) throw () __attribute__ ((__const__)); extern long double j0l (long double) throw (); extern long double __j0l (long double) throw (); extern long double j1l (long double) throw (); extern long double __j1l (long double) throw (); extern long double jnl (int, long double) throw (); extern long double __jnl (int, long double) throw (); extern long double y0l (long double) throw (); extern long double __y0l (long double) throw (); extern long double y1l (long double) throw (); extern long double __y1l (long double) throw (); extern long double ynl (int, long double) throw (); extern long double __ynl (int, long double) throw (); extern long double erfl (long double) throw (); extern long double __erfl (long double) throw (); extern long double erfcl (long double) throw (); extern long double __erfcl (long double) throw (); extern long double lgammal (long double) throw (); extern long double __lgammal (long double) throw (); extern long double tgammal (long double) throw (); extern long double __tgammal (long double) throw (); extern long double gammal (long double) throw (); extern long double __gammal (long double) throw (); extern long double lgammal_r (long double, int *__signgamp) throw (); extern long double __lgammal_r (long double, int *__signgamp) throw (); extern long double rintl (long double __x) throw (); extern long double __rintl (long double __x) throw (); extern long double nextafterl (long double __x, long double __y) throw () __attribute__ ((__const__)); extern long double __nextafterl (long double __x, long double __y) throw () __attribute__ ((__const__)); extern long double nexttowardl (long double __x, long double __y) throw () __attribute__ ((__const__)); extern long double __nexttowardl (long double __x, long double __y) throw () __attribute__ ((__const__)); extern long double remainderl (long double __x, long double __y) throw (); extern long double __remainderl (long double __x, long double __y) throw (); extern long double scalbnl (long double __x, int __n) throw (); extern long double __scalbnl (long double __x, int __n) throw (); extern int ilogbl (long double __x) throw (); extern int __ilogbl (long double __x) throw (); extern long double scalblnl (long double __x, long int __n) throw (); extern long double __scalblnl (long double __x, long int __n) throw (); extern long double nearbyintl (long double __x) throw (); extern long double __nearbyintl (long double __x) throw (); extern long double roundl (long double __x) throw () __attribute__ ((__const__)); extern long double __roundl (long double __x) throw () __attribute__ ((__const__)); extern long double truncl (long double __x) throw () __attribute__ ((__const__)); extern long double __truncl (long double __x) throw () __attribute__ ((__const__)); extern long double remquol (long double __x, long double __y, int *__quo) throw (); extern long double __remquol (long double __x, long double __y, int *__quo) throw (); extern long int lrintl (long double __x) throw (); extern long int __lrintl (long double __x) throw (); __extension__ extern long long int llrintl (long double __x) throw (); extern long long int __llrintl (long double __x) throw (); extern long int lroundl (long double __x) throw (); extern long int __lroundl (long double __x) throw (); __extension__ extern long long int llroundl (long double __x) throw (); extern long long int __llroundl (long double __x) throw (); extern long double fdiml (long double __x, long double __y) throw (); extern long double __fdiml (long double __x, long double __y) throw (); extern long double fmaxl (long double __x, long double __y) throw () __attribute__ ((__const__)); extern long double __fmaxl (long double __x, long double __y) throw () __attribute__ ((__const__)); extern long double fminl (long double __x, long double __y) throw () __attribute__ ((__const__)); extern long double __fminl (long double __x, long double __y) throw () __attribute__ ((__const__)); extern int __fpclassifyl (long double __value) throw () __attribute__ ((__const__)); extern int __signbitl (long double __value) throw () __attribute__ ((__const__)); extern long double fmal (long double __x, long double __y, long double __z) throw (); extern long double __fmal (long double __x, long double __y, long double __z) throw (); # 375 "/usr/include/x86_64-linux-gnu/bits/mathcalls.h" 3 4 extern int __issignalingl (long double __value) throw () __attribute__ ((__const__)); extern long double scalbl (long double __x, long double __n) throw (); extern long double __scalbl (long double __x, long double __n) throw (); # 152 "/usr/include/math.h" 2 3 4 # 168 "/usr/include/math.h" 3 4 extern int signgam; # 209 "/usr/include/math.h" 3 4 enum { FP_NAN = 0, FP_INFINITE = 1, FP_ZERO = 2, FP_SUBNORMAL = 3, FP_NORMAL = 4 }; # 347 "/usr/include/math.h" 3 4 typedef enum { _IEEE_ = -1, _SVID_, _XOPEN_, _POSIX_, _ISOC_ } _LIB_VERSION_TYPE; extern _LIB_VERSION_TYPE _LIB_VERSION; # 370 "/usr/include/math.h" 3 4 struct __exception { int type; char *name; double arg1; double arg2; double retval; }; extern int matherr (struct __exception *__exc) throw (); # 534 "/usr/include/math.h" 3 4 } # 46 "/opt/Xilinx/Vivado/2017.4/lnx64/tools/gcc/lib/gcc/x86_64-unknown-linux-gnu/4.6.3/../../../../include/c++/4.6.3/cmath" 2 3 # 76 "/opt/Xilinx/Vivado/2017.4/lnx64/tools/gcc/lib/gcc/x86_64-unknown-linux-gnu/4.6.3/../../../../include/c++/4.6.3/cmath" 3 namespace std __attribute__ ((__visibility__ ("default"))) { inline double abs(double __x) { return __builtin_fabs(__x); } inline float abs(float __x) { return __builtin_fabsf(__x); } inline long double abs(long double __x) { return __builtin_fabsl(__x); } template<typename _Tp> inline typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value, double>::__type abs(_Tp __x) { return __builtin_fabs(__x); } using ::acos; inline float acos(float __x) { return __builtin_acosf(__x); } inline long double acos(long double __x) { return __builtin_acosl(__x); } template<typename _Tp> inline typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value, double>::__type acos(_Tp __x) { return __builtin_acos(__x); } using ::asin; inline float asin(float __x) { return __builtin_asinf(__x); } inline long double asin(long double __x) { return __builtin_asinl(__x); } template<typename _Tp> inline typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value, double>::__type asin(_Tp __x) { return __builtin_asin(__x); } using ::atan; inline float atan(float __x) { return __builtin_atanf(__x); } inline long double atan(long double __x) { return __builtin_atanl(__x); } template<typename _Tp> inline typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value, double>::__type atan(_Tp __x) { return __builtin_atan(__x); } using ::atan2; inline float atan2(float __y, float __x) { return __builtin_atan2f(__y, __x); } inline long double atan2(long double __y, long double __x) { return __builtin_atan2l(__y, __x); } template<typename _Tp, typename _Up> inline typename __gnu_cxx::__promote_2<_Tp, _Up>::__type atan2(_Tp __y, _Up __x) { typedef typename __gnu_cxx::__promote_2<_Tp, _Up>::__type __type; return atan2(__type(__y), __type(__x)); } using ::ceil; inline float ceil(float __x) { return __builtin_ceilf(__x); } inline long double ceil(long double __x) { return __builtin_ceill(__x); } template<typename _Tp> inline typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value, double>::__type ceil(_Tp __x) { return __builtin_ceil(__x); } using ::cos; inline float cos(float __x) { return __builtin_cosf(__x); } inline long double cos(long double __x) { return __builtin_cosl(__x); } template<typename _Tp> inline typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value, double>::__type cos(_Tp __x) { return __builtin_cos(__x); } using ::cosh; inline float cosh(float __x) { return __builtin_coshf(__x); } inline long double cosh(long double __x) { return __builtin_coshl(__x); } template<typename _Tp> inline typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value, double>::__type cosh(_Tp __x) { return __builtin_cosh(__x); } using ::exp; inline float exp(float __x) { return __builtin_expf(__x); } inline long double exp(long double __x) { return __builtin_expl(__x); } template<typename _Tp> inline typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value, double>::__type exp(_Tp __x) { return __builtin_exp(__x); } using ::fabs; inline float fabs(float __x) { return __builtin_fabsf(__x); } inline long double fabs(long double __x) { return __builtin_fabsl(__x); } template<typename _Tp> inline typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value, double>::__type fabs(_Tp __x) { return __builtin_fabs(__x); } using ::floor; inline float floor(float __x) { return __builtin_floorf(__x); } inline long double floor(long double __x) { return __builtin_floorl(__x); } template<typename _Tp> inline typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value, double>::__type floor(_Tp __x) { return __builtin_floor(__x); } using ::fmod; inline float fmod(float __x, float __y) { return __builtin_fmodf(__x, __y); } inline long double fmod(long double __x, long double __y) { return __builtin_fmodl(__x, __y); } using ::frexp; inline float frexp(float __x, int* __exp) { return __builtin_frexpf(__x, __exp); } inline long double frexp(long double __x, int* __exp) { return __builtin_frexpl(__x, __exp); } template<typename _Tp> inline typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value, double>::__type frexp(_Tp __x, int* __exp) { return __builtin_frexp(__x, __exp); } using ::ldexp; inline float ldexp(float __x, int __exp) { return __builtin_ldexpf(__x, __exp); } inline long double ldexp(long double __x, int __exp) { return __builtin_ldexpl(__x, __exp); } template<typename _Tp> inline typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value, double>::__type ldexp(_Tp __x, int __exp) { return __builtin_ldexp(__x, __exp); } using ::log; inline float log(float __x) { return __builtin_logf(__x); } inline long double log(long double __x) { return __builtin_logl(__x); } template<typename _Tp> inline typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value, double>::__type log(_Tp __x) { return __builtin_log(__x); } using ::log10; inline float log10(float __x) { return __builtin_log10f(__x); } inline long double log10(long double __x) { return __builtin_log10l(__x); } template<typename _Tp> inline typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value, double>::__type log10(_Tp __x) { return __builtin_log10(__x); } using ::modf; inline float modf(float __x, float* __iptr) { return __builtin_modff(__x, __iptr); } inline long double modf(long double __x, long double* __iptr) { return __builtin_modfl(__x, __iptr); } using ::pow; inline float pow(float __x, float __y) { return __builtin_powf(__x, __y); } inline long double pow(long double __x, long double __y) { return __builtin_powl(__x, __y); } inline double pow(double __x, int __i) { return __builtin_powi(__x, __i); } inline float pow(float __x, int __n) { return __builtin_powif(__x, __n); } inline long double pow(long double __x, int __n) { return __builtin_powil(__x, __n); } template<typename _Tp, typename _Up> inline typename __gnu_cxx::__promote_2<_Tp, _Up>::__type pow(_Tp __x, _Up __y) { typedef typename __gnu_cxx::__promote_2<_Tp, _Up>::__type __type; return pow(__type(__x), __type(__y)); } using ::sin; inline float sin(float __x) { return __builtin_sinf(__x); } inline long double sin(long double __x) { return __builtin_sinl(__x); } template<typename _Tp> inline typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value, double>::__type sin(_Tp __x) { return __builtin_sin(__x); } using ::sinh; inline float sinh(float __x) { return __builtin_sinhf(__x); } inline long double sinh(long double __x) { return __builtin_sinhl(__x); } template<typename _Tp> inline typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value, double>::__type sinh(_Tp __x) { return __builtin_sinh(__x); } using ::sqrt; inline float sqrt(float __x) { return __builtin_sqrtf(__x); } inline long double sqrt(long double __x) { return __builtin_sqrtl(__x); } template<typename _Tp> inline typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value, double>::__type sqrt(_Tp __x) { return __builtin_sqrt(__x); } using ::tan; inline float tan(float __x) { return __builtin_tanf(__x); } inline long double tan(long double __x) { return __builtin_tanl(__x); } template<typename _Tp> inline typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value, double>::__type tan(_Tp __x) { return __builtin_tan(__x); } using ::tanh; inline float tanh(float __x) { return __builtin_tanhf(__x); } inline long double tanh(long double __x) { return __builtin_tanhl(__x); } template<typename _Tp> inline typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value, double>::__type tanh(_Tp __x) { return __builtin_tanh(__x); } } # 480 "/opt/Xilinx/Vivado/2017.4/lnx64/tools/gcc/lib/gcc/x86_64-unknown-linux-gnu/4.6.3/../../../../include/c++/4.6.3/cmath" 3 namespace std __attribute__ ((__visibility__ ("default"))) { # 730 "/opt/Xilinx/Vivado/2017.4/lnx64/tools/gcc/lib/gcc/x86_64-unknown-linux-gnu/4.6.3/../../../../include/c++/4.6.3/cmath" 3 template<typename _Tp> inline typename __gnu_cxx::__enable_if<__is_arithmetic<_Tp>::__value, int>::__type fpclassify(_Tp __f) { typedef typename __gnu_cxx::__promote<_Tp>::__type __type; return __builtin_fpclassify(0, 1, 4, 3, 2, __type(__f)); } template<typename _Tp> inline typename __gnu_cxx::__enable_if<__is_arithmetic<_Tp>::__value, int>::__type isfinite(_Tp __f) { typedef typename __gnu_cxx::__promote<_Tp>::__type __type; return __builtin_isfinite(__type(__f)); } template<typename _Tp> inline typename __gnu_cxx::__enable_if<__is_arithmetic<_Tp>::__value, int>::__type isinf(_Tp __f) { typedef typename __gnu_cxx::__promote<_Tp>::__type __type; return __builtin_isinf(__type(__f)); } template<typename _Tp> inline typename __gnu_cxx::__enable_if<__is_arithmetic<_Tp>::__value, int>::__type isnan(_Tp __f) { typedef typename __gnu_cxx::__promote<_Tp>::__type __type; return __builtin_isnan(__type(__f)); } template<typename _Tp> inline typename __gnu_cxx::__enable_if<__is_arithmetic<_Tp>::__value, int>::__type isnormal(_Tp __f) { typedef typename __gnu_cxx::__promote<_Tp>::__type __type; return __builtin_isnormal(__type(__f)); } template<typename _Tp> inline typename __gnu_cxx::__enable_if<__is_arithmetic<_Tp>::__value, int>::__type signbit(_Tp __f) { typedef typename __gnu_cxx::__promote<_Tp>::__type __type; return __builtin_signbit(__type(__f)); } template<typename _Tp> inline typename __gnu_cxx::__enable_if<__is_arithmetic<_Tp>::__value, int>::__type isgreater(_Tp __f1, _Tp __f2) { typedef typename __gnu_cxx::__promote<_Tp>::__type __type; return __builtin_isgreater(__type(__f1), __type(__f2)); } template<typename _Tp> inline typename __gnu_cxx::__enable_if<__is_arithmetic<_Tp>::__value, int>::__type isgreaterequal(_Tp __f1, _Tp __f2) { typedef typename __gnu_cxx::__promote<_Tp>::__type __type; return __builtin_isgreaterequal(__type(__f1), __type(__f2)); } template<typename _Tp> inline typename __gnu_cxx::__enable_if<__is_arithmetic<_Tp>::__value, int>::__type isless(_Tp __f1, _Tp __f2) { typedef typename __gnu_cxx::__promote<_Tp>::__type __type; return __builtin_isless(__type(__f1), __type(__f2)); } template<typename _Tp> inline typename __gnu_cxx::__enable_if<__is_arithmetic<_Tp>::__value, int>::__type islessequal(_Tp __f1, _Tp __f2) { typedef typename __gnu_cxx::__promote<_Tp>::__type __type; return __builtin_islessequal(__type(__f1), __type(__f2)); } template<typename _Tp> inline typename __gnu_cxx::__enable_if<__is_arithmetic<_Tp>::__value, int>::__type islessgreater(_Tp __f1, _Tp __f2) { typedef typename __gnu_cxx::__promote<_Tp>::__type __type; return __builtin_islessgreater(__type(__f1), __type(__f2)); } template<typename _Tp> inline typename __gnu_cxx::__enable_if<__is_arithmetic<_Tp>::__value, int>::__type isunordered(_Tp __f1, _Tp __f2) { typedef typename __gnu_cxx::__promote<_Tp>::__type __type; return __builtin_isunordered(__type(__f1), __type(__f2)); } } # 4 "mandelbrot-hls/mandelbrot.h" 2 using namespace std; const int imgWidth = 1024; const int imgHeight = 512; const int max_iteration = 512; const double minR = -2.5; const double maxR = 1.5; const double minI = -1.0; const double maxI = 1.0; void mandlebrot_main(int res[imgWidth][imgHeight]); # 2 "mandelbrot-hls/mandelbrot.cpp" 2 double mapToReal(int x, int imgWidth, double minR, double maxR) { double xrange = maxR - minR; return (x * (xrange / imgWidth) + minR); } double mapToImag(int y, int imgHeight, double minI, double maxI) { double yrange = maxI - minI; return (y * (yrange / imgHeight) + minI); } int findmandelbrot(double cr, double ci, int max_iteration) { int i = 0; double zr = 0.0, zi = 0.0; while (i < max_iteration && (zr * zr + zi * zi) < 4.0) { double temp = (zr * zr) - (zi * zi) + cr; zi = (2.0 * zr * zi) + ci; zr = temp; i++; }; return i; } void mandlebrot_main(int res[imgWidth][imgHeight]) { for (int y = 0; y < imgHeight; y++) { for (int x = 0; x < imgWidth; x++) { double cr = mapToReal(x, imgWidth, minR, maxR); double ci = mapToImag(y, imgHeight, minI, maxI); int n = findmandelbrot(cr, ci, max_iteration); res[x][y] = n % 256; } } }
[ "veranki@buffalo.edu" ]
veranki@buffalo.edu
8847d16b7798ba0e8531ebc0c1ee9b429eca909d
1fc1c628992be7cc95bc49b428594caf57e0b049
/cpp files/Linked List/Linked List (ready) struct.cpp
1b1c1c6c3f71c56e2e6034623a8e8588285d5010
[]
no_license
av1shek/DSA-NITW
8150b5646956177fa965a18b2c474db863687705
fe8219c145fccfaedf0a59867c7d4cc7fb70bdf1
refs/heads/master
2023-05-13T21:43:16.393840
2021-06-03T09:02:17
2021-06-03T09:02:17
373,443,487
0
0
null
null
null
null
UTF-8
C++
false
false
1,244
cpp
#include <iostream> using namespace std; typedef struct node *lptr; void insert(lptr &, int); /// insert a element in last void takeInput(lptr &); /// takes input while not -1 void print(lptr); /// prints the list int getSize(lptr); /// returns the size of list struct ele { int integer; char ch; }; struct node { struct ele data; struct node *next; node() { next=NULL; } }; void insert(lptr &P, struct ele x) { lptr temp = new node; temp->data = x; if(P==NULL) P = temp; else { lptr T = P; while(T->next != NULL) T = T->next; T->next = temp; } return; } void takeInput(lptr &L) { while(true) { struct ele temp; cin>>temp.integer; if(temp.integer == -1) break; insert(L, temp); } return; } void print(lptr L) { while(L!=NULL) { cout<<L->data.integer<<" "; L = L->next; } return; } int getSize(lptr L) { int count=0; while(L!=NULL) { count++; L = L->next; } return count; } int main() { lptr L = NULL; takeInput(L); print(L); return 0; }
[ "navodayanabhishek@gmail.com" ]
navodayanabhishek@gmail.com
65f70b4fa86669d97f7ae611e79ab5eec6a740c3
d40b0229971f4d5bc73c28af32471554a2e6e559
/Lab8/Lab8A/PhoneNumber.h
0ca19871d41fe31a2d4f2bc027d17a0ce4ab487c
[]
no_license
kevinwongwc95/Compsci200
1ac7ba139f2633c688b08b6412f0482b0fe7ff7c
f1ba00cef5b3911bf1d26b9643e1b65c73acc314
refs/heads/master
2020-05-30T05:01:52.897177
2015-10-08T01:42:12
2015-10-08T01:42:12
42,163,703
0
0
null
null
null
null
UTF-8
C++
false
false
492
h
// Lab 8A Write And Test A Queue Template // Programmer: Kevin Wong // Editor(s) used: Codeblocks // Compiler(s) used: GNU GCC Compiler #ifndef PHONENUMBER_H #define PHONENUMBER_H #include <iostream> #include <string> using std::string; using std::ostream; using std::istream; class PhoneNumber { friend ostream &operator<<(ostream &, const PhoneNumber &); friend istream &operator>>(istream &, PhoneNumber &); private: string areaCode; string exchange; string line; }; #endif
[ "Kevin@Kevins-MacBook-Pro-6.local" ]
Kevin@Kevins-MacBook-Pro-6.local
af43016127c4ee0ae5b42691424cc9060d0d61f3
5f15bd5f1536a9174ab0b12016d93832df7cbe64
/COJ/Cpp/P1328_CAVerage.cpp
daa9b7999c7c78b72b2e680f7c6d7c4e9d67cca9
[]
no_license
JuanM97/ProgrammingContests
ffeb651d70c24ff025766ec38da83e9a41b4b7b8
24174fb0ad8e5f9312bdff3ac6f4053fbda10fbf
refs/heads/master
2020-06-03T07:07:15.132198
2016-01-05T03:48:46
2016-01-05T03:48:46
40,952,640
0
1
null
null
null
null
UTF-8
C++
false
false
741
cpp
/* * File: P1328_CAVerage.cpp * Author: JuanM * * Created on May 3, 2013, 12:23 AM */ #include <iostream> #include <cstdio> #include <algorithm> #include <math.h> using namespace std; double avg[55]; int main() { int cases,num,cont; double a,pts; scanf("%d",&cases); while(cases--){ scanf("%d",&num); pts=0; for(int i=0;i<num;i++){ scanf("%lf",&avg[i]); pts+=avg[i]; } for(int i=0;i<num;i++){ scanf("%lf",&a); pts+=a; avg[i]+=a;avg[i]/=2; } pts/=(2*num); cont=0; for(int i=0;i<num;i++){ if(avg[i]<pts)cont++; } printf("%d\n",cont); } return 0; }
[ "jhonymss@hotmail.com" ]
jhonymss@hotmail.com
8fe98ca8d307f990f6935d2beb15fb81f7b81bda
a088e23598aefec1d1c729808ea2b6b36f3eb226
/013_section_oop_classes_and_objects/020_move_constructors.cpp
c07e8090491a86929490fcc54d030a930196436f
[]
no_license
mau5atron/CppTime
98947e82b714a932fdc776e0ed8bab2e48a69e46
63bb52ec6fa572ad888269f3ac84c16d7feadcb6
refs/heads/master
2023-02-17T18:28:16.433811
2021-01-16T03:06:28
2021-01-16T03:06:28
185,449,133
0
0
null
null
null
null
UTF-8
C++
false
false
4,336
cpp
#include <iostream> #include <vector> using std::cout; using std::endl; class Move { private: int *data; public: void set_data_val(int d){ *data = d; }; int get_data_val(){ return *data; }; Move(int d); // Constructor Move(const Move &source); // Copy constructor Move(Move &&source); // Move constructor ~Move(); // Destructor }; // Constructor, allocates storage and copy Move::Move(const Move &source){ data = new int; *data = *source.data; } // "Steal" the data abd then null out the source pointer Move::Move(Move &&source) : data{source.data}{ source.data = nullptr; } int main(void) { // Example, move class // Inefficient copying /* Vector<Move> vec; vec.push_back(Move{10}); vec.push_back(Move{20}); // Copy constructors will be called to copy the temps // What it looks like in terminal... Constructor for: 10 Constructor for: 10 Copy constructor - deep copy for: 10 Destructor freeing data for: 10 Constructor for: 20 Constructor for: 20 Copy constructor - deep copy for: 20 Constructor for: 10 Copy constructor - deep copy for: 10 Destructor freeing data for: 10 Destructor freeing data for: 20 So what does the move constructor do? - Intead of making a deep copy of the move constructor - 'moves' the resource - Simply copies the address of the resource from source to the current object - And, nulls out the pointer to the source pointer - Very efficient Syntax - r-value reference Type::Type(Type &&source); Player::Player(Player &&source); Move::Move(Move &&source); // "Steal" the data abd then null out the source pointer Move::Move(Move &&source) : data{source.data}{ source.data = nullptr; } // After adding the move constructor..... Efficient Output: Constructor for: 10 Move constructor - moving resource: 10 Destructor freeing data for nullptr Constructor for: 20 Move constructor - moving resource: 20 Move constructor - moving resource: 10 Destructor freeing data for nullptr Destructor freeing data for nullptr Destructor freeing data for: 10 Destructor freeing data for: 20 */ return 0; } /* Move Constructor: introduced in C++11 - Sometimes when we execute code the compiler creates unnamed temporary values int total {0}; total = 100 + 200; - 100 + 200 is evaluated and 300 stored in an unnamed temp value - the 300 is then stored in the variable total - then the temp value is discarded - the same happens with object as well When is it useful? - Sometimes copy constructors are called many times automatically due to the copy semantics of c++. - Copy constructors doing deep copying can have a significant performance bottleneck - C++11 introduced move semantics and the move constructor - Move constructor moves an object rather than copy it - Optional but recommended whne you have a raw pointer - Copy elision - C++ may optimize copying away completely (RVO-Return Value Optimization) r-value references: - Used in moving semantics and perfect forwarding - Move semantics is all about r-value references - used by move constructor and move assignment operator to efficiently move an object rather than copy it - r-value reference operator (&&) r-value references: int x {100}; // l-value reference int &l_ref = x; l_ref = 10; // change x to 10 int &&r_ref = 200; // r-value ref r_ref = 300; // change r_ref to 300 int &&x_ref = x; // Compiler error l-value reference parameters: int x {100}; // x is an l-value void func(int &num); // A func(x); // calls A - x is an l-value func(200); // Error - 200 is an r-value r-value reference parameters: int x {100}; void func(int &&num); // B func(200); // calls B - 200 is an r-value func(x); // Error - x is an l-value error: cannot bind rvalue reference of type 'int&&' to lvalue of type 'int' l-value and r-value reference parameters: int x {100}; // x is an l-value void func(int &num); // A void func(int &&num); // B func(x); // calls A - x is an l-value func(200); // calls B - 200 is an r-value Examples: Check main above^ */
[ "gabrielbetancourt96@outlook.com" ]
gabrielbetancourt96@outlook.com
6d73137fd7586e329244b1b8d46e8731091fe30f
777a75e6ed0934c193aece9de4421f8d8db01aac
/src/Providers/UNIXProviders/ElementConfiguration/UNIX_ElementConfigurationProvider.cpp
0fd8aa23449071b2c46b7ed4df2d9a8c0c844819
[ "MIT" ]
permissive
brunolauze/openpegasus-providers-old
20fc13958016e35dc4d87f93d1999db0eae9010a
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
refs/heads/master
2021-01-01T20:05:44.559362
2014-04-30T17:50:06
2014-04-30T17:50:06
19,132,738
1
0
null
null
null
null
UTF-8
C++
false
false
3,190
cpp
//%LICENSE//////////////////////////////////////////////////////////////// // // Licensed to The Open Group (TOG) under one or more contributor license // agreements. Refer to the OpenPegasusNOTICE.txt file distributed with // this work for additional information regarding copyright ownership. // Each contributor licenses this file to you under the OpenPegasus Open // Source License; you may not use this file except in compliance with the // License. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // ////////////////////////////////////////////////////////////////////////// // //%///////////////////////////////////////////////////////////////////////// #include "UNIX_ElementConfigurationProvider.h" UNIX_ElementConfigurationProvider::UNIX_ElementConfigurationProvider() { } UNIX_ElementConfigurationProvider::~UNIX_ElementConfigurationProvider() { } CIMInstance UNIX_ElementConfigurationProvider::constructInstance( const CIMName &className, const CIMNamespaceName &nameSpace, const UNIX_ElementConfiguration &_p) { CIMProperty p; CIMInstance inst(className); // Set path inst.setPath(CIMObjectPath(String(""), // hostname nameSpace, CIMName("UNIX_ElementConfiguration"), constructKeyBindings(_p))); //CIM_ElementConfiguration Properties if (_p.getElement(p)) inst.addProperty(p); if (_p.getConfiguration(p)) inst.addProperty(p); return inst; } Array<CIMKeyBinding> UNIX_ElementConfigurationProvider::constructKeyBindings(const UNIX_ElementConfiguration& _p) { Array<CIMKeyBinding> keys; keys.append(CIMKeyBinding( PROPERTY_ELEMENT, CIMValue(_p.getElement()).toString(), CIMKeyBinding::REFERENCE)); keys.append(CIMKeyBinding( PROPERTY_CONFIGURATION, CIMValue(_p.getConfiguration()).toString(), CIMKeyBinding::REFERENCE)); return keys; } #define UNIX_PROVIDER UNIX_ElementConfigurationProvider #define UNIX_PROVIDER_NAME "UNIX_ElementConfigurationProvider" #define CLASS_IMPLEMENTATION UNIX_ElementConfiguration #define CLASS_IMPLEMENTATION_NAME "UNIX_ElementConfiguration" #define BASE_CLASS_NAME "CIM_ElementConfiguration" #define NUMKEYS_CLASS_IMPLEMENTATION 2 #include "UNIXProviderBase.hpp"
[ "brunolauze@msn.com" ]
brunolauze@msn.com
1dc8737f0e98527e803ddcc69fe58603e2f32501
997b8a6c16a27788a802b4c33f3172df98851bbc
/virtualPark/Alarm.cpp
62749e5d4c5ad8082670d528f87130dfd167d12e
[]
no_license
shimachao/virtualPark
78eeab73a213d681386501a976e2bea6ac9cc573
f78d1caebc27b646de82d7d84a91f66032577bde
refs/heads/master
2021-01-10T03:49:10.694127
2016-03-26T08:56:26
2016-03-26T08:56:26
54,770,824
0
0
null
null
null
null
GB18030
C++
false
false
908
cpp
#include "stdafx.h" #include "Alarm.h" Alarm::Alarm():m_state(OFF) , m_duration(0) { } Alarm::~Alarm() { } // 打开警报器 void Alarm::open() { m_state = ON; m_duration = 3; // 警报持续3秒 } // 查询状态 AlarmState Alarm::getState() { return m_state; } // 更新状态 void Alarm::update() { if (m_state == ON) { if (m_duration == 0) { m_state = OFF; } else { m_duration--; } } } // 绘制 void Alarm::draw(Graphics* pGraphics) { // 绘制边框 Pen pen(Color(0, 0, 0)); pGraphics->DrawRectangle(&pen, 0, 0, 60, 60); if (m_state == OFF) { SolidBrush brush(Color(200, 200, 200)); pGraphics->FillEllipse(&brush, 1, 1, 58, 58); } else { SolidBrush brush(Color(255, 0, 0)); pGraphics->FillEllipse(&brush, 1, 1, 58, 58); } }
[ "531236305@qq.com" ]
531236305@qq.com
2dcadb599f3abc68ccdb263b69eb7946290324ca
5b05583d04d2167d06d3eb1c37b7bd8a24347035
/TEAMPIWORKINGCODE/TeamPi_6968_InfiniteRecharge/src/main/include/RobotIO.h
7401a4c6277e3c0a7e9e9c8157439ca61ab291bd
[]
no_license
TeamPi6968/Buildingseason2020
6d55ebe1682ac1d02536bab613ac798e0d7d3b01
718e3c44fdea8719432b8f43e670f0390a65e044
refs/heads/master
2020-12-23T16:59:54.641075
2020-10-05T18:09:22
2020-10-05T18:09:22
237,210,301
0
0
null
null
null
null
UTF-8
C++
false
false
5,078
h
#pragma once #include "frc/I2C.h" //In this class, all defines and constants can be found. class RobotIO { public: //SparkMax Settings //MotorTypes: #define BRUSHLESS true #define BRUSHED false //Yes & No boolean (for inverted, encoder and PID Controller) #define YES true #define NO false //Motorcontroller Config: //Drivetrain Motorcontrollers: int canDrivetrainLF = 1; //Left Front CANID bool drivetrainLFMotorType = BRUSHLESS; //MotorType bool drivetrainLFInverted = YES; //Inverted? bool drivetrainLFEncoder = NO; //Encoder? bool drivetrainLFPIDController = NO; //PID Controller? int canDrivetrainLB = 2; //Left Back CANID bool drivetrainLBMotorType = BRUSHLESS; //MotorType bool drivetrainLBInverted = YES; //Inverted? bool drivetrainLBEncoder = NO; //Encoder? bool drivetrainLBPIDController = NO; //PID Controller? int canDrivetrainRB = 8; //Right Back CANID bool drivetrainRBMotorType = BRUSHLESS; //MotorType bool drivetrainRBInverted = YES; //Inverted? bool drivetrainRBEncoder = NO; //Encoder? bool drivetrainRBPIDController = NO; //PID Controller? int canDrivetrainRF = 9; //Right Front CANID bool drivetrainRFMotorType = BRUSHLESS; //MotorType bool drivetrainRFInverted = YES; //Inverted? bool drivetrainRFEncoder = NO; //Encoder? bool drivetrainRFPIDController = NO; //PID Controller? //Intake Motorcontroller: int canIntakeCylinder = 10; //Intake Cylinder CANID bool intakeCylinderInverted = NO; //Inverted? //Storage Motorcontrollers: int canStorageRevolver = 3; //Storage Revolver CANID bool storageRevolverMotorType = BRUSHLESS; //MotorType bool storageRevolverInverted = NO; //Inverted? bool storageRevolverEncoder = YES; //Encoder? bool storageRevolverPIDController = YES; //PID Controller? int canStorageLoader = 5; //Storage Loader CANID bool storageLoaderMotorType = BRUSHLESS; //MotorType bool storageLoaderInverted = NO; //Inverted? bool storageLoaderEncoder = NO; //Encoder? bool storageLoaderPIDController = NO; //PID Controller? //Outtake Motorcontrollers: int canOuttakeUW = 6; //Motor Upper Wheels CANID bool outtakeUWMotorType = BRUSHED; //MotorType bool outtakeUWInverted = NO; //Inverted? bool outtakeUWEncoder = NO; //Encoder? bool outtakeUWPIDController = NO; //PID Controller? int canOuttakeDW = 7; //Motor Down Wheels CANID bool outtakeDWMotorType = BRUSHED; //MotorType bool outtakeDWInverted = NO; //Inverted? bool outtakeDWEncoder = NO; //Encoder? bool outtakeDWPIDController = NO; //PID Controller? //Control Panel Motorcontroller: int canCPWheels = 4; //Control Panel Wheels CANID bool CPWheelsMotorType = BRUSHLESS; //MotorType bool CPWheelsInverted = NO; //Inverted? bool CPWheelsEncoder = NO; //Encoder? bool CPWheelsPIDController = NO; //PID Controller? //Pneumatics //Pneumatic Control Module: int canPCM = 11; //Power Distribution Panel: int canPDP = 0; //Pigeon Gyroscope: int canPigeon = 12; //Sensors //ColorSensor: frc::I2C::Port portColorSensorCP = frc::I2C::Port::kOnboard; //Acceleration Settings //Drivetrain Acceleration: int accDrivetrain = 0.2; //Intake Acceleration: int accIntakeCylinder = 1; //Storage Acceleration: int accStorageRevolver = 1; int accStorageLoader = 0.1; //Outtake Acceleration: int accOuttake = 1; //Control Panel: int accCPWheels = 0.2; //Pneumatic Ports (PCM Ports) //Intake Pistons: int intakeLRPortForward = 0; //Left intake piston forward int intakeLRPortReverse = 1; //Left intake piston reverse //Control Panel Piston: int cpPortForward = 2; //Control panel piston forward int cpPortReverse = 3; //Control panel piston reverse //Drive Settings: (RTPI_Drivetrain) //Drive Mode's #define ROCKET_LEAGUE_DRIVE 0 #define FIRST_PERSON_SHOOTER_DRIVE 1 //drive Mode int driveMode = ROCKET_LEAGUE_DRIVE; //Standard Drive Mode //Intake Settings (RTPI_Intake) //Max Intake Speed double intakeSpeed = 0.5; //Change State Detection Variables bool intakeBState0 = 0; //Current Intake Button State, Number 0 bool lastIntakeBState0 = 0; //last Intake Button State, Number 0 bool intakePState0 = 0; //Current Intake Piston State, Number 0 //Storage Settings (RTPI_Storage) //Change State Detection Revolver 0 bool storageRevolverBState0 = 0; bool lastStorageRevolverBState0 = 0; //Change State Detection Revolver 1 bool storageRevolverBState1 = 0; bool lastStorageRevolverBState1 = 0; //Pneumatic Settings: (RTPI_Pneumatics) // //Autonomous Functions: //Autonomous Enabled/Disabled bool autoFunction = false; };
[ "duncan.kikkert@gmail.com" ]
duncan.kikkert@gmail.com
193da0ecabeeeed73c5e746d3b97800b97b75a5d
5380227d69d4968dd61125938e6761069e3463c3
/leetcode222/leetcode222/main.cpp
4b716e3877d93fc808cee4e5c59202ddca123ff9
[]
no_license
ly-huang/LeetCode
5abf16cd32951ef1bd61d102c65ea5334bd672ee
f7c787eb96c1cca5232a18be39b9410ffa21577b
refs/heads/master
2023-03-06T09:08:53.751250
2021-02-20T03:40:09
2021-02-20T03:40:09
280,097,655
0
0
null
null
null
null
UTF-8
C++
false
false
524
cpp
// // main.cpp // leetcode222 // // Created by ly on 2020/11/24. // #include <iostream> struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; int countNodes(TreeNode* root) { if(root==nullptr) return 0; int left=countNodes(root->left); int right=countNodes(root->right); return 1+left+right; } int main(int argc, const char * argv[]) { // insert code here... std::cout << "Hello, World!\n"; return 0; }
[ "" ]
b0cc7f4ffd7529e46f32e244dc4f16232ba98521
bf77a7039872e0a55daeaed8ecadae5eb1726f71
/components/setup/steam.cpp
8a01262a7921372ade05283d269af9f45751ab2a
[]
no_license
m1cke1/LinkerMod
7723b569b2c2146d869678301f04f219f1a70dba
3183ed6397d64c4df739dc5ab0e42b071932d120
refs/heads/master
2020-12-25T15:50:52.317558
2016-05-10T23:01:09
2016-05-10T23:01:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,064
cpp
#include "steam.h" #include <Windows.h> #include "io.h" static char appDir_BO1[MAX_PATH] = ""; int AppInfo_Init(void) { if (!SteamAPI_Init()) { SteamAPI_Shutdown(); printf("ERROR: SteamAPI could not be initialized\n"); return 1; } printf("\nSearching for \"Call of Duty: Black Ops\"... "); bool appInstalled_BO1_SP = SteamApps()->BIsAppInstalled(APPID_BO1_SP); if (!appInstalled_BO1_SP) { printf("Failed!\n"); return 2; } char appDir_BO1_SP[MAX_PATH] = ""; SteamApps()->GetAppInstallDir(APPID_BO1_SP, appDir_BO1_SP, MAX_PATH); printf("Found!\n"); printf_v(" %s\n", appDir_BO1_SP); printf("Searching for \"Call of Duty: Black Ops Mod Tools (BETA)\"... "); bool appInstalled_BO1_TOOLS = SteamApps()->BIsAppInstalled(APPID_BO1_TOOLS); if (!appInstalled_BO1_TOOLS) { printf("Failed!\n"); return 2; } char appDir_BO1_TOOLS[MAX_PATH] = ""; SteamApps()->GetAppInstallDir(APPID_BO1_TOOLS, appDir_BO1_TOOLS, MAX_PATH); printf("Found!\n"); printf_v(" %s\n\n", appDir_BO1_TOOLS); if (strcmp(appDir_BO1_SP, appDir_BO1_TOOLS) != 0) { printf("ERROR: Directory Mismatch\n"); return 3; } strcpy_s(appDir_BO1, appDir_BO1_TOOLS); printf_nv("\n"); SteamAPI_Shutdown(); return 0; } const char* AppInfo_AppDir(void) { return appDir_BO1; } const char* AppInfo_FFDir(void) { static char ffCommonDir[MAX_PATH] = "\0"; if (ffCommonDir[0] == '\0') { sprintf_s(ffCommonDir, "%s/zone/common", AppInfo_AppDir()); } return ffCommonDir; } const char* AppInfo_ZoneDir(void) { static char ffLocalizedDir[MAX_PATH] = "\0"; if (ffLocalizedDir[0] == '\0') { sprintf_s(ffLocalizedDir, "%s/zone", AppInfo_AppDir()); } return ffLocalizedDir; } const char* AppInfo_IWDDir(void) { static char iwdDir[MAX_PATH] = "\0"; if (iwdDir[0] == '\0') { sprintf_s(iwdDir, "%s/main", AppInfo_AppDir()); } return iwdDir; } const char* AppInfo_RawDir(void) { static char rawDir[MAX_PATH] = "\0"; if (rawDir[0] == '\0') { sprintf_s(rawDir, "%s/raw", AppInfo_AppDir()); } #if _DEBUG return "out/"; #else return rawDir; #endif }
[ "brokensilencedev@gmail.com" ]
brokensilencedev@gmail.com
0136c325dbf963747777d19741bf7d6073a2b06c
74add41a97244667539db1f082f7b268f5a675d0
/Behaviors/LightOrg.h
cd0cafa434426371e9304c3e9f3776820db5cb43
[]
no_license
LMurphy186232/Core_Model
31c76cfece12b64510bb78ed9300372ebcf07a20
572199409732f71dda3043524cbb85485836a48e
refs/heads/master
2023-06-25T19:55:46.017823
2023-05-28T12:46:21
2023-05-28T12:46:21
39,642,142
5
2
null
2023-08-03T12:58:11
2015-07-24T15:32:52
C++
UTF-8
C++
false
false
9,945
h
//--------------------------------------------------------------------------- #ifndef LightOrgH #define LightOrgH //--------------------------------------------------------------------------- #include <xercesc/dom/DOM.hpp> #include "LightBase.h" class DOMDocument; class clTreePopulation; class clTree; /** * Light org - Version 1.0 * * This class does the organizational work for getting trees their light values * for a timestep. It hooks into a light shell object and is triggered by that * object when it is triggered by the behavior manager. * * All light objects require a tree float data member called "Light", which this * object will register for them. * * An object of this class will then call each tree and direct it to the * appropriate light shell object function for calculation of its light value. * * This class has a core job for those light objects that apply to trees. * However, there are many behaviors which don't calculate tree light levels in * the traditional sense but calculate light levels for other purposes and are * descended from the clLightBase class. This class can still perform useful * services for them, such as keeping the common light parameters. * * A fatal error will be thrown if the number of years per timestep in the * sim manager is not an integer. This is less a calculations problem than a * conceptual one; these light behaviors cannot handle partial growing seasons * and it would be a shame not to alert someone to that. * * Copyright 2011 Charles D. Canham. * @author Lora E. Murphy * * <br>Edit history: * <br>----------------- * <br>October 20, 2011 - Wiped the slate clean for SORTIE 7.0 (LEM) */ class clLightOrg { public: /** * Destructor. */ ~clLightOrg(); /** * Constructor. * @param p_oHookedShell A clLightBase object (a light shell object) which * then becomes the hooked light shell object. */ clLightOrg(clLightBase *p_oHookedShell); /** * Performs the light calculations. This will control the calculation of * light values and their assignment to individual trees. This should be * called each timestep by the hooked shell's * Action() function. */ void DoLightAssignments(); /** * Performs setup functions. It creates and populates the light functions * table. It can find any light shell behavior as long as the * namestring of that object has "lightshell" somewhere in it. Any behavior * which happens to have "lightshell" in its name but is not a light shell * behavior will probably cause crashing. * * DoSetup() is called by the hooked shell's GetData() function. * * @param p_oSimManager Pointer to the simulation manager. Since this object * is not descended from clWorkerBase, it does not already have its own * pointer. * @param p_oDoc Pointer to parsed parameter file. */ void DoSetup(clSimManager *p_oSimManager, xercesc::DOMDocument *p_oDoc); /** * Does the registration of the "Light" tree data member variable. It goes * through the light functions table and, for every species/type combo that * has a valid pointer, registers the variable. Return codes are captured in * the mp_iLightCodes array. * * @param p_oSimManager Pointer to Sim Manager object. * @param p_oPop Tree population object. */ void DoTreeDataMemberRegistrations(clSimManager *p_oSimManager, clTreePopulation *p_oPop); /**Describes the placement of the fisheye photo*/ enum fotocrowndpth {mid, /**<Middle of the crown (halfway down)*/ top /**<Top of the crown*/ }; /** * Gets the light extinction coefficent. If the tree type is snag, then the * snag age is extracted and the coefficient value matching its age is * returned. Otherwise, the value in mp_fLightExtCoef for the appropriate * species is returned. * @param p_oTree Tree for which to obtain the light extinction coefficient. * @return The light extinction coefficient, as the proportion of light * transmitted by the tree, as a value between 0 and 1. */ float GetLightExtCoeff(clTree *p_oTree); /** * Gets the beam fraction of global radiation. * @return The beam fraction of global radiation. */ float GetBeamFractionGlobalRadiation() {return m_fBeamFracGlobRad;}; /** * Gets the clear sky transmission coefficient. * @return The clear sky transmission coefficient. */ float GetClearSkyTransmissionCoefficient() {return m_fClearSkyTransCoeff;}; /** * Gets the maximum tree height across all species. * @return The maximum tree height, in meters. */ float GetMaxTreeHeight() {return m_fMaxTreeHeight;}; /** * Gets the depth of the fisheye photo. * @return Depth of the fisheye photo. */ //enum fotocrowndpth GetPhotoDepth() {return m_iPhotoDepth;}; /** * Gets the first day of the growing season. * @return First day of the growing season, as a julian day. */ int GetFirstDayOfGrowingSeason() {return m_iFirstJulDay;}; /** * Gets the last day of the growing season. * @return Last day of the growing season, as a julian day. */ int GetLastDayOfGrowingSeason() {return m_iLastJulDay;}; /** * Gets a pointer to a light shell object. * @param iSp Species for which to get the light shell object. * @param iTp Tree type for which to get the light shell object. * @return Light shell object for the given species and type, or NULL if it * does not exist. */ clLightBase* GetLightShell(short int iSp, short int iTp) {return mp_oLightFunctionTable[iSp][iTp];}; protected: clTreePopulation *mp_oPop; /**<Stashed pointer to the tree population object*/ clLightBase ***mp_oLightFunctionTable; /**<Light shell objects. Array size is number of species by number of types. For each combo, this points to the light shell object which is handling its light calculation. A pointer may be NULL if a combo is not getting any light calculations.*/ int m_iTotalSpecies; /**<Total number of species*/ int m_iTotalTypes; /**<Total number of tree types*/ // //These are the variables common to all light objects // //Species-specific values - these are in arrays of size = # species and are //read in from the parameter file. These must be provided for all species //whether or not they themselves use light. double *mp_fLightExtCoef;/**<Light extinction coefficient of live tree crowns. One for each species.*/ double **mp_fSnagLightExtCoef; /**<Light extinction coefficient of snag crowns. First index is sized m_iNumSnagAgeClasses, second is sized number of total species. This is only required from the parameter file if the tree population indicates that snags will be made this run.*/ int *mp_iSnagAgeClasses; /**<Upper limit of age in each snag age class. This is for determining a snag's light extinction coefficient. This is only required from the parameter file if the tree population indicates that snags will be made this run. This array is sized m_iNumSnagAgeClasses, but there won't be a value in the last bucket since the value is always infinity.*/ //Single common values - from the parameter file double m_fBeamFracGlobRad; /**<Beam fraction of global radiation. Old parameter kt.*/ double m_fClearSkyTransCoeff; /**<Clear sky transmission coefficient. Old parameter tran*/ int m_iFirstJulDay; /**<First julian day of growing season. Old parameter jdb*/ int m_iLastJulDay; /**<Last julian day of growing season. Old parameter jde*/ int m_iNumSnagAgeClasses; /**<Number of age classes for snags, for the purpose of dividing up the light extinction coefficients. The last age class upper bound is always infinity.*/ //Single common values - calculated float m_fMaxTreeHeight; /**<Maximum height possible for any tree. In meters. Old parameter maxht.*/ /** Return codes for the "Light" tree float data member variable. Array size is number of species by number of types (even if not every species and type requires light)*/ short int **mp_iLightCodes; /** * Declares the light functions table and populates it with the appropriate * behavior pointers. It does this by going through the behaviors and looking * for the ones with "lightshell" in their names, and then getting the * species/type combos those behaviors are supposed to act on. For each of * these combos, their respective place in the table is populated with the * behavior's pointer. * * @param p_oSimManager Sim Manager object. * @param p_oPop Tree population object. * @throw Error if a species/type combo is claimed by more than one behavior. */ void PopulateLightFunctionsTable(clSimManager *p_oSimManager, clTreePopulation *p_oPop); /** * Reads data from the parameter file. The first thing to determine is whether * there are any light objects in need of the common parameters. To determine * this, this function tests each behavior first to see if it can be casted to * type clLightBase. If it can, its flag "m_bNeedsCommonParameters" is * checked. Parameters are only read if there is a behavior whose flag is set * to "true". Additionally, if the tree population indicates that snags are * made, then the light extinction information for them is required. * * @param p_oSimManager Sim Manager object. * @param p_oDoc DOM tree of parsed input file. * @throws modelErr if: * <ul> * <li>The value for m_iPhotoDepth is not a member of fotocrowndepth</li> * <li>The snag age classes are not greater than zero, and the second age * class is not greater than the first</li> * <li>Any of the light extinction coefficients are not between 0 and 1</li> * <li>The value of the clear sky transmission coefficient is 0</li> * </ul> */ void GetParameterFileData(clSimManager *p_oSimManager, xercesc::DOMDocument *p_oDoc); }; //--------------------------------------------------------------------------- #endif
[ "murphyl@caryinstitute.org" ]
murphyl@caryinstitute.org
2cded3b703c94058013c8d69773ea18616993563
771a5f9d99fdd2431b8883cee39cf82d5e2c9b59
/SDK/BP_EyeOfReach_parameters.h
0a5edf7fc238de1bc8d0571604dd1e8edf0bd22b
[ "MIT" ]
permissive
zanzo420/Sea-Of-Thieves-SDK
6305accd032cc95478ede67d28981e041c154dce
f56a0340eb33726c98fc53eb0678fa2d59aa8294
refs/heads/master
2023-03-25T22:25:21.800004
2021-03-20T00:51:04
2021-03-20T00:51:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,117
h
#pragma once // Name: SeaOfThieves, Version: 2.0.23 /*!!DEFINE!!*/ /*!!HELPER_DEF!!*/ /*!!HELPER_INC!!*/ #ifdef _MSC_VER #pragma pack(push, 0x01) #endif namespace CG { //--------------------------------------------------------------------------- // Parameters //--------------------------------------------------------------------------- // Function BP_EyeOfReach.BP_EyeOfReach_C.determine sfx relationship struct ABP_EyeOfReach_C_determine_sfx_relationship_Params { TEnumAsByte<RareAudio_EEmitterRelationship> Relationship; // (Parm, OutParm, ZeroConstructor, IsPlainOldData, NoDestructor) }; // Function BP_EyeOfReach.BP_EyeOfReach_C.DoFireEffect struct ABP_EyeOfReach_C_DoFireEffect_Params { }; // Function BP_EyeOfReach.BP_EyeOfReach_C.UserConstructionScript struct ABP_EyeOfReach_C_UserConstructionScript_Params { }; // Function BP_EyeOfReach.BP_EyeOfReach_C.OnWeaponFired struct ABP_EyeOfReach_C_OnWeaponFired_Params { }; // Function BP_EyeOfReach.BP_EyeOfReach_C.ScopeOn struct ABP_EyeOfReach_C_ScopeOn_Params { }; // Function BP_EyeOfReach.BP_EyeOfReach_C.ScopeOff struct ABP_EyeOfReach_C_ScopeOff_Params { }; // Function BP_EyeOfReach.BP_EyeOfReach_C.ScopeTick struct ABP_EyeOfReach_C_ScopeTick_Params { float DeltaSeconds; // (Parm, ZeroConstructor, IsPlainOldData, NoDestructor) }; // Function BP_EyeOfReach.BP_EyeOfReach_C.ScopeOffImmediate struct ABP_EyeOfReach_C_ScopeOffImmediate_Params { }; // Function BP_EyeOfReach.BP_EyeOfReach_C.GlintOn struct ABP_EyeOfReach_C_GlintOn_Params { }; // Function BP_EyeOfReach.BP_EyeOfReach_C.GlintOff struct ABP_EyeOfReach_C_GlintOff_Params { }; // Function BP_EyeOfReach.BP_EyeOfReach_C.ExecuteUbergraph_BP_EyeOfReach struct ABP_EyeOfReach_C_ExecuteUbergraph_BP_EyeOfReach_Params { int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData, NoDestructor) }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "40242723+alxalx14@users.noreply.github.com" ]
40242723+alxalx14@users.noreply.github.com
f7240bf9f9d696be268498f70086c41cd3a240f9
ea537927ff592c52b8ae13ffff69f1b3c58e4d48
/common/io/file_io.h
90ad885e7f59db723b05a5f7b27822da1b1efab0
[ "MIT" ]
permissive
124327288/YuYu
eacbcbd496ee5032dcf4fdc4fc2dbc4c7b767e1e
f3598899ae5e6892a6b5d546bb0849f5d6a3c5a8
refs/heads/main
2023-02-26T03:07:04.273960
2021-01-25T20:56:28
2021-01-25T20:56:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,048
h
#ifndef _YY_FILE_IO_H_ #define _YY_FILE_IO_H_ #include "strings/utils.h" #include <cassert> class yyFileIO { FILE * m_file; bool m_isOpen; public: yyFileIO() : m_file(nullptr), m_isOpen(false) { } ~yyFileIO() { if(m_isOpen) close(); } bool isEOF() { if(m_isOpen) { return feof(m_file) != 0; } return true; } void close() { if(m_isOpen) { fclose(m_file); m_file=nullptr; m_isOpen=false; } } bool isOpen() { return m_isOpen; } bool open(const char* fileName, const char* charMode) { assert(fileName); assert(charMode); close(); m_file = fopen(fileName,charMode); if( m_file ) m_isOpen = true; return m_isOpen; } void flush() { if( m_isOpen ) fflush(m_file); } size_t writeByte(char b) { if( m_isOpen ) return fwrite(&b,1,1,m_file); return 0; } size_t writeByte(int i) { if( m_isOpen ) return fwrite(&i,1,1,m_file); return 0; } size_t writeUnsignedInt(unsigned int i) { if( m_isOpen ) return fwrite(&i,1,4,m_file); return 0; } size_t writeIntAsUTF16LE(int i) { size_t r=0; if( m_isOpen ) { char buf[32]; sprintf(buf, "%i", i); r = writeANSIStringAsUTF16LE(buf); } return r; } size_t writeUnsignedIntAsUTF16LE(unsigned int i) { size_t r=0; if( m_isOpen ) { char buf[32]; sprintf(buf, "%u", i); r = writeANSIStringAsUTF16LE(buf); } return r; } size_t writeANSIStringAsUTF16LE(const char* str) { size_t r=0; if( m_isOpen ) { auto len = strlen(str); for(size_t i = 0; i < len; ++i) { char c = str[i]; r += writeByte(c); r += writeByte(0x00); } } return r; } size_t writeChar16(char16_t c) { if( m_isOpen ) return fwrite(&c,1,2,m_file); return 0; } size_t writeBytes(void* bytes, size_t numOfBytes) { if( m_isOpen ) return fwrite(bytes,1,numOfBytes,m_file); return 0; } size_t skipLine() { size_t readNum=0; if( m_isOpen ) { unsigned char buf[2]; while(!feof(m_file)) { auto rn = fread(buf, 1, 2, m_file); readNum += rn; if( rn < 2 ) return readNum; wchar_t currentChar = buf[1]; currentChar <<= 8; currentChar |= buf[0]; if(currentChar == L'\n') break; } } return readNum; } size_t readWordFromUTF16LE( std::wstring& outString, bool withoutAlphas = false, bool withoutDigits = false, bool withoutDots = false, bool withoutCommas = false, bool withoutPlusAndMinus = false, bool withoutAnyOtheSymbols = false, bool * isNewLine = nullptr) { size_t readNum=0; if( m_isOpen ) { outString.clear(); bool contain = false; // read 2 bytes unsigned char buf[2]; while(!feof(m_file)) { auto rn = fread(buf, 1, 2, m_file); readNum += rn; if( rn < 2 ) return readNum; wchar_t currentChar = buf[1]; currentChar <<= 8; currentChar |= buf[0]; if(isNewLine){ *isNewLine = false; //if( currentChar == u'\n' ) //*isNewLine = true; } if( currentChar == L'\n' ) { if(isNewLine) *isNewLine = true; return readNum; } if( contain && util::is_space(currentChar) ) return readNum; if( util::is_digit(currentChar) && !withoutDigits ) outString.push_back(currentChar); else if( util::is_alpha(currentChar) && !withoutAlphas ) outString.push_back(currentChar); else if( currentChar == L'-' && !withoutPlusAndMinus ) outString.push_back(currentChar); else if( currentChar == L'+' && !withoutPlusAndMinus ) outString.push_back(currentChar); else if( currentChar == L'.' && !withoutPlusAndMinus ) outString.push_back(currentChar); else if( currentChar == L',' && !withoutPlusAndMinus ) outString.push_back(currentChar); else if( !withoutAnyOtheSymbols ) outString.push_back(currentChar); if( outString.size() ) contain = true; } } return readNum; } bool isUTF16LE(){ if( m_isOpen ) { fseek(m_file, 0, SEEK_SET); unsigned char buf[2]; if( fread(buf,1,2,m_file) == 2 ){ if( buf[0] == 0xff && buf[1] == 0xfe ) return true; else fseek(m_file, 0, SEEK_SET); return false; } } return false; } size_t get_lineUTF16LE( std::wstring& outString){ size_t readNum=0; if( m_isOpen ) { outString.clear(); bool contain = false; // read 2 bytes unsigned char buf[2]; while(!feof(m_file)) { auto rn = fread(buf, 1, 2, m_file); readNum += rn; if( rn < 2 ) return readNum; wchar_t currentChar = buf[1]; currentChar <<= 8; currentChar |= buf[0]; if( currentChar == L'\n' ) break; else outString.push_back(currentChar); } } return readNum; } size_t readUnsignedInt(unsigned int & dds_magic){ size_t r=0; if( m_isOpen ) { r = fread(&dds_magic, 1, 4, m_file); } return r; } size_t readBytes(void* bytes, size_t numOfBytes){ size_t r=0; if( m_isOpen ) { r = fread(bytes, 1, numOfBytes, m_file); } return r; } }; #endif
[ "artembasov@outlook.com" ]
artembasov@outlook.com
c120e022d0204a340ee29901d7c9e29e9c27d831
6db80d5f5db51d3dac6f09c935c9b21fb1c6c793
/image.cc
391ff4783e54564b1b36fd62b72a153593ca801f
[]
no_license
rumandas2005/amazing_repository
29a048020d30ae46a405dfa93b4366811fa46153
c5752f2ca62f371a42211b60e461bb499b7d2150
refs/heads/master
2021-04-27T00:06:22.335112
2017-06-30T23:30:27
2017-06-30T23:30:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,265
cc
// Created by Ioannis Stamos // Modified by Wei Shi #include <iostream> #include <string.h> #include "image.h" using namespace std; namespace image { Image::Image(const Image &an_image){ AllocateSpaceAndSetSize(an_image.num_rows(), an_image.num_columns()); SetNumberGrayLevels(an_image.num_gray_levels()); for (size_t i = 0; i < num_rows(); ++i) for (size_t j = 0; j < num_columns(); ++j){ SetPixel(i,j, an_image.GetPixel(i,j)); } } Image::Image(Image &&an_image) { AllocateSpaceAndSetSize(std::move(an_image.num_rows()), std::move(an_image.num_columns())); SetNumberGrayLevels(std::move(an_image.num_gray_levels())); for (size_t i = 0; i < num_rows(); ++i) for (size_t j = 0; j < num_columns(); ++j){ SetPixel(i,j, std::move(an_image.GetPixel(i,j))); } } Image::~Image(){ DeallocateSpace(); } Image& Image::operator=(const Image& rhs) { AllocateSpaceAndSetSize(rhs.num_rows(), rhs.num_columns()); SetNumberGrayLevels(rhs.num_gray_levels()); for (size_t i = 0; i < num_rows(); ++i) { for (size_t j = 0; j < num_columns(); ++j){ SetPixel(i,j,rhs.GetPixel(i,j)); } } return *this; } Image& Image::operator=(Image&& rhs) { AllocateSpaceAndSetSize(std::move(rhs.num_rows()), std::move(rhs.num_columns())); SetNumberGrayLevels(std::move(rhs.num_gray_levels())); for (size_t i = 0; i < num_rows(); ++i) { for (size_t j = 0; j < num_columns(); ++j){ SetPixel(i,j,std::move(rhs.GetPixel(i,j))); } } return *this; } void Image::AllocateSpaceAndSetSize(size_t num_rows, size_t num_columns) { if (pixels_ != nullptr){ DeallocateSpace(); } pixels_ = new int*[num_rows]; for (size_t i = 0; i < num_rows; ++i) pixels_[i] = new int[num_columns]; num_rows_ = num_rows; num_columns_ = num_columns; } void Image::DeallocateSpace() { for (size_t i = 0; i < num_rows_; i++) delete pixels_[i]; delete pixels_; pixels_ = nullptr; num_rows_ = 0; num_columns_ = 0; } void Image::Fill(unsigned short value) { for(size_t i = 0; i < num_rows_; ++i) { for(size_t j = 0; j < num_columns_; ++j) { SetPixel(i,j,value); } } } bool ReadImage(const string &filename, Image *an_image) { if (an_image == nullptr) abort(); FILE *input = fopen(filename.c_str(),"rb"); if (input == 0) { cout << "ReadImage: Cannot open file" << endl; return false; } // Check for the right "magic number". char line[1024]; if (fread(line, 1, 3, input) != 3 || strncmp(line,"P5\n",3)) { fclose(input); cout << "ReadImage: Expected .pgm file" << endl; return false; } // Skip comments. do fgets(line, sizeof line, input); while(*line == '#'); // Read the width and height. int num_columns,num_rows; sscanf(line,"%d %d\n", &num_columns, &num_rows); an_image->AllocateSpaceAndSetSize(num_rows, num_columns); // Read # of gray levels. fgets(line, sizeof line, input); int levels; sscanf(line,"%d\n", &levels); an_image->SetNumberGrayLevels(levels); // read pixel row by row. for (int i = 0; i < num_rows; ++i) { for (int j = 0;j < num_columns; ++j) { const int byte=fgetc(input); if (byte == EOF) { fclose(input); cout << "ReadImage: short file" << endl; return false; } an_image->SetPixel(i, j, byte); } } fclose(input); return true; } bool WriteImage(const string &filename, const Image &an_image) { FILE *output = fopen(filename.c_str(), "w"); if (output == 0) { cout << "WriteImage: cannot open file" << endl; return false; } const int num_rows = an_image.num_rows(); const int num_columns = an_image.num_columns(); const int colors = an_image.num_gray_levels(); // Write the header. fprintf(output, "P5\n"); // Magic number. fprintf(output, "#\n"); // Empty comment. fprintf(output, "%d %d\n%03d\n", num_columns, num_rows, colors); for (int i = 0; i < num_rows; ++i) { for (int j = 0; j < num_columns; ++j) { const int byte = an_image.GetPixel(i , j); if (fputc(byte,output) == EOF) { fclose(output); cout << "WriteImage: could not write" << endl; return false; } } } fclose(output); return true; } } // namespace ComputerVisionProjects
[ "dobobobado@gmail.com" ]
dobobobado@gmail.com
d0b22d5ca4295b3985419f1fa0a4399b98daba76
5b39937c88d98d8bf9aa3d242ade98d3ebdb3bd3
/Documents Personnels/Iris Hoel/Simu 2011 v1.1/outils_strategie.cpp
0cdf54db3d420aaad5fc7aed8bc4e9f8dd5062fd
[]
no_license
robinmoussu/robotronik
2c542360ac5819a3cedab3b3786909df021e927f
5a21218001c79dbfd1c987b2041f9ba2647b0c96
refs/heads/master
2021-01-10T21:11:34.944493
2015-03-12T17:04:04
2015-03-12T17:04:04
32,186,393
0
0
null
null
null
null
ISO-8859-2
C++
false
false
9,837
cpp
# include "main.hpp" extern int BORDURES_BLANCHES; extern int LARGEUR_FENETRE; extern int HAUTEUR_FENETRE; extern float RAPPORT_LARGEUR; extern float RAPPORT_HAUTEUR; extern int EPAISSEUR_PIXEL; extern int DELAY; extern float VITESSE_TRANS_ROBOT_DEFAUT; extern float VITESSE_ROT_ROBOT_DEFAUT; extern float VITESSE_PINCE_DEFAUT; extern int ANGLE_PINCE_DEFAUT; extern int CONFIG; extern int DEBUG; extern int num_strat; extern Elements tableau_p[19]; //Case grille[6][6]; void ini_strategie() { /* int i = 0, j = 0; for(i=0; i<6;i++) grille[i][i].occupe = 0; for(i=0; i<6;i++) for(j=0; j<6; j++) { grille[i][j].position.x = i; grille[i][j].position.y = j; } for(i=0; i<6;i +=2) for(j=0; j<6; j +=2) { grille[i][j].couleur = BLEU; } for(i=1; i<6;i +=2) for(j=1; j<6; j +=2) { grille[i][j].couleur = ROUGE; } */ //creer_info_position(-1,-1); } void gagner(SDL_Surface *screen, Robot *R) { if(R->etape == 7 && R->position_robot.x >= 15*RAPPORT_LARGEUR && R->position_robot.x <= 25*RAPPORT_LARGEUR && R->position_robot.y >= 15*RAPPORT_HAUTEUR && R->position_robot.y <= 25*RAPPORT_HAUTEUR && R->saisie_arriere_ok != -1 && R->couleur_depart == ROUGE ) { log("Objectifs remplis !"); creer_info("gagné ! :P"); } else if(R->etape == 7 && R->position_robot.x >= 275*RAPPORT_LARGEUR && R->position_robot.x <= 285*RAPPORT_LARGEUR && R->position_robot.y >= 15*RAPPORT_HAUTEUR && R->position_robot.y <= 25*RAPPORT_HAUTEUR && R->saisie_arriere_ok != -1 && R->couleur_depart == BLEU ) { log("Objectifs remplis !"); creer_info("gagné ! :P"); } } //---------------------- int position_grille_x(Robot *R) { int i = 0; for(i=0;i<=6;i++) { if(R->position_robot.x >= (44.4+35*i)*RAPPORT_LARGEUR && R->position_robot.x <= (45.6+35*i)*RAPPORT_LARGEUR) { if(R->num ==1 ) creer_info_position(i,-2); return i; } } if(R->num ==1 ) creer_info_position(-1,-2); return -1; } int position_grille_y(Robot *R) { int i = 0; for(i=0;i<=5;i++) { if(R->position_robot.y >= (35*i-0.6)*RAPPORT_HAUTEUR && R->position_robot.y <= (35*i+0.6)*RAPPORT_HAUTEUR) { if(R->num ==1 ) creer_info_position(-2,i); return i; } } if(R->num ==1 ) creer_info_position(-2,-1); return -1; } int direction_grille(Robot *R) { if(R->direction_robot <= 1.58 && R->direction_robot >= 1.57 ) return BAS; else if(R->direction_robot <= 3.15 && R->direction_robot >= 3.14 ) return GAUCHE; else if(R->direction_robot <= 4.72 && R->direction_robot >= 4.71 ) return HAUT; else if(R->direction_robot <= 0.01 | R->direction_robot >= 6.27) return DROITE; return -1; } //---------------------- llist inverser_inst_couleur(llist liste) { llist liste_save = liste; liste = rechercherElement(liste, TOURNER); while(liste != NULL) { liste->val.signe *= -1; liste = liste->nxt; liste = rechercherElement(liste, TOURNER); } return liste_save; } llist inverser_sens_avancer(llist liste) { llist liste_save = liste; liste = rechercherElement(liste, AVANCER); while(liste != NULL) { liste->val.signe *= -1; liste = liste->nxt; liste = rechercherElement(liste, AVANCER); } return liste_save; } int rotation_ok(Robot * R) { int ret = 1, i =0; int distance_min = (10+23)*(10+23); for(i=0; i < 19; i++ ) if( R->saisie_avant_ok != i && R->saisie_arriere_ok != i && (distance_carre(R->position_robot.x,R->position_robot.y,tableau_p[i].position.x,tableau_p[i].position.y) < distance_min)) ret = 0; return ret; } //---------------------- void save_inst(llist liste, inst *instruction_en_cour) { liste->val.valeur = (*instruction_en_cour).valeur; (*instruction_en_cour).valeur = 0; } llist deposer_avant_derriere_proche(llist liste, int sens, inst *instruction_en_cour) { save_inst(liste, instruction_en_cour); inst new_inst; new_inst.type = TOURNER; new_inst.valeur = 108; new_inst.signe = -1*sens; new_inst.vitesse = 0; par_defaut(&new_inst); liste = ajouterEnTete(liste, new_inst); new_inst.type = AVANCER; new_inst.valeur = 15; new_inst.signe = -1; new_inst.vitesse = 0; par_defaut(&new_inst); liste = ajouterEnTete(liste, new_inst); new_inst.type = LIBERER_AVANT; new_inst.valeur = 0; new_inst.signe = 0; new_inst.vitesse = 0; par_defaut(&new_inst); liste = ajouterEnTete(liste, new_inst); new_inst.type = AVANCER; new_inst.valeur = 15; new_inst.signe = 0; new_inst.vitesse = 0; par_defaut(&new_inst); liste = ajouterEnTete(liste, new_inst); new_inst.type = TOURNER; new_inst.valeur = 108; new_inst.signe = sens; new_inst.vitesse = 0; par_defaut(&new_inst); liste = ajouterEnTete(liste, new_inst); liste = ajouterEnTete(liste, new_inst); return liste; } llist deposer_avant_derriere_loin(llist liste, int sens, inst *instruction_en_cour) { save_inst(liste, instruction_en_cour); inst new_inst; new_inst.type = TOURNER; new_inst.valeur = 135; new_inst.signe = -1*sens; new_inst.vitesse = 0; par_defaut(&new_inst); liste = ajouterEnTete(liste, new_inst); new_inst.type = AVANCER; new_inst.valeur = 25; new_inst.signe = -1; new_inst.vitesse = 0; par_defaut(&new_inst); liste = ajouterEnTete(liste, new_inst); new_inst.type = LIBERER_AVANT; new_inst.valeur = 0; new_inst.signe = 0; new_inst.vitesse = 0; par_defaut(&new_inst); liste = ajouterEnTete(liste, new_inst); new_inst.type = AVANCER; new_inst.valeur = 25; new_inst.signe = 0; new_inst.vitesse = 0; par_defaut(&new_inst); liste = ajouterEnTete(liste, new_inst); new_inst.type = TOURNER; new_inst.valeur = 135; new_inst.signe = sens; new_inst.vitesse = 0; par_defaut(&new_inst); liste = ajouterEnTete(liste, new_inst); liste = ajouterEnTete(liste, new_inst); return liste; } llist deposer_avant_devant_proche(llist liste, int sens, inst *instruction_en_cour) { save_inst(liste, instruction_en_cour); inst new_inst; new_inst.type = TOURNER; new_inst.valeur = 72; new_inst.signe = -1*sens; new_inst.vitesse = 0; par_defaut(&new_inst); liste = ajouterEnTete(liste, new_inst); new_inst.type = AVANCER; new_inst.valeur = 15; new_inst.signe = -1; new_inst.vitesse = 0; par_defaut(&new_inst); liste = ajouterEnTete(liste, new_inst); new_inst.type = LIBERER_AVANT; new_inst.valeur = 0; new_inst.signe = 0; new_inst.vitesse = 0; par_defaut(&new_inst); liste = ajouterEnTete(liste, new_inst); new_inst.type = AVANCER; new_inst.valeur = 15; new_inst.signe = 0; new_inst.vitesse = 0; par_defaut(&new_inst); liste = ajouterEnTete(liste, new_inst); new_inst.type = TOURNER; new_inst.valeur = 72; new_inst.signe = sens; new_inst.vitesse = 0; par_defaut(&new_inst); liste = ajouterEnTete(liste, new_inst); liste = ajouterEnTete(liste, new_inst); return liste; } llist deposer_avant_devant_loin(llist liste, int sens, inst *instruction_en_cour) { save_inst(liste, instruction_en_cour); inst new_inst; new_inst.type = TOURNER; new_inst.valeur = 45; new_inst.signe = -1*sens; new_inst.vitesse = 0; par_defaut(&new_inst); liste = ajouterEnTete(liste, new_inst); new_inst.type = AVANCER; new_inst.valeur = 25; new_inst.signe = -1; new_inst.vitesse = 0; par_defaut(&new_inst); liste = ajouterEnTete(liste, new_inst); new_inst.type = LIBERER_AVANT; new_inst.valeur = 0; new_inst.signe = 0; new_inst.vitesse = 0; par_defaut(&new_inst); liste = ajouterEnTete(liste, new_inst); new_inst.type = AVANCER; new_inst.valeur = 25; new_inst.signe = 0; new_inst.vitesse = 0; par_defaut(&new_inst); liste = ajouterEnTete(liste, new_inst); new_inst.type = TOURNER; new_inst.valeur = 45; new_inst.signe = sens; new_inst.vitesse = 0; par_defaut(&new_inst); liste = ajouterEnTete(liste, new_inst); liste = ajouterEnTete(liste, new_inst); return liste; } llist fermer_avant(llist liste, inst *instruction_en_cour) { save_inst(liste, instruction_en_cour); inst new_inst; new_inst.type = FERMER_AVANT; new_inst.valeur = ANGLE_PINCE_DEFAUT; new_inst.vitesse = VITESSE_PINCE_DEFAUT; liste = ajouterEnTete(liste, new_inst); liste = ajouterEnTete(liste, new_inst); return liste; } llist fermer_arriere(llist liste, inst *instruction_en_cour) { save_inst(liste, instruction_en_cour); inst new_inst; new_inst.type = FERMER_ARRIERE; new_inst.valeur = ANGLE_PINCE_DEFAUT; new_inst.vitesse = VITESSE_PINCE_DEFAUT; liste = ajouterEnTete(liste, new_inst); liste = ajouterEnTete(liste, new_inst); return liste; }
[ "felix@piedallu.me" ]
felix@piedallu.me
9120564a9fbe2f9319a12afab0d793fb514486a8
406e523984da1490f37b4d1347fb55149923e310
/include/utils/log.h
229d703976245fc3db29202e6f50cbde9ed4beca
[]
no_license
gaomy3832/graphGASLite
458869e12d5c0c616ca6af693ac541050b2aef97
1c6679f83f3cd129cacadc0ee4587cec1cb820bc
refs/heads/master
2020-05-29T11:52:15.382972
2018-10-20T23:00:57
2018-10-20T23:00:57
48,075,855
2
0
null
null
null
null
UTF-8
C++
false
false
3,433
h
#ifndef UTILS_LOG_H_ #define UTILS_LOG_H_ /** * Generic logging/info/warn/panic routines. */ #include <cstdio> #include <cstdlib> #include <cstring> #include <mutex> #define PANIC_EXIT_CODE (112) /* Logging */ // Generic logging, thread-unsafe #define __panic(logFdErr, logHeader, ...) \ { \ fprintf(logFdErr, "%sPanic on %s:%d: ", logHeader, __FILE__, __LINE__); \ fprintf(logFdErr, __VA_ARGS__); \ fprintf(logFdErr, "\n"); \ fflush(logFdErr); \ exit(PANIC_EXIT_CODE); \ } #define __warn(logFdErr, logHeader, ...) \ { \ fprintf(logFdErr, "%sWARN: ", logHeader); \ fprintf(logFdErr, __VA_ARGS__); \ fprintf(logFdErr, "\n"); \ fflush(logFdErr); \ } #define __info(logFdOut, logHeader, ...) \ { \ fprintf(logFdOut, "%s", logHeader); \ fprintf(logFdOut, __VA_ARGS__); \ fprintf(logFdOut, "\n"); \ fflush(logFdOut); \ } // Basic logging, thread-unsafe, print to stdout/stderr, no header #define panic(...) __panic(stderr, "", __VA_ARGS__) #define warn(...) __warn(stderr, "", __VA_ARGS__) #define info(...) __info(stdout, "", __VA_ARGS__) // Logging class, thread-safe, support redirection to files, support header class Logger { public: Logger(const char* header = "", const char* file = nullptr) : logHeader(header) { if (file) { fd = fopen(file, "a"); if (fd == NULL) { perror("fopen() failed"); // We can panic in InitLog (will dump to stderr) panic("Could not open logfile %s", file); } logFdOut = fd; logFdErr = fd; } else { fd = nullptr; logFdOut = stdout; logFdErr = stderr; } } ~Logger() { fclose(fd); } template<typename... Args> void log_panic(const char* fmt, Args... args) { __panic(logFdErr, logHeader.c_str(), fmt, args...); } template<typename... Args> void log_warn(const char* fmt, Args... args) { logPrintLock.lock(); __warn(logFdErr, logHeader.c_str(), fmt, args...); logPrintLock.unlock(); } template<typename... Args> void log_info(const char* fmt, Args... args) { logPrintLock.lock(); __info(logFdErr, logHeader.c_str(), fmt, args...); logPrintLock.unlock(); } private: FILE* fd; FILE* logFdErr; FILE* logFdOut; const std::string logHeader; std::mutex logPrintLock; }; /* Assertion */ #ifndef NASSERT #ifndef assert #define assert(expr) \ if (!(expr)) { \ fprintf(stderr, "%sFailed assertion on %s:%d '%s'\n", "", __FILE__, __LINE__, #expr); \ fflush(stderr); \ exit(PANIC_EXIT_CODE); \ }; #endif #define assert_msg(cond, ...) \ if (!(cond)) { \ fprintf(stderr, "%sFailed assertion on %s:%d: ", "", __FILE__, __LINE__); \ fprintf(stderr, __VA_ARGS__); \ fprintf(stderr, "\n"); \ fflush(stderr); \ exit(PANIC_EXIT_CODE); \ }; #else // NASSERT // Avoid unused warnings, never emit any code // see http://cnicholson.net/2009/02/stupid-c-tricks-adventures-in-assert/ #define assert(cond) do { (void)sizeof(cond); } while (0); #define assert_msg(cond, ...) do { (void)sizeof(cond); } while (0); #endif // NASSERT #endif // UTILS_LOG_H_
[ "mgao12@stanford.edu" ]
mgao12@stanford.edu
c7c01a0c23fede58ef0c4c34e092ef3e84d74806
1b091302660b32d47d22ce3c4834af5f002c7ca3
/XDKSamples/IntroGraphics/SimpleTexture/SimpleTexture.cpp
62b1e7164b647c91a6b401e561578495450f4098
[ "MIT" ]
permissive
lb-YoshikiDomae/Xbox-ATG-Samples
bf13c65a82f453b74b270af24b88461b42e99c03
76d236e3bd372aceec18b2ad0556a7879dbd9628
refs/heads/master
2021-07-08T14:42:56.429213
2017-10-03T00:28:02
2017-10-03T00:28:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,424
cpp
//-------------------------------------------------------------------------------------- // SimpleTexture.cpp // // Advanced Technology Group (ATG) // Copyright (C) Microsoft Corporation. All rights reserved. //-------------------------------------------------------------------------------------- #include "pch.h" #include "SimpleTexture.h" #include "ATGColors.h" #include "ReadData.h" using namespace DirectX; using Microsoft::WRL::ComPtr; namespace { struct Vertex { XMFLOAT4 position; XMFLOAT2 texcoord; }; std::vector<uint8_t> LoadBGRAImage(const wchar_t* filename, uint32_t& width, uint32_t& height) { ComPtr<IWICImagingFactory> wicFactory; DX::ThrowIfFailed(CoCreateInstance(CLSID_WICImagingFactory2, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&wicFactory))); ComPtr<IWICBitmapDecoder> decoder; DX::ThrowIfFailed(wicFactory->CreateDecoderFromFilename(filename, 0, GENERIC_READ, WICDecodeMetadataCacheOnDemand, decoder.GetAddressOf())); ComPtr<IWICBitmapFrameDecode> frame; DX::ThrowIfFailed(decoder->GetFrame(0, frame.GetAddressOf())); DX::ThrowIfFailed(frame->GetSize(&width, &height)); WICPixelFormatGUID pixelFormat; DX::ThrowIfFailed(frame->GetPixelFormat(&pixelFormat)); uint32_t rowPitch = width * sizeof(uint32_t); uint32_t imageSize = rowPitch * height; std::vector<uint8_t> image; image.resize(size_t(imageSize)); if (memcmp(&pixelFormat, &GUID_WICPixelFormat32bppBGRA, sizeof(GUID)) == 0) { DX::ThrowIfFailed(frame->CopyPixels(0, rowPitch, imageSize, reinterpret_cast<BYTE*>(image.data()))); } else { ComPtr<IWICFormatConverter> formatConverter; DX::ThrowIfFailed(wicFactory->CreateFormatConverter(formatConverter.GetAddressOf())); BOOL canConvert = FALSE; DX::ThrowIfFailed(formatConverter->CanConvert(pixelFormat, GUID_WICPixelFormat32bppBGRA, &canConvert)); if (!canConvert) { throw std::exception("CanConvert"); } DX::ThrowIfFailed(formatConverter->Initialize(frame.Get(), GUID_WICPixelFormat32bppBGRA, WICBitmapDitherTypeErrorDiffusion, nullptr, 0, WICBitmapPaletteTypeMedianCut)); DX::ThrowIfFailed(formatConverter->CopyPixels(0, rowPitch, imageSize, reinterpret_cast<BYTE*>(image.data()))); } return image; } } Sample::Sample() : m_frame(0) { // Use gamma-correct rendering. m_deviceResources = std::make_unique<DX::DeviceResources>(DXGI_FORMAT_B8G8R8A8_UNORM_SRGB, DXGI_FORMAT_D32_FLOAT, 2, DX::DeviceResources::c_Enable4K_UHD); } // Initialize the Direct3D resources required to run. void Sample::Initialize(IUnknown* window) { m_gamePad = std::make_unique<GamePad>(); m_deviceResources->SetWindow(window); m_deviceResources->CreateDeviceResources(); CreateDeviceDependentResources(); m_deviceResources->CreateWindowSizeDependentResources(); CreateWindowSizeDependentResources(); } #pragma region Frame Update // Executes basic render loop. void Sample::Tick() { PIXBeginEvent(PIX_COLOR_DEFAULT, L"Frame %I64u", m_frame); m_timer.Tick([&]() { Update(m_timer); }); Render(); PIXEndEvent(); m_frame++; } // Updates the world. void Sample::Update(DX::StepTimer const&) { PIXBeginEvent(PIX_COLOR_DEFAULT, L"Update"); auto pad = m_gamePad->GetState(0); if (pad.IsConnected()) { if (pad.IsViewPressed()) { Windows::ApplicationModel::Core::CoreApplication::Exit(); } } PIXEndEvent(); } #pragma endregion #pragma region Frame Render // Draws the scene. void Sample::Render() { // Don't try to render anything before the first Update. if (m_timer.GetFrameCount() == 0) { return; } // Prepare the render target to render a new frame. m_deviceResources->Prepare(); Clear(); auto context = m_deviceResources->GetD3DDeviceContext(); PIXBeginEvent(context, PIX_COLOR_DEFAULT, L"Render"); // Set input assembler state. context->IASetInputLayout(m_spInputLayout.Get()); UINT strides = sizeof(Vertex); UINT offsets = 0; context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); context->IASetVertexBuffers(0, 1, m_spVertexBuffer.GetAddressOf(), &strides, &offsets); context->IASetIndexBuffer(m_spIndexBuffer.Get(), DXGI_FORMAT_R16_UINT, 0); // Set shaders. context->VSSetShader(m_spVertexShader.Get(), nullptr, 0); context->GSSetShader(nullptr, nullptr, 0); context->PSSetShader(m_spPixelShader.Get(), nullptr, 0); // Set texture and sampler. auto sampler = m_spSampler.Get(); context->PSSetSamplers(0, 1, &sampler); auto texture = m_spTexture.Get(); context->PSSetShaderResources(0, 1, &texture); // Draw quad. context->DrawIndexed(6, 0, 0); PIXEndEvent(context); // Show the new frame. PIXBeginEvent(context, PIX_COLOR_DEFAULT, L"Present"); m_deviceResources->Present(); m_graphicsMemory->Commit(); PIXEndEvent(context); } // Helper method to clear the back buffers. void Sample::Clear() { auto context = m_deviceResources->GetD3DDeviceContext(); PIXBeginEvent(context, PIX_COLOR_DEFAULT, L"Clear"); // Clear the views. auto renderTarget = m_deviceResources->GetRenderTargetView(); auto depthStencil = m_deviceResources->GetDepthStencilView(); // Use linear clear color for gamma-correct rendering. context->ClearRenderTargetView(renderTarget, ATG::ColorsLinear::Background); context->ClearDepthStencilView(depthStencil, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0); context->OMSetRenderTargets(1, &renderTarget, depthStencil); // Set the viewport. auto viewport = m_deviceResources->GetScreenViewport(); context->RSSetViewports(1, &viewport); PIXEndEvent(context); } #pragma endregion #pragma region Message Handlers // Message handlers void Sample::OnSuspending() { auto context = m_deviceResources->GetD3DDeviceContext(); context->Suspend(0); } void Sample::OnResuming() { auto context = m_deviceResources->GetD3DDeviceContext(); context->Resume(); m_timer.ResetElapsedTime(); } #pragma endregion #pragma region Direct3D Resources // These are the resources that depend on the device. void Sample::CreateDeviceDependentResources() { auto device = m_deviceResources->GetD3DDevice(); m_graphicsMemory = std::make_unique<GraphicsMemory>(device, m_deviceResources->GetBackBufferCount()); // Load and create shaders. auto vertexShaderBlob = DX::ReadData(L"VertexShader.cso"); DX::ThrowIfFailed( device->CreateVertexShader(vertexShaderBlob.data(), vertexShaderBlob.size(), nullptr, m_spVertexShader.ReleaseAndGetAddressOf())); auto pixelShaderBlob = DX::ReadData(L"PixelShader.cso"); DX::ThrowIfFailed( device->CreatePixelShader(pixelShaderBlob.data(), pixelShaderBlob.size(), nullptr, m_spPixelShader.ReleaseAndGetAddressOf())); // Create input layout. static const D3D11_INPUT_ELEMENT_DESC s_inputElementDesc[2] = { { "SV_Position", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 16, D3D11_INPUT_PER_VERTEX_DATA , 0 }, }; DX::ThrowIfFailed( device->CreateInputLayout(s_inputElementDesc, _countof(s_inputElementDesc), vertexShaderBlob.data(), vertexShaderBlob.size(), m_spInputLayout.ReleaseAndGetAddressOf())); // Create vertex buffer. static const Vertex s_vertexData[4] = { { { -0.5f, -0.5f, 0.5f, 1.0f },{ 0.f, 1.f } }, { { 0.5f, -0.5f, 0.5f, 1.0f },{ 1.f, 1.f } }, { { 0.5f, 0.5f, 0.5f, 1.0f },{ 1.f, 0.f } }, { { -0.5f, 0.5f, 0.5f, 1.0f },{ 0.f, 0.f } }, }; D3D11_SUBRESOURCE_DATA initialData = {}; initialData.pSysMem = s_vertexData; D3D11_BUFFER_DESC bufferDesc = {}; bufferDesc.ByteWidth = sizeof(s_vertexData); bufferDesc.Usage = D3D11_USAGE_IMMUTABLE; bufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; bufferDesc.StructureByteStride = sizeof(Vertex); DX::ThrowIfFailed( device->CreateBuffer(&bufferDesc, &initialData, m_spVertexBuffer.ReleaseAndGetAddressOf())); // Create index buffer. static const uint16_t s_indexData[6] = { 3,1,0, 2,1,3, }; initialData.pSysMem = s_indexData; bufferDesc.ByteWidth = sizeof(s_indexData); bufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER; bufferDesc.StructureByteStride = sizeof(uint16_t); DX::ThrowIfFailed( device->CreateBuffer(&bufferDesc, &initialData, m_spIndexBuffer.ReleaseAndGetAddressOf())); // Create sampler. D3D11_SAMPLER_DESC samplerDesc = {}; samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.ComparisonFunc = D3D11_COMPARISON_NEVER; samplerDesc.MinLOD = 0; samplerDesc.MaxLOD = D3D11_FLOAT32_MAX; DX::ThrowIfFailed( device->CreateSamplerState(&samplerDesc, m_spSampler.ReleaseAndGetAddressOf())); // Create texture. D3D11_TEXTURE2D_DESC txtDesc = {}; txtDesc.MipLevels = txtDesc.ArraySize = 1; txtDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM_SRGB; // sunset.jpg is in sRGB colorspace txtDesc.SampleDesc.Count = 1; txtDesc.Usage = D3D11_USAGE_IMMUTABLE; txtDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE; auto image = LoadBGRAImage(L"sunset.jpg", txtDesc.Width, txtDesc.Height); initialData.pSysMem = image.data(); initialData.SysMemPitch = txtDesc.Width * sizeof(uint32_t); ComPtr<ID3D11Texture2D> tex; DX::ThrowIfFailed( device->CreateTexture2D(&txtDesc, &initialData, tex.GetAddressOf())); DX::ThrowIfFailed( device->CreateShaderResourceView(tex.Get(), nullptr, m_spTexture.ReleaseAndGetAddressOf())); } // Allocate all memory resources that change on a window SizeChanged event. void Sample::CreateWindowSizeDependentResources() { } #pragma endregion
[ "chuckw@windows.microsoft.com" ]
chuckw@windows.microsoft.com
960bacd4b3a620ec22f660a87217c6d612ba6c23
6fd10243dd9694a7f42928ba7bff1202025870b8
/bintree/postorder2.cpp
2036dcffbb9953b1ebff68f2d4af155699b0f751
[]
no_license
wangshuaiCode/geeksforgeeks
070db6ba6f3e2c38a56579a9cad953fc231d33ab
ece0f27e6e85f003225a388ffed173804862320f
refs/heads/master
2020-05-17T16:26:20.372156
2014-10-24T14:50:55
2014-10-24T14:50:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
643
cpp
struct Node { int data; struct Node *left; struct Node *right; } struct btnode{ struct Node *node; bool isFirst; } void postorder(strcut Node *root) { stack<struct btnode *> s; struct Node * p = root; struct btnode *temp; while(!s.empty() && p != NULL) { struct btnode * bt = (struct btnode *)malloc(sizeof(struct btnode)); bt -> node = p; bt -> isFirst = true; s.push(bt); p = p -> left; } if(!s.empty()) { temp = s.top(); s.pop(); if(temp -> isFirst == true) { temp -> isFirst = false; s.push(temp); p = temp -> node -> right; } else { cout << temp -> node -> data; p = NULL; } } }
[ "ws93124@163.com" ]
ws93124@163.com
c7924fbb0ae676b279f6d63f46198f196299c898
89e8958e54176ef05f1bbeec3cd64cfe74c68145
/arduino/ESPWebServer/ESPWebServer.ino
3bd6e60e05d859e469ff393058928cfa39504336
[]
no_license
Theophrast/ESPWebServer
8774aca1f3a06d2287e6fcb801af0da3a8056348
e1ab38c8f570d2a0618b2ef331d3012f3c0fe07e
refs/heads/master
2021-09-19T14:48:56.787853
2018-07-28T16:34:31
2018-07-28T16:34:31
113,192,255
0
0
null
null
null
null
UTF-8
C++
false
false
6,625
ino
/* SD card webserver http://esp8266.github.io/Arduino/versions/2.0.0/doc/libraries.html */ #include <ArduinoJson.h> #include <ESP8266WiFi.h> #include <WiFiClient.h> #include <ESP8266WebServer.h> #include <ESP8266mDNS.h> #include <SPI.h> #include "SdFat.h" ADC_MODE(ADC_VCC); #define DBG_OUTPUT_PORT Serial const char* ssid = "T***I"; const char* password = "U******51"; const char* host = "esp_webserver"; ESP8266WebServer httpserver(80); ESP8266WebServer statusserver(8080); #define USE_SDIO 0 const uint8_t SD_CS_PIN = 16; SdFat SD; static bool hasSD = false; File uploadFile; bool loadFromSdCard(String path) { DBG_OUTPUT_PORT.println("--> loadFromSdCard() path: "+path); String dataType = "text/plain"; if (path.endsWith("/")) path += "index.htm"; if (path.endsWith(".src")) path = path.substring(0, path.lastIndexOf(".")); else if (path.endsWith(".htm") || path.endsWith(".html")) dataType = "text/html"; else if (path.endsWith(".css")) dataType = "text/css"; else if (path.endsWith(".js")) dataType = "application/javascript"; else if (path.endsWith(".png")) dataType = "image/png"; else if (path.endsWith(".gif")) dataType = "image/gif"; else if (path.endsWith(".jpg")) dataType = "image/jpeg"; else if (path.endsWith(".ico")) dataType = "image/x-icon"; else if (path.endsWith(".xml")) dataType = "text/xml"; else if (path.endsWith(".pdf")) dataType = "application/pdf"; else if (path.endsWith(".zip")) dataType = "application/zip"; File dataFile = SD.open(path.c_str()); if (dataFile.isDirectory()) { path += "/index.htm"; dataType = "text/html"; dataFile = SD.open(path.c_str()); } if (!dataFile) return false; if (httpserver.hasArg("download")) dataType = "application/octet-stream"; if (httpserver.streamFile(dataFile, dataType) != dataFile.size()) { DBG_OUTPUT_PORT.println("Sent less data than expected!"); } dataFile.close(); return true; } bool loadStatusPageFromSdCard() { String path="/config/html/index.htm"; DBG_OUTPUT_PORT.println("--> loadFromSdCard() path: "+path); String dataType = "text/plain"; if (path.endsWith("/")) path += "index.htm"; if (path.endsWith(".src")) path = path.substring(0, path.lastIndexOf(".")); else if (path.endsWith(".htm")) dataType = "text/html"; else if (path.endsWith(".css")) dataType = "text/css"; else if (path.endsWith(".js")) dataType = "application/javascript"; else if (path.endsWith(".png")) dataType = "image/png"; else if (path.endsWith(".gif")) dataType = "image/gif"; else if (path.endsWith(".jpg")) dataType = "image/jpeg"; else if (path.endsWith(".ico")) dataType = "image/x-icon"; else if (path.endsWith(".xml")) dataType = "text/xml"; else if (path.endsWith(".pdf")) dataType = "application/pdf"; else if (path.endsWith(".zip")) dataType = "application/zip"; File dataFile = SD.open(path.c_str()); if (dataFile.isDirectory()) { path += "/index.htm"; dataType = "text/html"; dataFile = SD.open(path.c_str()); } if (!dataFile) return false; if (statusserver.hasArg("download")) dataType = "application/octet-stream"; if (statusserver.streamFile(dataFile, dataType) != dataFile.size()) { DBG_OUTPUT_PORT.println("Sent less data than expected!"); } dataFile.close(); return true; } void showStat() { StaticJsonBuffer<800> jsonBuffer; JsonObject& serverStatus = jsonBuffer.createObject(); //Chip serverStatus["elapsedTime"] = millis(); serverStatus["sdkVersion"] = ESP.getSdkVersion(); serverStatus["coreVersion"] = ESP.getCoreVersion(); serverStatus["cpuFreqMHz"] = ESP.getCpuFreqMHz(); serverStatus["chipId"] = String(ESP.getChipId(), HEX); serverStatus["freeHeap"] = ESP.getFreeHeap(); serverStatus["flashChipSize"] = ESP.getFlashChipSize(); serverStatus["flashChipRealSize"] = ESP.getFlashChipRealSize(); serverStatus["flashChipSpeed"] = ESP.getFlashChipSpeed(); serverStatus["voltage"] = ESP.getVcc(); String mLocalIp = WiFi.localIP().toString(); String mSubnetMask = WiFi.subnetMask().toString(); String mGateway = WiFi.gatewayIP().toString(); String mMacAddress = WiFi.macAddress().c_str(); //Wireless serverStatus["ssid"] = ssid; serverStatus["signalStrength"] = WiFi.RSSI(); serverStatus["channel"] = WiFi.channel(); serverStatus["localIP"] = mLocalIp; serverStatus["subnetMask"] = mSubnetMask; serverStatus["gatewayIP"] = mGateway; serverStatus["macAddress"] = mMacAddress; String response; serverStatus.prettyPrintTo(response); statusserver.send(200, "text/plain", response); } void handleNotFoundHTTP() { String str_uri=httpserver.uri(); DBG_OUTPUT_PORT.println("handlenotFoundHTTP() path: "+str_uri); if (hasSD && loadFromSdCard(str_uri)) return; String msg = "<h1>404 Not found</h1><p>The requested URL was not found on this server</p>"; httpserver.send(404, "text/html", msg); DBG_OUTPUT_PORT.print(msg); } void handleNotFoundStatus() { String str_uri=statusserver.uri(); DBG_OUTPUT_PORT.println("handlenotFoundStatus() path: "+str_uri); if ( loadStatusPageFromSdCard()) return; String msg = "<h1>404 Not found</h1><p>The requested URL was not found on this server</p>"; statusserver.send(404, "text/html", msg); DBG_OUTPUT_PORT.print(msg); } void setup(void) { DBG_OUTPUT_PORT.begin(115200); DBG_OUTPUT_PORT.setDebugOutput(true); DBG_OUTPUT_PORT.print("\n"); WiFi.begin(ssid, password); DBG_OUTPUT_PORT.print("Connecting to "); DBG_OUTPUT_PORT.println(ssid); // Wait for connection uint8_t i = 0; while (WiFi.status() != WL_CONNECTED && i++ < 20) {//wait 10 seconds delay(500); } if (i == 21) { DBG_OUTPUT_PORT.print("Could not connect to"); DBG_OUTPUT_PORT.println(ssid); while (1) delay(500); } DBG_OUTPUT_PORT.print("Connected! IP address: "); DBG_OUTPUT_PORT.println(WiFi.localIP()); if (MDNS.begin(host)) { MDNS.addService("http", "tcp", 80); DBG_OUTPUT_PORT.println("MDNS responder started"); DBG_OUTPUT_PORT.print("You can now connect to http://"); DBG_OUTPUT_PORT.print(host); DBG_OUTPUT_PORT.println(".local"); } statusserver.on("/server-status", showStat); statusserver.onNotFound(handleNotFoundStatus); httpserver.onNotFound(handleNotFoundHTTP); statusserver.begin(); httpserver.begin(); DBG_OUTPUT_PORT.println("HTTP server started"); if (SD.begin(SD_CS_PIN, SD_SCK_MHZ(16))) { DBG_OUTPUT_PORT.println("SD Card initialized."); hasSD = true; }else{ SD.initErrorHalt(); } } void loop(void) { httpserver.handleClient(); statusserver.handleClient(); }
[ "jjanos512@gmail.com" ]
jjanos512@gmail.com
33880da0f1131f08db37b4c2619bf67b62173e9d
c459ada4ee8a006f244757d9b14eaccc2f897c4f
/src/filesystem/write_ahead_log.h
2b177dd4c89551850f6896c812c362e8eebd69a4
[ "Apache-2.0" ]
permissive
rrozestw/smf
56133b24aab55847d53578dfbb186074c06e538f
1dafa1ed529134fd81e504129356cb252694a80f
refs/heads/master
2021-04-28T11:14:12.385041
2018-02-16T04:08:11
2018-02-16T23:46:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,098
h
// Copyright (c) 2016 Alexander Gallego. All rights reserved. // #pragma once // std #include <memory> #include <ostream> #include <utility> // seastar #include <core/distributed.hh> #include <core/future.hh> #include <core/sstring.hh> // smf #include "filesystem/wal_opts.h" #include "filesystem/wal_requests.h" #include "filesystem/wal_topics_manager.h" #include "platform/macros.h" namespace smf { /// brief - write ahead log class write_ahead_log { public: explicit write_ahead_log(wal_opts opt); /// \brief returns starting offset off a successful write seastar::future<seastar::lw_shared_ptr<wal_write_reply>> append( wal_write_request r); seastar::future<seastar::lw_shared_ptr<wal_read_reply>> get( wal_read_request r); // \brief filesystem monitoring seastar::future<> open(); seastar::future<> close(); // support seastar shardable seastar::future<> stop() { return close(); } ~write_ahead_log() = default; SMF_DISALLOW_COPY_AND_ASSIGN(write_ahead_log); const wal_opts opts; private: smf::wal_topics_manager tm_; }; } // namespace smf
[ "gallego.alexx@gmail.com" ]
gallego.alexx@gmail.com
4c4f2db6356e0788213e34cd82c563103a48a03d
b26aa47f533073a31a82a7a6486c8f25e21c335a
/TitanCore/src/TiChunkTerrainSection.cpp
cc47d7de5f19ef6afed5e77383f448eea0554a51
[]
no_license
cty41/Titan
a15393004590373de8c3052eff7cad05cb271d81
b85d3ca0f417047de8a1b92cec35715da06a171d
refs/heads/master
2021-01-10T20:47:18.198284
2011-12-22T01:44:31
2011-12-22T01:44:31
1,260,510
1
2
null
null
null
null
UTF-8
C++
false
false
10,224
cpp
#include "TitanStableHeader.h" #include "TiChunkTerrainSection.h" #include "TiChunkTerrain.h" #include "TiHardwareBufferMgr.h" #include "TiRenderQueue.h" #include "TiLogMgr.h" namespace Titan { #define LEVEL_SIDE_LENGTH(i) (1<<i) #define LEVEL_COUNT(i) (LEVEL_SIDE_LENGTH(i)*LEVEL_SIDE_LENGTH(i)) #define SKIRT_HEIGHT 50.0f ChunkTerrainSection::ChunkTerrainSection() :BaseTerrainSection() { } //-------------------------------------------------------------------------------// ChunkTerrainSection::~ChunkTerrainSection() { for(uint i = 0; i < CHUNK_MAX_LOD; ++i) { delete [] mErrorMerticTree[i]; } } //-------------------------------------------------------------------------------// void ChunkTerrainSection::create(BaseTerrain* creator, uint16 sectorX, uint16 sectorZ, uint16 heightMapX, uint16 heightMapZ, uint16 xVerts, uint16 zVerts, const Rect2D& worldRect) { BaseTerrainSection::create(creator, sectorX, sectorZ, heightMapX, heightMapZ, xVerts, zVerts, worldRect); ChunkTerrain* pChunkTerrain = static_cast<ChunkTerrain*>(creator); mTotalLevels = pChunkTerrain->getDetailLevels(); for(uint i = 0; i < CHUNK_MAX_LOD; ++i) { mErrorMerticTree[i] = new float[LEVEL_COUNT(i)]; } // build the errorMetric trees _buildErrorMetricTree(); } //-------------------------------------------------------------------------------// void ChunkTerrainSection::_updateRenderQueue(RenderQueue* queue, Camera* cam) { if(cam->isVisible(mSectionBound)) { TerrainSectionRendVec::iterator it = mTerrainSectionRendVec.begin(), itend = mTerrainSectionRendVec.end(); while (it != itend) { TITAN_DELETE (*it++); } mTerrainSectionRendVec.clear(); _calcLod(cam); //if(mTerrainSectionRend) TerrainSectionRendVec::iterator it2 = mTerrainSectionRendVec.begin(), itend2 = mTerrainSectionRendVec.end(); for(; it2 != itend2; ++it2) queue->addRenderable((*it2)); } } //-------------------------------------------------------------------------------// void ChunkTerrainSection::_buildErrorMetricTree() { // the sector shift tells us how large our // root node is in terms of vertices int shift = mCreator->getSectorShift(); int stride = (1 << shift) + 1; // this information is used to setup our initial // step size and vertex count information int stepSize = stride >> CHUNK_MIN_TESSLLATION_SHIFT; int vertCount = (1 << CHUNK_MIN_TESSLLATION_SHIFT) + 1; // we can now step through the levels // of detail and determine an error // metric for each node of the quad // tree. This data is stored in the // error metric tree for later use for(int i = mTotalLevels - 1; i >= 0; --i) { int localStep = stepSize >> i; int xSpan = (vertCount - 1) * localStep; int zSpan = (vertCount - 1) * localStep; int side_count = LEVEL_SIDE_LENGTH(i); for(int z = 0; z < side_count; ++z) { for(int x = 0; x < side_count; ++x) { // compute the local errorMetric. // m_heightMapX and m_heightMapZ // are the pixel location in the // height map for this section float errorMetric = mCreator->computeErrorMetricOfGrid( vertCount, vertCount, localStep - 1, localStep - 1, mHeightMapX + (x * xSpan), mHeightMapZ + (z * zSpan)); if(i + 1 < mTotalLevels) { int nextLevel = i + 1; int nX = x << 1; int nZ = z << 1; int dim = side_count << 1; errorMetric = maximum( errorMetric, mErrorMerticTree[nextLevel][(nZ*dim)+nX]); errorMetric = maximum( errorMetric, mErrorMerticTree[nextLevel][(nZ*dim)+nX+1]); errorMetric = maximum( errorMetric, mErrorMerticTree[nextLevel][((nZ+1)*dim)+nX]); errorMetric = maximum( errorMetric, mErrorMerticTree[nextLevel][((nZ+1)*dim)+nX+1]); } mErrorMerticTree[i][(z*side_count)+x] = errorMetric; } } } } //-------------------------------------------------------------------------------// void ChunkTerrainSection::_buildVertexBuffer() { mSectionBound.getMinimum().y = MAX_REAL32; mSectionBound.getMaximum().y = MIN_REAL32; uint32 pageSize = mXVerts * mZVerts; uint32 bufferSize = pageSize << 1; BaseTerrain::SectorVertex* pVerts = new BaseTerrain::SectorVertex[bufferSize]; for (uint16 z = 0; z < mZVerts; ++z) { for (uint16 x = 0; x < mXVerts; ++x) { float height = mCreator->readWorldHeight( mHeightMapX + x, mHeightMapZ + z); #if 0 pVerts[(z * mXVerts) + x].normal = mCreator->readWorldNormal( mHeightMapX + x, mHeightMapZ + z); #endif uint vertIndex = (z * mXVerts) + x; pVerts[vertIndex].height = height; height -= SKIRT_HEIGHT; pVerts[vertIndex + pageSize].height = height; mSectionBound.getMinimum().y = minimum(mSectionBound.getMinimum().y, height); mSectionBound.getMaximum().y = maximum(mSectionBound.getMaximum().y, height); } } mSectorVerts = HardwareBufferMgr::getSingletonPtr()->createVertexBuffer(sizeof(BaseTerrain::SectorVertex), bufferSize, HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY, false); mSectorVerts->writeData(0, bufferSize * sizeof(BaseTerrain::SectorVertex), (void*)pVerts); delete [] pVerts; mVertexBufferBinding = HardwareBufferMgr::getSingletonPtr()->createVertexBufferBinding(); mVertexBufferBinding->setBinding(0, mCreator->getHorzVertexData()); mVertexBufferBinding->setBinding(1, mSectorVerts); } //-------------------------------------------------------------------------------// void ChunkTerrainSection::_buildRenderData(RenderData* rend) { } //-------------------------------------------------------------------------------// void ChunkTerrainSection::_calcLod(Camera* cam) { // compute a 2d point for each corner of the section Vector2 corner0(mSectionBound.getMinimum().x, mSectionBound.getMinimum().z); Vector2 corner1(mSectionBound.getMinimum().x, mSectionBound.getMaximum().z); Vector2 corner2(mSectionBound.getMaximum().x, mSectionBound.getMaximum().z); Vector2 corner3(mSectionBound.getMaximum().x, mSectionBound.getMinimum().z); Vector2 viewPoint= Vector2(cam->getPosition().x, cam->getPosition().z); // compute view distance to our 4 corners float distance0 = viewPoint.distance(corner0); float distance1 = viewPoint.distance(corner1); float distance2 = viewPoint.distance(corner2); float distance3 = viewPoint.distance(corner3); _recursiveTessellate(distance0, distance1, distance2, distance3, 0, 0, 0, mCreator->getLodErrorScale(), mCreator->getRatioLimit()); } //-------------------------------------------------------------------------------// void ChunkTerrainSection::_recursiveTessellate(float distA, float distB, float distC, float distD, int level, int levelX, int levelZ, float vScale, float vLimit) { bool split = false; // can we attempt to split? if (level+1 < mTotalLevels) { int index = (levelZ*LEVEL_SIDE_LENGTH(level))+levelX; float errorMetric = mErrorMerticTree[level][index]; // find the shortest distance float dist = minimum(distA, distB); dist = minimum(dist, distC); dist = minimum(dist, distD); // find the ratio of errorMetric over distance float vRatio = (errorMetric*vScale)/(dist+0.0001f); // if we exceed the ratio limit, split if (vRatio > vLimit) { int nextLevel = level+1; int startX = levelX<<1; int startZ = levelZ<<1; // compute midpoint distances float midAB = (distA + distB)*0.5f; float midBC = (distB + distC)*0.5f; float midCD = (distC + distD)*0.5f; float midDA = (distD + distA)*0.5f; float midQuad = (distA + distC)*0.5f; // recurse through the four children _recursiveTessellate( distA, midAB, midQuad, midDA, nextLevel, startX, startZ, vScale, vLimit); _recursiveTessellate( midAB, distB, midBC, midQuad, nextLevel, startX, startZ+1, vScale, vLimit); _recursiveTessellate( midBC, distC, midCD, midQuad, nextLevel, startX+1, startZ+1, vScale, vLimit); _recursiveTessellate( midAB, midQuad, midCD, distD, nextLevel, startX+1, startZ, vScale, vLimit); // remember that we split split = true; } } // did we split? if (!split) { // add ourselves to the renderable list uint8 lodShift = 5 - level; uint8 offsetX = levelX << lodShift; uint8 offsetZ = levelZ << lodShift; uint16 vertexStride = (1 << mCreator->getSectorShift()) + 1; uint16 rendBaseVertex = (offsetZ * vertexStride) + offsetX; #if 1 ChunkTerrain* cTerrain = static_cast<ChunkTerrain*>(mCreator); TerrainSectionRend* chunkRend = TITAN_NEW TerrainSectionRend(this); chunkRend->setSectionPos(getSectionPos()); int vertexCount = mCreator->getSectorVertex() * mCreator->getSectorVertex(); RenderData* rend; rend = chunkRend->getRenderData(); rend->operationType = OT_TRIANGLE_STRIP; rend->vertexData = TITAN_NEW VertexData(mCreator->getVertexDecl(),mVertexBufferBinding); rend->vertexData->vertexStart = rendBaseVertex; rend->vertexData->vertexCount = vertexCount; rend->useIndex = true; rend->indexData = TITAN_NEW IndexData(); rend->indexData->indexBuffer = cTerrain->getLodIndexBuffer(0, level); rend->indexData->indexStart = 0; rend->indexData->indexCount = rend->indexData->indexBuffer->getNumIndexes(); mTerrainSectionRendVec.push_back(chunkRend); RenderData* rend2; TerrainSectionRend* skirtRend = TITAN_NEW TerrainSectionRend(this); skirtRend->setSectionPos(getSectionPos()); rend2 = skirtRend->getRenderData(); rend2->operationType = OT_TRIANGLE_STRIP; rend2->vertexData = TITAN_NEW VertexData(mCreator->getVertexDecl(),mVertexBufferBinding); rend2->vertexData->vertexStart = rendBaseVertex; rend2->vertexData->vertexCount = vertexCount; rend2->useIndex = true; rend2->indexData = TITAN_NEW IndexData(); rend2->indexData->indexBuffer = cTerrain->getLodIndexBuffer(1, level); rend2->indexData->indexStart = 0; rend2->indexData->indexCount = rend2->indexData->indexBuffer->getNumIndexes(); mTerrainSectionRendVec.push_back(skirtRend); #endif } } }
[ "ctyFranky@gmail.com" ]
ctyFranky@gmail.com
06d245d09d101526d96f9f69effed3ba63a5a588
1d56c831c9d962691461ca7416bd19a6f0a862a9
/nowcoder/nowcoder/sword_to_offer.cpp
389ae895bbe8d8fe1923e995d6dde3b1d89ba172
[]
no_license
zhjc/FirstProject
54aac9d1968fe83238c6b2dde74225d7b06d268f
671ac1b803157afef9dc914752cd19f78b2b50d0
refs/heads/master
2021-01-22T11:47:22.707588
2017-12-25T11:51:53
2017-12-25T11:51:53
38,825,770
0
0
null
null
null
null
GB18030
C++
false
false
15,344
cpp
#include <iostream> #include <sstream> #include <fstream> #include <algorithm> #include <numeric> #include <vector> #include <map> #include <set> #include <queue> #include <stack> #include <deque> using namespace std; struct TreeLinkNode { int val; struct TreeLinkNode *left; struct TreeLinkNode *right; struct TreeLinkNode *next; TreeLinkNode(int x) :val(x), left(NULL), right(NULL), next(NULL) { } }; struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) { } }; struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) { } }; bool cmp_find(vector<int>& a, vector<int>& b) { return a[0] < b[0]; } class OfferSolution { public: bool IsContinuous(vector<int> numbers) { if (numbers.size() != 5)return false; sort(numbers.begin(), numbers.end()); int numofzero = 0; int interval = 0; for (int i = 0; i < numbers.size() - 1; ++i) { if (numbers[i] == 0) { numofzero++; continue; } if (numbers[i] == numbers[i + 1]) { return false; } interval += numbers[i + 1] - numbers[i] - 1; } if (interval <= numofzero) { return true; } return false; } void FindNumsAppearOnce(vector<int> data, int* num1, int *num2) { sort(data.begin(), data.end()); int seq = 0; for (int i = 0; i < data.size() - 1; i++) { if (data[i] != data[i + 1]) { if (i == 0) { *num1 = data[i]; seq++; } else { if (data[i - 1] != data[i]) { if (i + 1 == data.size() - 1) { *num1 = data[i]; *num2 = data[i + 1]; return; } else { if (seq == 0) { *num1 = data[i]; seq++; } else { *num2 = data[i]; return; } } } else { if (i + 1 == data.size() - 1) { *num2 = data[i + 1]; return; } } } } } } vector<int> multiply(const vector<int>& A) { // violence method vector<int> vecres(A.size()); for (int i = 0; i < A.size(); ++i) { vecres[i] = 1; for (int j = 0; j < A.size(); ++j) { if (i == j) { continue; } vecres[i] *= A[j]; } } return vecres; } vector<vector<int> > Print(TreeNode* pRoot) { vector<vector<int> > vecres; if (pRoot == NULL) { return vecres; } queue<TreeNode*> que; que.push(pRoot); bool even = false; while (!que.empty()) { int quesize = que.size(); vector<int> temp; for (int i = 0; i < quesize; ++i) { TreeNode* cur = que.front(); temp.push_back(cur->val); que.pop(); if (cur->left) { que.push(cur->left); } if (cur->right) { que.push(cur->right); } } if (even) { reverse(temp.begin(), temp.end()); } vecres.push_back(temp); even = !even; } return vecres; } ListNode* deleteDuplication(ListNode* pHead) { ListNode* cur = pHead; if (cur == NULL || pHead->next == NULL) { return cur; } int head_num = -1; if (head_num == pHead->val) { head_num = -2; } ListNode* head_ = new ListNode(head_num); head_->next = pHead; ListNode* p = head_; ListNode* q = head_->next; while (q) { while (q->next && q->val==q->next->val) { q = q->next; } if (p->next != q) { q = q->next; p->next = q; } else { p = q; q = q->next; } } return head_->next; } string ReverseSentence(string str) { string strres, strtmp; for (int i = 0; i < str.size(); ++i) { if (str[i] == ' ') { strres = " " + strtmp + strres; strtmp = ""; } else { strtmp += str[i]; } } if (!strtmp.empty()) { strres = strtmp + strres; } return strres; } vector<vector<int> > FindContinuousSequence(int sum) { vector<vector<int> > vecres; vector<int> temp; int n = 2; while (n <= (sum+1)/2) { int mid = sum / n; // 序列的中位数 // 在该区间内以大小n为窗口滑动并计算窗口内数字总和 for (int i = mid - n / 2; i <= mid; ++i) { if (i <= 0) { continue; } int loc_sum = 0; for (int j = i; j < i + n; ++j) { loc_sum += j; } if (loc_sum == sum) { temp.resize(0); for (int j = i; j < i + n; ++j) { temp.push_back(j); } vecres.push_back(temp); } } n++; } sort(vecres.begin(), vecres.end()); return vecres; } TreeLinkNode* GetNext(TreeLinkNode* pNode) { return NULL; } static string PMN_int2str(int a) { ostringstream os; os << a; return os.str(); } static bool PMN_cmp(int a, int b) { string sa = PMN_int2str(a); string sb = PMN_int2str(b); return sa + sb < sb + sa; } // 33 string PrintMinNumber(vector<int> numbers) { string strres; sort(numbers.begin(), numbers.end(), PMN_cmp); for (size_t i = 0; i < numbers.size(); ++i) { strres += PMN_int2str(numbers[i]); } return strres; } // 34 丑数 bool isUglyNum(int n) { while (n % 2 == 0) { n = n / 2; } while (n % 3 == 0) { n = n / 3; } while (n % 5 == 0) { n = n / 5; } return n == 1 ? true : false; } int Min3(int num1, int num2, int num3) { int aux = num1 < num2 ? num1 : num2; return aux < num3 ? aux : num3; } int GetUglyNumber_Solution(int index) { int ret = 0; vector<int> vecugly({ 1,2,3,4,5 }); if (index < 0) { return -1; } else if (index < 5) { return vecugly[index]; } else { int founded = 5; int t2 = 2; int t3 = 1; int t5 = 1; while (founded < index) { int min_ugly = Min3(vecugly[t2]*2, vecugly[t3]*3, vecugly[t5]*5); vecugly.push_back(min_ugly); while (vecugly[t2]*2 <= vecugly.back()) { t2++; } while (vecugly[t3] * 3 <= vecugly.back()) { t3++; } while (vecugly[t5] * 5 <= vecugly.back()) { t5++; } founded++; } return vecugly[index - 1]; } return ret; } int FirstNotRepeatingChar(string str) { int nums[26 * 2]; int nums_tag[26 * 2] = { 0 }; for (int i = 0; i < str.size(); ++i) { nums_tag[str[i] - 'A']++; nums[str[i] - 'A'] = i; } int temp = INT_MAX; for (int i = 0; i < 26 * 2; ++i) { if (nums_tag[i]==1) { if (nums[i]<temp) { temp = nums[i]; } } } return temp; } bool hasPath(char* matrix, int rows, int cols, char* str) { if (matrix==NULL || rows<=0 || cols<=0) { return false; } bool* tag = new bool[cols * rows](); for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { if (hasPathInternal(matrix, rows, cols, str, tag, i, j)) { return true; } } } return false; } bool hasPathInternal(char* matrix, int rows, int cols, char* str, bool* tag, int curx, int cury) { if (*str == '\0') { return true; } if (cury == cols) { curx++; cury = 0; } if (cury == -1) { curx--; cury = cols - 1; } if (curx<0||curx>=rows) { return false; } if (tag[curx*cols+cury] || *str!=matrix[curx*cols+cury]) { return false; } tag[curx*cols + cury] = true; bool flag = hasPathInternal(matrix, rows, cols, str + 1, tag, curx - 1, cury) || hasPathInternal(matrix, rows, cols, str + 1, tag, curx + 1, cury) || hasPathInternal(matrix, rows, cols, str + 1, tag, curx, cury - 1) || hasPathInternal(matrix, rows, cols, str + 1, tag, curx, cury + 1); tag[curx*cols + cury] = false; return flag; } // 66 int movingCount(int threshold, int rows, int cols) { vector<vector<bool> > vectag(rows); for (int i = 0; i < rows; ++i) { vectag[i].resize(cols, false); } return movingCountInternal(0, 0, threshold, rows, cols, vectag); } int movingCountInternal(int curx, int cury, int threshold, int rows, int cols, vector<vector<bool> >& tag) { if (curx < 0 || curx >= rows || cury<0 || cury >= cols || NumSum(curx) + NumSum(cury)>threshold || tag[curx][cury]) { return 0; } tag[curx][cury] = true; return 1 + movingCountInternal(curx - 1, cury, threshold, rows, cols, tag) + movingCountInternal(curx + 1, cury, threshold, rows, cols, tag) + movingCountInternal(curx, cury - 1, threshold, rows, cols, tag) + movingCountInternal(curx, cury + 1, threshold, rows, cols, tag); } int NumSum(int n) { int res = 0; do { res += n % 10; } while ((n = n / 10) > 0); return res; } // 求逆数对 long long merge(int a[], int aux[], int l, int m, int r) { int i, j; long long count_ = 0; for (i = m + 1; i > l; --i) { aux[i - 1] = a[i - 1]; } for (j = r; j > m; --j) { aux[j] = a[j]; } i = m; j = r; int k = r; while (i>=l && j>m) { if (aux[i]<aux[j]) { a[k--] = aux[j--]; } else { a[k--] = aux[i--]; count_ += j - m; } } while (i>=l) { a[k--] = aux[i--]; } while (j>m) { a[k--] = aux[j--]; } return count_; } long long merge_sort(int a[], int aux[], int l, int r) { if (r <= l) { return 0; } int m = (l + r) / 2; long long num = 0; num += merge_sort(a, aux, l, m); num += merge_sort(a, aux, m + 1, r); num += merge(a, aux, l, m, r); return num; } int InversePairs(vector<int> data) { if (data.empty()) { return 0; } int* cp = new int[data.size()]; long long count_ = merge_sort(&data[0], cp, 0, data.size() - 1); cout << count_ << endl; for (auto i : data) { cout << i << " "; } cout << endl; delete[] cp; return count_ % 1000000007; } // 正则表达式 bool match(char* str, char* pattern) { bool flag = true; return flag; } // 表示数值的字符串 bool isNumeric(char* string) { bool flag = true; return flag; } }; int test_offer() { OfferSolution sol; /*//.65 char* matrix = "abcesfcsadee"; int rows = 3; int cols = 4; char* str = "bcced"; if (sol.hasPath(matrix, rows, cols, str)) { cout << matrix << " has path " << str << endl; } else { cout << matrix << " hasn't path " << str << endl; }*/ /*TreeLinkNode* t8 = new TreeLinkNode(8); TreeLinkNode* t5 = new TreeLinkNode(5); TreeLinkNode* t6 = new TreeLinkNode(6); TreeLinkNode* t7 = new TreeLinkNode(7); TreeLinkNode* t9 = new TreeLinkNode(9); TreeLinkNode* t10 = new TreeLinkNode(10); TreeLinkNode* t11 = new TreeLinkNode(11); t8->left = t6; t8->right = t10; t6->left = t5; t6->right = t7; t10->left = t9; t10->right = t11; sol.GetNext(t8);*/ //sol.FindContinuousSequence(100); /*string str1 = "abcXYZdef"; string str2 = str1.substr(3); string str3 = str1.substr(0, 3); cout << str2+str3 << endl;*/ //string str = "student. an am I"; //cout<< sol.ReverseSentence(str) << endl; //sol.IsContinuous(vector<int>({0,3,1,6,4})); //int num1, num2; //sol.FindNumsAppearOnce(vector<int>({ 4,6,1,1,1,1 }), &num1, &num2); //cout << num1 << " " << num2 << endl; /* ListNode* t1 = new ListNode(1); ListNode* t2 = new ListNode(1); ListNode* t31 = new ListNode(1); ListNode* t32 = new ListNode(1); ListNode* t41 = new ListNode(1); ListNode* t42 = new ListNode(2); ListNode* t5 = new ListNode(5); t1->next = t2; t2->next = t31; t31->next = t32; t32->next = t41; t41->next = t42; t42->next = t5; sol.deleteDuplication(t1);*/ // 33 //vector<int> vecn({ 3,32,321 }); //sol.PrintMinNumber(vecn); // 34 //sol.GetUglyNumber_Solution(7); //sol.FirstNotRepeatingChar("aabDcdedjDejdss"); //sol.InversePairs(vector<int>({ 364,637,341,406,747,995,234,971,571,219,993,407,416,366,315,301,601,650,418,355,460,505,360,965,516,648,727,667,465,849,455,181,486,149,588,233,144,174,557,67,746,550,474,162,268,142,463,221,882,576,604,739,288,569,256,936,275,401,497,82,935,983,583,523,697,478,147,795,380,973,958,115,773,870,259,655,446,863,735,784,3,671,433,630,425,930,64,266,235,187,284,665,874,80,45,848,38,811,267,575 })); //sol.InversePairs(vector<int>({ 1,2,3,4,5,6,7,0 })); //sol.InversePairs(vector<int>({ 7,5,6,4 })); return 0; }
[ "735828661@qq.com" ]
735828661@qq.com
cb00724169f77ccc44d741c13cba85f828da18ac
bfd0cbd908f8f0d2b673dacba9a87fd51684e16f
/MCSS.h
67bee71e7ab209bbca4af0d46e679df70b224d82
[]
no_license
sg47/MovingShadowRemove
cfd75bfd4f0bf32bd147ee6a6cc1733771e06ab6
f1acb8448a83bd56c00330da55556bb488543215
refs/heads/master
2020-12-25T16:14:34.351087
2013-02-21T04:09:18
2013-02-21T04:09:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,975
h
#ifndef __MCSS_H__ #define __MCSS_H__ #include <iostream> #include <string> #include <opencv2/opencv.hpp> using namespace cv; using namespace std; /* some default parameters */ #define MAX_OBJ_NUM 100 #define MIN_OBJ_AREA 200 #define STACK_SIZE 200000 #define MAX_LGC_NUM 900 #define MIN_LGC_AREA 5 #define SMALL_LGC_LABEL 65535 #define LOW_LUMINANCE_RATIO_THRESHOLD 1 #define HIGH_LUMINANCE_RATIO_THRESHOLD 6 #define LOW_RELATIVE_SIZE_THRESHOLD 0.04 #define HIGH_RELATIVE_SIZE_THRESHOLD 1 #define EXTRINSIC_TERMINAL_POINT_WEIGHT_THRESHOLD 0.22 #define ALPHA 0.000321 #define FRAME_WINDOW 60 #define HISTORY 30 #define DEFAULT_MGTHR_FIXED (Vec3f(0.22, 0.22, 0.22)) /* some parameters of the model */ struct MCSS_Param { float threshold1, threshold2; float lambda_low, lambda_high; float tao; float alpha; Vec3f mgThrFixed; bool isMGThrFixed; bool hasFringe; }; /* moving cast shadow suppression */ /* * the class implements the following algorithm: * "Accurate moving cast shadow suppression based on local color constancy detection" * Ariel Amato, Mikhail G. Mozerov, Andrew D. Bagdanov, and Jordi Gonz` lez */ class MCSS { public: MCSS(); /* update the model */ void operator()(Mat current, Mat background, Mat mask, OutputArray output); /* get some current parameters */ MCSS_Param getParameters(); /* set parameters */ void setParameters(MCSS_Param parameters); /* luminance ratio */ Mat lumRatio; /* label each pixel which LGC they belong */ Mat lgcLabel; /* result mask */ Mat dst; private: int nframes; Size frameSize; int frameType; /* the threshold to limit the LGC area */ float threshold1, threshold2; /* needed when calculate the luminance ratio */ float v; /* relative size threshold lambda */ float lambda_low, lambda_high; /* Extrinsic terminal point weight threshold tao */ float tao; /* an argument needed when computing minimum gradient threshold */ float alpha; /* we can use a fixed value or calculate it in each frame */ bool isMGThrFixed; Vec3f mgThrFixed; /* indicate if the narrow bright fringe exist */ bool hasFringe; /* check if each lgc belongs to shadow */ vector<bool> lgcIsShadow; /* sum of each pixel in mean_bg */ vector<Vec3f> mean_average_bg; /* sum of each pixel in variance_bg */ vector<Vec3f> standard_deviation_average_bg; /* Minimum gradient threshold in RGB space */ vector<Vec3f> mgThr; /* mean value in the lgc */ vector<Vec3f> meanLGC; /* terminal pixel weight */ vector<float> tpw; Mat lgcImg; /* label each pixel which object they belong */ Mat objLabel; /* area of each object */ vector<int> objArea; /* area of each LGC */ vector<int> lgcArea; /* record the object index of each lgc */ vector<int> lgcToObj; /* mean value and standard deviation of background * cont, mean, std * */ Mat cont, mean, STD; int getNearestVal(Point pos); }; #endif /*__MCSS_H__*/
[ "nicklhy@gmail.com" ]
nicklhy@gmail.com
d0d2ea283a1c1f0e720996566ed273f04d3e3703
02e541928d0cdac6bce3e5d3e8d8304d3a7357bf
/Codes/p10783-odd_sum.cpp
4fbbebd1bce385bb7dabbeef3a9e96e22d822e42
[]
no_license
israkul9/Uva-Problems-
90063119f6f1441ec6b03c072a517414592f5fc3
282c438cfce62874385305a9f1750d4f81e8c75e
refs/heads/master
2021-07-23T19:34:00.745196
2020-08-04T09:01:29
2020-08-04T09:01:29
201,115,518
0
0
null
null
null
null
UTF-8
C++
false
false
416
cpp
#include<bits/stdc++.h> using namespace std; int main() { int a,b,i=0,j,d,T,temp; scanf("%d",&T); for(j=1; j<=T; j++) { scanf("%d%d",&a,&b); if(a>b){ temp=a; a=b; b=temp; } d=0; for (i=a; i<=b; i++) { if(i%2!=0) d=d+i; } printf("Case %d: %d\n",j,d); } return 0; }
[ "israkul9@gmail.com" ]
israkul9@gmail.com
71fef214b3dcb1edd18e3094d5d3d7a96f0d036a
d12bfeeb222f21d06348337ab93acf4c5be113fe
/lv2/experiment/src/filters.cc
4c0eb5136f2bded01e9c24721fb9f5f86cfd589c
[]
no_license
Sammons/sound-stuff
ca182798891fc0dff67cf68caad6bc388bc40511
b9acb09c0fb0359e5d750f772d3c6850226fd6c1
refs/heads/master
2023-02-04T17:22:16.798038
2020-12-29T06:10:38
2020-12-29T06:10:38
322,953,654
0
0
null
null
null
null
UTF-8
C++
false
false
21,059
cc
#include <math.h> #include <stdio.h> #include "./biquad.cc" struct PassFilterParams { double cutoff_frequency; double steepness; double dryness; double wetness; double sample_rate; double boost_db; }; struct Filter { BiquadTransposeCanonical<double> biquad = BiquadTransposeCanonical<double>(); PassFilterParams params; public: /* From testing the cliff on this is awful, but it does quiet frequencies well above the cutoff */ Filter() { } // low pass filter void configure_lpf1(PassFilterParams &params) { this->params = params; const double theta = 2.0 * M_PI * params.cutoff_frequency / params.sample_rate; const double gamma = cos(theta) / (1.0 + sin(theta)); const double a0 = (1.0 - gamma) / 2.0; const double a1 = (1.0 - gamma) / 2.0; const double a2 = 0.0; const double b1 = -gamma; const double b2 = 0.0; const double c0 = params.wetness; const double d0 = params.dryness; printf("Initialized LPF1 with a0=%f a1=%f a2=%f b1=%f b2=%f c0=%f d0=%f\n", a0, a1, a2, b1, b2, c0, d0); this->biquad.set_params({a0, a1, a2, b1, b2, c0, d0}); } // high pass filter void configure_hpf1(PassFilterParams &params) { this->params = params; const double theta = 2.0 * M_PI * params.cutoff_frequency / params.sample_rate; const double gamma = cos(theta) / (1.0 + sin(theta)); const double a0 = (1.0 + gamma) / 2.0; const double a1 = -((1.0 + gamma) / 2.0); const double a2 = 0.0; const double b1 = -gamma; const double b2 = 0.0; const double c0 = params.wetness; const double d0 = params.dryness; printf("Initialized HPF1 with a0=%f a1=%f a2=%f b1=%f b2=%f c0=%f d0=%f\n", a0, a1, a2, b1, b2, c0, d0); this->biquad.set_params({a0, a1, a2, b1, b2, c0, d0}); } // high pass filter void configure_hpf2(PassFilterParams &params) { this->params = params; const double theta = 2.0 * M_PI * params.cutoff_frequency / params.sample_rate; if (params.steepness <= 0) { params.steepness = 0.707; } const double d = 1.0 / params.steepness; const double beta_numerator = 1.0 - (d / 2.0) * sin(theta); const double beta_denominator = 1.0 + (d / 2.0) * sin(theta); const double beta = 0.5 * (beta_numerator / beta_denominator); const double gamma = (0.5 + beta) * cos(theta); const double alpha = (0.5 + beta + gamma) / 2.0; const double a0 = alpha; const double a1 = -2.0 * alpha; const double a2 = alpha; const double b1 = -2.0 * gamma; const double b2 = 2.0 * beta; const double c0 = params.wetness; const double d0 = params.dryness; printf("Initialized HPF2 with a0=%f a1=%f a2=%f b1=%f b2=%f c0=%f d0=%f\n", a0, a1, a2, b1, b2, c0, d0); this->biquad.set_params({a0, a1, a2, b1, b2, c0, d0}); } // low pass filter void configure_lpf2(PassFilterParams &params) { this->params = params; const double theta = 2.0 * M_PI * params.cutoff_frequency / params.sample_rate; if (params.steepness <= 0) { params.steepness = 0.707; } const double d = 1.0 / params.steepness; const double beta_numerator = 1.0 - (d / 2.0) * sin(theta); const double beta_denominator = 1.0 + (d / 2.0) * sin(theta); const double beta = 0.5 * (beta_numerator / beta_denominator); const double gamma = (0.5 + beta) * cos(theta); const double alpha = (0.5 + beta - gamma) / 2.0; const double a0 = alpha; const double a1 = 2.0 * alpha; const double a2 = alpha; const double b1 = -2.0 * gamma; const double b2 = 2.0 * beta; const double c0 = params.wetness; const double d0 = params.dryness; printf("Initialized LPF2 with a0=%f a1=%f a2=%f b1=%f b2=%f c0=%f d0=%f\n", a0, a1, a2, b1, b2, c0, d0); this->biquad.set_params({a0, a1, a2, b1, b2, c0, d0}); } // band pass filter void configure_bpf2(PassFilterParams &params) { this->params = params; const double theta = M_PI * params.cutoff_frequency / params.sample_rate; const double k = tan(theta); const double ksquared = k * k; if (params.steepness <= 0) { params.steepness = 0.707; } const double delta = ksquared * params.steepness + k + params.steepness; const double a0 = k / delta; const double a1 = 0.0; const double a2 = -k / delta; const double b1 = ((2.0 * params.steepness) * (ksquared - 1.0)) / delta; const double b2 = (ksquared * params.steepness - k + params.steepness) / delta; const double c0 = params.wetness; const double d0 = params.dryness; printf("Initialized BPF2 with a0=%f a1=%f a2=%f b1=%f b2=%f c0=%f d0=%f\n", a0, a1, a2, b1, b2, c0, d0); this->biquad.set_params({a0, a1, a2, b1, b2, c0, d0}); } // band stop filter void configure_bsf2(PassFilterParams &params) { this->params = params; const double theta = M_PI * params.cutoff_frequency / params.sample_rate; const double k = tan(theta); const double ksquared = k * k; if (params.steepness <= 0) { params.steepness = 0.707; } const double delta = ksquared * params.steepness + k + params.steepness; const double a0 = (params.steepness * (ksquared + 1)) / delta; const double a1 = (2.0 * params.steepness * (ksquared - 1)) / delta; const double a2 = (params.steepness * (ksquared + 1)) / delta; const double b1 = (2.0 * params.steepness * (ksquared - 1)) / delta; const double b2 = ((ksquared * params.steepness) - k + params.steepness) / delta; const double c0 = params.wetness; const double d0 = params.dryness; printf("Initialized BSF2 with a0=%f a1=%f a2=%f b1=%f b2=%f c0=%f d0=%f\n", a0, a1, a2, b1, b2, c0, d0); this->biquad.set_params({a0, a1, a2, b1, b2, c0, d0}); } // lpf w/ steepness = 0.707 void configure_butterworth_lpf2(PassFilterParams &params) { params.steepness = 0.707; // not used but essentially hardcoded const double theta = M_PI * params.cutoff_frequency / params.sample_rate; const double c = 1.0 / (tan(theta)); const double csquared = c * c; const double a0 = 1.0 / (1.0 + M_SQRT2 + csquared); const double a1 = 2.0 * a0; const double a2 = a0; const double b1 = 2.0 * a0 * (1.0 - csquared); const double b2 = a0 * (1 - M_SQRT2 * c + csquared); const double c0 = params.wetness; const double d0 = params.dryness; printf("Initialized Butterworth LPF2 with a0=%f a1=%f a2=%f b1=%f b2=%f c0=%f d0=%f\n", a0, a1, a2, b1, b2, c0, d0); this->biquad.set_params({a0, a1, a2, b1, b2, c0, d0}); } // hpf w/ steepness = 0.707 void configure_butterworth_hpf2(PassFilterParams &params) { params.steepness = 0.707; // not used but essentially hardcoded const double theta = M_PI * params.cutoff_frequency / params.sample_rate; const double c = tan(theta); const double csquared = c * c; const double a0 = 1.0 / (1.0 + M_SQRT2 + csquared); const double a1 = -2.0 * a0; const double a2 = a0; const double b1 = 2.0 * a0 * (csquared - 1.0); const double b2 = a0 * (1 - M_SQRT2 * c + csquared); const double c0 = params.wetness; const double d0 = params.dryness; printf("Initialized Butterworth HPF2 with a0=%f a1=%f a2=%f b1=%f b2=%f c0=%f d0=%f\n", a0, a1, a2, b1, b2, c0, d0); this->biquad.set_params({a0, a1, a2, b1, b2, c0, d0}); } // corner freq has -6db and sums out symmetrically with the hpf, good for crossovers void configure_linkwitz_riley_lpf2(PassFilterParams &params) { const double theta = M_PI * params.cutoff_frequency / params.sample_rate; const double omega = M_PI * params.cutoff_frequency; const double omega_squared = omega * omega; const double k = omega / tan(theta); const double ksquared = k * k; const double delta = ksquared + omega_squared + 2.0 * k * omega; const double a0 = omega_squared / delta; const double a1 = 2.0 * omega_squared / delta; const double a2 = omega_squared / delta; const double b1 = (-2.0 * ksquared + 2.0 * omega_squared) / delta; const double b2 = (-2.0 * k * omega + ksquared + omega_squared) / delta; const double c0 = params.wetness; const double d0 = params.dryness; printf("Initialized Linkwitz Riley LPF2 with a0=%f a1=%f a2=%f b1=%f b2=%f c0=%f d0=%f\n", a0, a1, a2, b1, b2, c0, d0); this->biquad.set_params({a0, a1, a2, b1, b2, c0, d0}); } // corner freq has -6db and sums out symmetrically with the lpf, good for crossovers void configure_linkwitz_riley_hpf2(PassFilterParams &params) { const double theta = M_PI * params.cutoff_frequency / params.sample_rate; const double omega = M_PI * params.cutoff_frequency; const double omega_squared = omega * omega; const double k = omega / tan(theta); const double ksquared = k * k; const double delta = ksquared + omega_squared + 2.0 * k * omega; const double a0 = ksquared / delta; const double a1 = -2.0 * ksquared / delta; const double a2 = ksquared / delta; const double b1 = (-2.0 * ksquared + 2.0 * omega_squared) / delta; const double b2 = (-2.0 * k * omega + ksquared + omega_squared) / delta; const double c0 = params.wetness; const double d0 = params.dryness; printf("Initialized Linkwitz Riley HPF2 with a0=%f a1=%f a2=%f b1=%f b2=%f c0=%f d0=%f\n", a0, a1, a2, b1, b2, c0, d0); this->biquad.set_params({a0, a1, a2, b1, b2, c0, d0}); } // apf applies phase shift like an LPF but no response change void configure_apf1(PassFilterParams &params) { const double theta = (M_PI * params.cutoff_frequency / params.sample_rate); const double alpha = (tan(theta) - 1.0) / (tan(theta) + 1); const double a0 = alpha; const double a1 = 1.0; const double a2 = 0.0; const double b1 = alpha; const double b2 = 0.0; const double c0 = params.wetness; const double d0 = params.dryness; printf("Initialized APF1 with a0=%f a1=%f a2=%f b1=%f b2=%f c0=%f d0=%f\n", a0, a1, a2, b1, b2, c0, d0); this->biquad.set_params({a0, a1, a2, b1, b2, c0, d0}); } // apf applies phase shift like an LPF but no response change void configure_apf2(PassFilterParams &params) { if (params.steepness <= 0) { params.steepness = 0.707; } const double bw = params.cutoff_frequency / params.steepness; const double bw_theta = (M_PI * bw / params.sample_rate); const double alpha = (tan(bw_theta) - 1.0) / (tan(bw_theta) + 1.0); const double beta = -cos((2.0 * M_PI * params.cutoff_frequency) / params.sample_rate); const double a0 = -alpha; const double a1 = beta * (1.0 - alpha); const double a2 = 1.0; const double b1 = a1; const double b2 = a0; const double c0 = params.wetness; const double d0 = params.dryness; printf("Initialized APF2 with a0=%f a1=%f a2=%f b1=%f b2=%f c0=%f d0=%f\n", a0, a1, a2, b1, b2, c0, d0); this->biquad.set_params({a0, a1, a2, b1, b2, c0, d0}); } void configure_low_shelf1(PassFilterParams &params) { const double theta = 2.0 * M_PI * params.cutoff_frequency / params.sample_rate; const double u = pow((double)10.0, params.boost_db / 20.0); // actually accept db const double beta = 4.0 / (1 + u); const double delta = beta * tan(theta / 2.0); const double gamma = (1.0 - delta) / (1.0 + delta); const double a0 = (1.0 - gamma) / 2.0; const double a1 = a0; const double a2 = 0.0; const double b1 = -gamma; const double b2 = 0.0; const double c0 = u - 1.0; const double d0 = 1.0; params.wetness = c0; params.dryness = d0; printf("Initialized Low Shelf1 with a0=%f a1=%f a2=%f b1=%f b2=%f c0=%f d0=%f u=%f\n", a0, a1, a2, b1, b2, c0, d0, u); this->biquad.set_params({a0, a1, a2, b1, b2, c0, d0}); } void configure_high_shelf1(PassFilterParams &params) { const double theta = 2.0 * M_PI * params.cutoff_frequency / params.sample_rate; const double u = pow((double)10.0, params.boost_db / 20.0); const double beta = (1.0 + u) / 4.0; const double delta = beta * tan(theta / 2.0); const double gamma = (1.0 - delta) / (1.0 + delta); const double a0 = (1.0 + gamma) / 2.0; const double a1 = -a0; const double a2 = 0.0; const double b1 = -gamma; const double b2 = 0.0; const double c0 = u - 1.0; const double d0 = 1.0; params.wetness = c0; params.dryness = d0; printf("Initialized Low Shelf1 with a0=%f a1=%f a2=%f b1=%f b2=%f c0=%f d0=%f\n", a0, a1, a2, b1, b2, c0, d0); this->biquad.set_params({a0, a1, a2, b1, b2, c0, d0}); } void configure_non_constant_eq(PassFilterParams &params) { const double theta = 2.0 * M_PI * params.cutoff_frequency / params.sample_rate; const double u = pow((double)10.0, params.boost_db / 20.0); const double epsilon = 4.0 / (1.0 + u); const double beta = 0.5 * ((1.0 - epsilon * tan(theta / (2.0 * params.steepness))) / (1.0 + epsilon * tan(theta / (2.0 * params.steepness)))); const double gamma = (0.5 + beta) * cos(theta); const double a0 = 0.5 - beta; const double a1 = 0.0; const double a2 = -(0.5 - beta); const double b1 = -2.0 * gamma; const double b2 = 2.0 * beta; const double c0 = u - 1.0; const double d0 = 1.0; params.wetness = c0; params.dryness = d0; printf("Initialized Low Shelf1 with a0=%f a1=%f a2=%f b1=%f b2=%f c0=%f d0=%f\n", a0, a1, a2, b1, b2, c0, d0); this->biquad.set_params({a0, a1, a2, b1, b2, c0, d0}); } void configure_constant_eq_boost(PassFilterParams &params) { const double theta = M_PI * params.cutoff_frequency / params.sample_rate; const double k = tan(theta); const double ksquared = k * k; const double v = pow(10, params.boost_db / 20.0); const double d = (1.0) + (1.0 / params.boost_db) * k + ksquared; const double e = (1.0) + (1.0 / (v * params.steepness)) * k + ksquared; const double alpha = 1.0 + (v / params.steepness) * k + ksquared; const double beta = 2.0 * (ksquared - 1.0); const double gamma = 1.0 - (v / params.steepness) * k + ksquared; const double delta = 1.0 - (1.0 / params.steepness) * k + ksquared; const double rho = 1.0 - (1.0 / (params.steepness * v)) * k + ksquared; const double a0 = alpha / d; const double a1 = beta / d; const double a2 = gamma / d; const double b1 = beta / d; const double b2 = delta / d; const double c0 = 1.0; const double d0 = 0.0; params.wetness = c0; params.dryness = d0; printf("Initialized Constant EQ Boost with a0=%f a1=%f a2=%f b1=%f b2=%f c0=%f d0=%f\n", a0, a1, a2, b1, b2, c0, d0); this->biquad.set_params({a0, a1, a2, b1, b2, c0, d0}); } void configure_constant_eq_cut(PassFilterParams &params) { const double theta = M_PI * params.cutoff_frequency / params.sample_rate; const double k = tan(theta); const double ksquared = k * k; const double v = pow(10, params.boost_db / 20.0); const double d = (1.0) + (1.0 / params.boost_db) * k + ksquared; const double e = (1.0) + (1.0 / (v * params.steepness)) * k + ksquared; const double alpha = 1.0 + (v / params.steepness) * k + ksquared; const double beta = 2.0 * (ksquared - 1.0); const double gamma = 1.0 - (v / params.steepness) * k + ksquared; const double delta = 1.0 - (1.0 / params.steepness) * k + ksquared; const double rho = 1.0 - (1.0 / (params.steepness * v)) * k + ksquared; const double a0 = d / e; const double a1 = beta / e; const double a2 = delta / e; const double b1 = a1; const double b2 = rho / e; const double c0 = 1.0; const double d0 = 0.0; params.wetness = c0; params.dryness = d0; printf("Initialized Constant EQ Boost with a0=%f a1=%f a2=%f b1=%f b2=%f c0=%f d0=%f\n", a0, a1, a2, b1, b2, c0, d0); this->biquad.set_params({a0, a1, a2, b1, b2, c0, d0}); } void configure_all_pole1(PassFilterParams &params) { const double theta = 2.0 * M_PI * params.cutoff_frequency / params.sample_rate; const double gamma = 2.0 - cos(theta); const double b1 = sqrt(gamma * gamma - 1.0 - gamma); const double a0 = 1.0 + b1; const double a1 = 0.0; const double a2 = 0.0; const double b2 = 0.0; const double c0 = 1.0; const double d0 = 0.0; params.wetness = c0; params.dryness = d0; printf("Initialized AllPole1 with a0=%f a1=%f a2=%f b1=%f b2=%f c0=%f d0=%f\n", a0, a1, a2, b1, b2, c0, d0); this->biquad.set_params({a0, a1, a2, b1, b2, c0, d0}); } // special MMA MIDI void configure_all_pole2(PassFilterParams &params) { const double theta = 2.0 * M_PI * params.cutoff_frequency / params.sample_rate; const double q = params.steepness; const double resonance = q <= 0.707 ? 0.0 : 20 * log10((q * q) / sqrt(q * q - 0.25)); const double r = (cos(theta) + sin(theta) * sqrt(pow(10.0, resonance / 10.0) - 1.0)) / (pow(10, resonance / 20.0) * sin(theta) + 1.0); const double g = 10.0; const double b1 = -2.0 * r * cos(theta); const double b2 = r * r; const double a0 = g * (1.0 + b1 + b2); const double a1 = 0.0; const double a2 = 0.0; const double c0 = 1.0; const double d0 = 0.0; params.wetness = c0; params.dryness = d0; printf("Initialized AllPole2 with a0=%f a1=%f a2=%f b1=%f b2=%f c0=%f d0=%f\n", a0, a1, a2, b1, b2, c0, d0); this->biquad.set_params({a0, a1, a2, b1, b2, c0, d0}); } double processSample(double xn) { return (this->params.dryness * xn) + (this->params.wetness * this->biquad.process_sample(xn)); } void reset() { this->biquad.reset(); } }; struct TriodeA { private: PassFilterParams hpf1params; PassFilterParams lowshelfparams; Filter hpf1; Filter lowshelf; double saturation; bool invert; double gain; double sample_rate; public: TriodeA() {} void configure(double hpf_fc, double hpf_boost, double lsf_fc, double lsf_boost, double sample_rate, double saturation, bool invert, double gain) { this->saturation = saturation; this->invert = invert; this->gain = gain; this->sample_rate = sample_rate; this->hpf1params.boost_db = hpf_boost; this->hpf1params.sample_rate = sample_rate; this->hpf1params.cutoff_frequency = hpf_fc; this->lowshelfparams.boost_db = lsf_boost; this->lowshelfparams.sample_rate = sample_rate; this->lowshelfparams.cutoff_frequency = hpf_fc; this->hpf1.configure_hpf1(this->hpf1params); this->lowshelf.configure_low_shelf1(this->lowshelfparams); } inline double sgn(double xn) { if (xn < 0) { return -1; } return 1; } inline double waveShape(double xn) { // return (0.5 * xn + abs(xn)) ; // return (xn + tanh(0.9 * xn) / tanh(xn)) / 2; return abs(xn); } void reset() { this->lowshelf.reset(); this->hpf1.reset(); } inline double processSample(double xn) { double output = this->waveShape(xn); if (this->invert) { output *= -1; } // output = (this->hpf1.processSample(output) + this->lowshelf.processSample(output))/2; // output = this->hpf1.processSample(output); return output; } }; struct TubeAPre { TriodeA tubes[6]; double low_shelf = 2050; double triode_low_shelf = 2050; double triode_lsf_boost = -3; double high_shelf = 10000; double high_shelf_gain = -3; double drive = 2; double output_gain = 0.5; Filter lsf; Filter hsf; public: TubeAPre() {} void configure(double sample_rate, double saturation) { this->high_shelf = sample_rate/2; int len = sizeof(tubes) / sizeof(TriodeA); for (int i = 0; i < len; ++i) { tubes[i] = TriodeA(); tubes[i].configure(this->high_shelf, this->high_shelf_gain, this->triode_low_shelf, this->triode_lsf_boost, sample_rate, saturation, true, 1); } PassFilterParams lsf_params; lsf_params.cutoff_frequency = sample_rate; lsf_params.sample_rate = sample_rate; lsf_params.boost_db = 1; lsf_params.steepness = 1.707; this->lsf.configure_linkwitz_riley_lpf2(lsf_params); PassFilterParams hsf_params; hsf_params.cutoff_frequency = sample_rate/2; hsf_params.sample_rate = sample_rate; hsf_params.boost_db = -3; this->hsf.configure_high_shelf1(hsf_params); } inline double processSample(double xn) { double output = xn; int len = sizeof(tubes) / sizeof(TriodeA); for (int i = 0; i < len - 1; ++i) { output = tubes[i].processSample(output * 2); } // output = (this->lsf.processSample(output * 2) + this->hsf.processSample(output * 2)) / 2; // output = this->hsf.processSample(output); // output = this->lsf.processSample(output); output = tubes[len -1].processSample(output); return output; } };
[ "ben@sammons.io" ]
ben@sammons.io
33fad54a582911f9e051b107ff21b041fc138fba
a533d4198ee1237df55c94ee8ae3df4aefdc55bd
/dp/HeadFirstDesignPatterns/c_plusplus/Silver/Interpreter/MiniDuckSimulator/Duck.hpp
9acdd5d4e5c25473dcb46519c2a54d024c20440b
[]
no_license
jufenghua596/book
c15aeb9b96e5fbb2e998286ef50bc5f569fa31a5
8b7d2db6b91268b3dcca39da4b067630768afdb6
refs/heads/master
2021-05-06T16:44:30.339828
2017-12-10T06:57:50
2017-12-10T06:57:50
113,723,089
1
0
null
null
null
null
UTF-8
C++
false
false
1,298
hpp
#ifndef _HFDP_CPP_INTERPRETER_DUCK_HPP_ #define _HFDP_CPP_INTERPRETER_DUCK_HPP_ #include "MiniDuckSimulator.hpp" namespace HeadFirstDesignPatterns { namespace Interpreter { namespace MiniDuckSimulator { class Duck { private: std::auto_ptr< FlyBehavior > _flyBehavior; private: std::auto_ptr< QuackBehavior > _quackBehavior; private: Duck( const Duck& ); // Disable copy constructor private: void operator=( const Duck& ); // Disable assignment operator protected: Duck( FlyBehavior* flyBehavior, QuackBehavior* quackBehavior ) : _flyBehavior( flyBehavior ), _quackBehavior( quackBehavior ) { assert( flyBehavior ); assert( quackBehavior ); } public: virtual ~Duck() = 0 { } public: void setFlyBehavior( FlyBehavior* fb ) { assert( fb ); _flyBehavior = std::auto_ptr< FlyBehavior >( fb ); } public: void setQuackBehavior( QuackBehavior* qb ) { assert( qb ); _quackBehavior = std::auto_ptr< QuackBehavior >( qb ); } public: void fly() const { _flyBehavior->fly(); } public: void quack() const { _quackBehavior->quack(); } public: void swim() const { std::cout << "All ducks float, even decoys!" << std::endl; } public: virtual void display() const = 0; }; } // namespace MiniDuckSimulator } // namespace Interpreter } // namespace HeadFirstDesignPatterns #endif
[ "jufenghua596@163.com" ]
jufenghua596@163.com
195003a3557ae00bd9110e5eebe32e6aba1b3fce
7f4d67bf2d239b580e3ee7ea5e11ebb990ce4a8c
/Framework/Framework/0625/CUI_SkillKeyBinding.cpp
da0715536730a53a44d83220194e42b07c0cf4a9
[]
no_license
batherit/WizardOfLegend
10d64a7785b9fcaa9506d0cc73a37063f78c5240
2b34b3c7d4a43eeb21fab49e00f25b17b99d0aef
refs/heads/master
2023-03-06T10:44:10.610300
2021-02-18T07:26:37
2021-02-18T07:26:37
278,795,613
0
0
null
null
null
null
UHC
C++
false
false
3,000
cpp
#include "stdafx.h" #include "CUI_SkillKeyBinding.h" #include "CBitmapMgr.h" #include "CUI_SkillKeyButton.h" #include "CUI_Image.h" #include "CPlayerWOL.h" #include "CState.h" CUI_SkillKeyBinding::CUI_SkillKeyBinding(CGameWorld & _rGameWorld, CObj * _pPlayer) : CObj(_rGameWorld, WINCX - (UI_SKILLKEY_BINDING_MENU_WIDTH >> 1) - 50 , WINCY >> 1, UI_SKILLKEY_BINDING_MENU_WIDTH, UI_SKILLKEY_BINDING_MENU_HEIGHT), m_pPlayer(_pPlayer) { m_hDCSkillKeyBinding = CBitmapMgr::GetInstance()->GetBitmapMemDC(TEXT("INVENTORY")); SetVisible(false); // 버튼키 바인딩 해줄 것 // 플레이어의 스킬바와 동기화 for (int i = 0; i < SKILL::KEY_END; i++) { // 77 => 슬롯 간 간격 m_pSkillKeyButtons[i] = new CUI_SkillKeyButton(_rGameWorld, this, GetRect().left + 97 + 77 * i, GetRect().top + 112, TO_PLAYER_WOL(_pPlayer), static_cast<SKILL::E_KEY>(i)); } m_pDesc = new CUI_Image(_rGameWorld, GetRect().left + 289, GetRect().top + 677, UI_SKILLKEY_BINDING_DESC_WIDTH, UI_SKILLKEY_BINDING_DESC_HEIGHT); } CUI_SkillKeyBinding::~CUI_SkillKeyBinding() { Release(); } int CUI_SkillKeyBinding::Update(float _fDeltaTime) { if (CKeyMgr::GetInstance()->IsKeyDown(KEY::KEY_TAB)) { if (IsVisible()) { m_pDesc->Clear(); m_iSkillKeyToSwapIndex = 0; SetVisible(false); CSoundMgr::Get_Instance()->PlaySound(TEXT("CLOSE_INVENTORY.mp3"), CSoundMgr::SKILL); } else { SetVisible(true); CSoundMgr::Get_Instance()->PlaySound(TEXT("OPEN_INVENTORY.mp3"), CSoundMgr::SKILL); } } if (!IsVisible()) return 0; // TODO : 버튼 업데이트 for (int i = 0; i < SKILL::KEY_END; i++) { m_pSkillKeyButtons[i]->Update(_fDeltaTime); } return 0; } void CUI_SkillKeyBinding::Render(HDC & _hdc, CCamera2D * _pCamera) { if (IsVisible()) { RECT& rcDrawArea = GetRect(); BitBlt(_hdc, rcDrawArea.left, // 출력 시작좌표 X rcDrawArea.top, // 출력 시작좌표 Y rcDrawArea.right - rcDrawArea.left + 1, rcDrawArea.bottom - rcDrawArea.top + 1, m_hDCSkillKeyBinding, 0, 0, SRCCOPY); //m_iWidth, //m_iHeight, //RGB(255, 0, 255)); for (int i = 0; i < SKILL::KEY_END; i++) { m_pSkillKeyButtons[i]->Render(_hdc, _pCamera); } m_pDesc->Render(_hdc, _pCamera); } } void CUI_SkillKeyBinding::Release(void) { m_pPlayer = nullptr; for (int i = 0; i < SKILL::KEY_END; i++) { DeleteSafe(m_pSkillKeyButtons[i]); } DeleteSafe(m_pDesc); } int CUI_SkillKeyBinding::UpdateSkillInfo(SKILL::E_KEY _eSkillKeyType) { CState<CPlayerWOL>* pSkillState = TO_PLAYER_WOL(m_pPlayer)->GetSkill(_eSkillKeyType); if (pSkillState) { m_pDesc->SetHDC(pSkillState->GetStateHDC(STATE_HDC::STATE_HDC_DESC)); } else { m_pDesc->Clear(); } return 0; } void CUI_SkillKeyBinding::SelectButton(SKILL::E_KEY _eSkillKeyType) { m_eSkillKeyToSwap[m_iSkillKeyToSwapIndex] = _eSkillKeyType; if (++m_iSkillKeyToSwapIndex == 2) { TO_PLAYER_WOL(m_pPlayer)->SwapSkillKey(m_eSkillKeyToSwap[0], m_eSkillKeyToSwap[1]); m_iSkillKeyToSwapIndex = 0; } }
[ "batherit0703@naver.com" ]
batherit0703@naver.com
2751ab44d92e906b8cf8d70e02218cd7800040d4
f22f1c9b9f0265295be7cb83433fcba66b620776
/native/include/src/main/c++/jcpp/native/api/net/NativeSelector.cpp
a01e0d9dd02b61ce60a37bb7579cf18307800c53
[]
no_license
egelor/jcpp-1
63c72c3257b52b37a952344a62fa43882247ba6e
9b5a180b00890d375d2e8a13b74ab5039ac4388c
refs/heads/master
2021-05-09T03:46:22.585245
2015-08-07T16:04:20
2015-08-07T16:04:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
232
cpp
#include "jcpp/native/api/net/NativeSelector.h" namespace jcpp { namespace native { namespace api { namespace net { NativeSelector::NativeSelector() { } NativeSelector::~NativeSelector() { } } } } }
[ "mimi4930" ]
mimi4930
f3e6ed430b0d4a3a50a1cd0dd4a7b504281aea1b
fd8fdf41880f3f67f8e6413c297b5144097b50ad
/trunk/src/server/co_msg_server/executor_thread_processor.h
e48b2408d4c149a5406bf110235521b13b5c6ad4
[]
no_license
liuxuanhai/CGI_Web
c67d4db6a3a4de3714babbd31f095d2285545aac
273343bb06a170ac3086d633435e7bcaaa81e8c5
refs/heads/master
2020-03-18T12:27:40.035442
2016-09-28T11:18:26
2016-09-28T11:18:26
134,727,689
1
1
null
null
null
null
UTF-8
C++
false
false
575
h
#ifndef _SERVER_EXECUTOR_THREAD_PROCESSOR_H_ #define _SERVER_EXECUTOR_THREAD_PROCESSOR_H_ #include "executor_thread_queue.h" #include "util/logger.h" class ExecutorThreadProcessor { public: ExecutorThreadProcessor() { } ~ExecutorThreadProcessor() { } int init(int size,int queue_capacity); int get_size(); ExecutorThreadQueue* get_queue(int n); int send_request(ExecutorThreadRequestElement& request); private: int m_size; int m_queue_capacity; ExecutorThreadQueue* m_queue_arr; DECL_LOGGER(logger); }; #endif
[ "penghuijun6738@163.com" ]
penghuijun6738@163.com
ace145671a87efb8c9c202a98d1d222be5eb10f3
ba6dcd969cca41047e7cba1f84fffc5eb8fb22ad
/src/solutions/55.cpp
7b45469c6077110e46df64f77de69dbc073b7300
[]
no_license
NoNameMing/PATB
730cf259ae7b05b24eef947174435fa26deaee73
a4e4e23c89b6cb738435e94ebdf1ea9287de8114
refs/heads/master
2020-05-31T15:13:39.250764
2019-07-27T01:34:20
2019-07-27T01:34:20
190,351,804
1
0
null
null
null
null
UTF-8
C++
false
false
982
cpp
#include <iostream> #include <algorithm> #include <vector> using namespace std; struct node { string name; int height; }; int cmp(struct node a, struct node b) { return a.height != b.height ? a.height > b.height : a.name < b.name; } int main(){ int n, k, m; cin >> n >> k; vector<node> stu(n); for (int i = 0; i < n; i++) { cin >> stu[i].name >> stu[i].height; } sort(stu.begin(), stu.end(), cmp); int t = 0, row = k; while(row){ if (row == k) m = n - n / k * (k - 1); else m = n / k; vector<string> ans(m); ans[m / 2] = stu[t].name; int j = m / 2 - 1; for (int i = t + 1; i < t + m; i = i + 2) ans[j--] = stu[i].name; j = m / 2 + 1; for (int i = t + 2; i < t + m; i = i + 2) ans[j++] = stu[i].name; cout << ans[0]; for (int i = 1; i < m; i++) cout << " " << ans[i]; cout << endl; t = t + m; row--; } return 0; }
[ "wangxiaoming@wangxiaomingdeMacBook-Air.local" ]
wangxiaoming@wangxiaomingdeMacBook-Air.local
7a95b147e003a6b59551c3da0b6fc10626eb5fdd
948f4e13af6b3014582909cc6d762606f2a43365
/testcases/juliet_test_suite/testcases/CWE195_Signed_to_Unsigned_Conversion_Error/s01/CWE195_Signed_to_Unsigned_Conversion_Error__connect_socket_memmove_84a.cpp
eadf74fd6d98f8fd687c92087f1adc72e87a859b
[]
no_license
junxzm1990/ASAN--
0056a341b8537142e10373c8417f27d7825ad89b
ca96e46422407a55bed4aa551a6ad28ec1eeef4e
refs/heads/master
2022-08-02T15:38:56.286555
2022-06-16T22:19:54
2022-06-16T22:19:54
408,238,453
74
13
null
2022-06-16T22:19:55
2021-09-19T21:14:59
null
UTF-8
C++
false
false
2,493
cpp
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE195_Signed_to_Unsigned_Conversion_Error__connect_socket_memmove_84a.cpp Label Definition File: CWE195_Signed_to_Unsigned_Conversion_Error.label.xml Template File: sources-sink-84a.tmpl.cpp */ /* * @description * CWE: 195 Signed to Unsigned Conversion Error * BadSource: connect_socket Read data using a connect socket (client side) * GoodSource: Positive integer * Sinks: memmove * BadSink : Copy strings using memmove() with the length of data * Flow Variant: 84 Data flow: data passed to class constructor and destructor by declaring the class object on the heap and deleting it after use * * */ #include "std_testcase.h" #include "CWE195_Signed_to_Unsigned_Conversion_Error__connect_socket_memmove_84.h" namespace CWE195_Signed_to_Unsigned_Conversion_Error__connect_socket_memmove_84 { #ifndef OMITBAD void bad() { int data; /* Initialize data */ data = -1; CWE195_Signed_to_Unsigned_Conversion_Error__connect_socket_memmove_84_bad * badObject = new CWE195_Signed_to_Unsigned_Conversion_Error__connect_socket_memmove_84_bad(data); delete badObject; } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ static void goodG2B() { int data; /* Initialize data */ data = -1; CWE195_Signed_to_Unsigned_Conversion_Error__connect_socket_memmove_84_goodG2B * goodG2BObject = new CWE195_Signed_to_Unsigned_Conversion_Error__connect_socket_memmove_84_goodG2B(data); delete goodG2BObject; } void good() { goodG2B(); } #endif /* OMITGOOD */ } /* close namespace */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN using namespace CWE195_Signed_to_Unsigned_Conversion_Error__connect_socket_memmove_84; /* so that we can use good and bad easily */ int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
[ "yzhang0701@gmail.com" ]
yzhang0701@gmail.com
cee6e544552f1b3b352a5b7d6251efc6fe1fb915
3b542298d1046b163f243d360943599f0e426e2a
/deps/v8/src/platform-openbsd.cc
408d4dc0f8487e08a8a4277ad8139f4910b6d4de
[ "BSD-3-Clause", "bzip2-1.0.6", "LicenseRef-scancode-unknown-license-reference", "ISC", "LicenseRef-scancode-openssl", "Apache-2.0", "MIT", "BSD-2-Clause", "Artistic-2.0", "NTP", "Zlib" ]
permissive
jashandeep-sohi/nodejs-qnx
59ad84df742d779bfcbf9f25899d04c8dc57a610
f8aa8a4c29ebc8157965400f98f79c3f39b4b608
refs/heads/master
2022-11-22T01:28:57.252590
2017-10-11T05:26:40
2017-10-11T05:26:40
106,509,655
2
3
NOASSERTION
2022-11-20T17:20:43
2017-10-11T05:29:43
JavaScript
UTF-8
C++
false
false
28,307
cc
// Copyright 2012 the V8 project authors. 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. // Platform specific code for OpenBSD and NetBSD goes here. For the POSIX // comaptible parts the implementation is in platform-posix.cc. #include <pthread.h> #include <semaphore.h> #include <signal.h> #include <sys/time.h> #include <sys/resource.h> #include <sys/syscall.h> #include <sys/types.h> #include <stdlib.h> #include <sys/types.h> // mmap & munmap #include <sys/mman.h> // mmap & munmap #include <sys/stat.h> // open #include <fcntl.h> // open #include <unistd.h> // sysconf #include <execinfo.h> // backtrace, backtrace_symbols #include <strings.h> // index #include <errno.h> #include <stdarg.h> #undef MAP_TYPE #include "v8.h" #include "platform-posix.h" #include "platform.h" #include "v8threads.h" #include "vm-state-inl.h" namespace v8 { namespace internal { // 0 is never a valid thread id on Linux and OpenBSD since tids and pids share a // name space and pid 0 is reserved (see man 2 kill). static const pthread_t kNoThread = (pthread_t) 0; double ceiling(double x) { return ceil(x); } static Mutex* limit_mutex = NULL; static void* GetRandomMmapAddr() { Isolate* isolate = Isolate::UncheckedCurrent(); // Note that the current isolate isn't set up in a call path via // CpuFeatures::Probe. We don't care about randomization in this case because // the code page is immediately freed. if (isolate != NULL) { #ifdef V8_TARGET_ARCH_X64 uint64_t rnd1 = V8::RandomPrivate(isolate); uint64_t rnd2 = V8::RandomPrivate(isolate); uint64_t raw_addr = (rnd1 << 32) ^ rnd2; // Currently available CPUs have 48 bits of virtual addressing. Truncate // the hint address to 46 bits to give the kernel a fighting chance of // fulfilling our placement request. raw_addr &= V8_UINT64_C(0x3ffffffff000); #else uint32_t raw_addr = V8::RandomPrivate(isolate); // The range 0x20000000 - 0x60000000 is relatively unpopulated across a // variety of ASLR modes (PAE kernel, NX compat mode, etc). raw_addr &= 0x3ffff000; raw_addr += 0x20000000; #endif return reinterpret_cast<void*>(raw_addr); } return NULL; } void OS::PostSetUp() { POSIXPostSetUp(); } uint64_t OS::CpuFeaturesImpliedByPlatform() { return 0; } int OS::ActivationFrameAlignment() { // With gcc 4.4 the tree vectorization optimizer can generate code // that requires 16 byte alignment such as movdqa on x86. return 16; } void OS::ReleaseStore(volatile AtomicWord* ptr, AtomicWord value) { __asm__ __volatile__("" : : : "memory"); // An x86 store acts as a release barrier. *ptr = value; } const char* OS::LocalTimezone(double time) { if (isnan(time)) return ""; time_t tv = static_cast<time_t>(floor(time/msPerSecond)); struct tm* t = localtime(&tv); if (NULL == t) return ""; return t->tm_zone; } double OS::LocalTimeOffset() { time_t tv = time(NULL); struct tm* t = localtime(&tv); // tm_gmtoff includes any daylight savings offset, so subtract it. return static_cast<double>(t->tm_gmtoff * msPerSecond - (t->tm_isdst > 0 ? 3600 * msPerSecond : 0)); } // We keep the lowest and highest addresses mapped as a quick way of // determining that pointers are outside the heap (used mostly in assertions // and verification). The estimate is conservative, i.e., not all addresses in // 'allocated' space are actually allocated to our heap. The range is // [lowest, highest), inclusive on the low and and exclusive on the high end. static void* lowest_ever_allocated = reinterpret_cast<void*>(-1); static void* highest_ever_allocated = reinterpret_cast<void*>(0); static void UpdateAllocatedSpaceLimits(void* address, int size) { ASSERT(limit_mutex != NULL); ScopedLock lock(limit_mutex); lowest_ever_allocated = Min(lowest_ever_allocated, address); highest_ever_allocated = Max(highest_ever_allocated, reinterpret_cast<void*>(reinterpret_cast<char*>(address) + size)); } bool OS::IsOutsideAllocatedSpace(void* address) { return address < lowest_ever_allocated || address >= highest_ever_allocated; } size_t OS::AllocateAlignment() { return sysconf(_SC_PAGESIZE); } void* OS::Allocate(const size_t requested, size_t* allocated, bool is_executable) { const size_t msize = RoundUp(requested, AllocateAlignment()); int prot = PROT_READ | PROT_WRITE | (is_executable ? PROT_EXEC : 0); void* addr = GetRandomMmapAddr(); void* mbase = mmap(addr, msize, prot, MAP_PRIVATE | MAP_ANON, -1, 0); if (mbase == MAP_FAILED) { LOG(i::Isolate::Current(), StringEvent("OS::Allocate", "mmap failed")); return NULL; } *allocated = msize; UpdateAllocatedSpaceLimits(mbase, msize); return mbase; } void OS::Free(void* address, const size_t size) { // TODO(1240712): munmap has a return value which is ignored here. int result = munmap(address, size); USE(result); ASSERT(result == 0); } void OS::Sleep(int milliseconds) { unsigned int ms = static_cast<unsigned int>(milliseconds); usleep(1000 * ms); } void OS::Abort() { // Redirect to std abort to signal abnormal program termination. abort(); } void OS::DebugBreak() { asm("int $3"); } class PosixMemoryMappedFile : public OS::MemoryMappedFile { public: PosixMemoryMappedFile(FILE* file, void* memory, int size) : file_(file), memory_(memory), size_(size) { } virtual ~PosixMemoryMappedFile(); virtual void* memory() { return memory_; } virtual int size() { return size_; } private: FILE* file_; void* memory_; int size_; }; OS::MemoryMappedFile* OS::MemoryMappedFile::open(const char* name) { FILE* file = fopen(name, "r+"); if (file == NULL) return NULL; fseek(file, 0, SEEK_END); int size = ftell(file); void* memory = mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, fileno(file), 0); return new PosixMemoryMappedFile(file, memory, size); } OS::MemoryMappedFile* OS::MemoryMappedFile::create(const char* name, int size, void* initial) { FILE* file = fopen(name, "w+"); if (file == NULL) return NULL; int result = fwrite(initial, size, 1, file); if (result < 1) { fclose(file); return NULL; } void* memory = mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, fileno(file), 0); return new PosixMemoryMappedFile(file, memory, size); } PosixMemoryMappedFile::~PosixMemoryMappedFile() { if (memory_) OS::Free(memory_, size_); fclose(file_); } void OS::LogSharedLibraryAddresses() { // This function assumes that the layout of the file is as follows: // hex_start_addr-hex_end_addr rwxp <unused data> [binary_file_name] // If we encounter an unexpected situation we abort scanning further entries. FILE* fp = fopen("/proc/self/maps", "r"); if (fp == NULL) return; // Allocate enough room to be able to store a full file name. const int kLibNameLen = FILENAME_MAX + 1; char* lib_name = reinterpret_cast<char*>(malloc(kLibNameLen)); i::Isolate* isolate = ISOLATE; // This loop will terminate once the scanning hits an EOF. while (true) { uintptr_t start, end; char attr_r, attr_w, attr_x, attr_p; // Parse the addresses and permission bits at the beginning of the line. if (fscanf(fp, "%" V8PRIxPTR "-%" V8PRIxPTR, &start, &end) != 2) break; if (fscanf(fp, " %c%c%c%c", &attr_r, &attr_w, &attr_x, &attr_p) != 4) break; int c; if (attr_r == 'r' && attr_w != 'w' && attr_x == 'x') { // Found a read-only executable entry. Skip characters until we reach // the beginning of the filename or the end of the line. do { c = getc(fp); } while ((c != EOF) && (c != '\n') && (c != '/')); if (c == EOF) break; // EOF: Was unexpected, just exit. // Process the filename if found. if (c == '/') { ungetc(c, fp); // Push the '/' back into the stream to be read below. // Read to the end of the line. Exit if the read fails. if (fgets(lib_name, kLibNameLen, fp) == NULL) break; // Drop the newline character read by fgets. We do not need to check // for a zero-length string because we know that we at least read the // '/' character. lib_name[strlen(lib_name) - 1] = '\0'; } else { // No library name found, just record the raw address range. snprintf(lib_name, kLibNameLen, "%08" V8PRIxPTR "-%08" V8PRIxPTR, start, end); } LOG(isolate, SharedLibraryEvent(lib_name, start, end)); } else { // Entry not describing executable data. Skip to end of line to set up // reading the next entry. do { c = getc(fp); } while ((c != EOF) && (c != '\n')); if (c == EOF) break; } } free(lib_name); fclose(fp); } void OS::SignalCodeMovingGC() { // Support for ll_prof.py. // // The Linux profiler built into the kernel logs all mmap's with // PROT_EXEC so that analysis tools can properly attribute ticks. We // do a mmap with a name known by ll_prof.py and immediately munmap // it. This injects a GC marker into the stream of events generated // by the kernel and allows us to synchronize V8 code log and the // kernel log. int size = sysconf(_SC_PAGESIZE); FILE* f = fopen(FLAG_gc_fake_mmap, "w+"); void* addr = mmap(NULL, size, PROT_READ | PROT_EXEC, MAP_PRIVATE, fileno(f), 0); ASSERT(addr != MAP_FAILED); OS::Free(addr, size); fclose(f); } int OS::StackWalk(Vector<OS::StackFrame> frames) { // backtrace is a glibc extension. int frames_size = frames.length(); ScopedVector<void*> addresses(frames_size); int frames_count = backtrace(addresses.start(), frames_size); char** symbols = backtrace_symbols(addresses.start(), frames_count); if (symbols == NULL) { return kStackWalkError; } for (int i = 0; i < frames_count; i++) { frames[i].address = addresses[i]; // Format a text representation of the frame based on the information // available. SNPrintF(MutableCStrVector(frames[i].text, kStackWalkMaxTextLen), "%s", symbols[i]); // Make sure line termination is in place. frames[i].text[kStackWalkMaxTextLen - 1] = '\0'; } free(symbols); return frames_count; } // Constants used for mmap. static const int kMmapFd = -1; static const int kMmapFdOffset = 0; VirtualMemory::VirtualMemory() : address_(NULL), size_(0) { } VirtualMemory::VirtualMemory(size_t size) { address_ = ReserveRegion(size); size_ = size; } VirtualMemory::VirtualMemory(size_t size, size_t alignment) : address_(NULL), size_(0) { ASSERT(IsAligned(alignment, static_cast<intptr_t>(OS::AllocateAlignment()))); size_t request_size = RoundUp(size + alignment, static_cast<intptr_t>(OS::AllocateAlignment())); void* reservation = mmap(GetRandomMmapAddr(), request_size, PROT_NONE, MAP_PRIVATE | MAP_ANON | MAP_NORESERVE, kMmapFd, kMmapFdOffset); if (reservation == MAP_FAILED) return; Address base = static_cast<Address>(reservation); Address aligned_base = RoundUp(base, alignment); ASSERT_LE(base, aligned_base); // Unmap extra memory reserved before and after the desired block. if (aligned_base != base) { size_t prefix_size = static_cast<size_t>(aligned_base - base); OS::Free(base, prefix_size); request_size -= prefix_size; } size_t aligned_size = RoundUp(size, OS::AllocateAlignment()); ASSERT_LE(aligned_size, request_size); if (aligned_size != request_size) { size_t suffix_size = request_size - aligned_size; OS::Free(aligned_base + aligned_size, suffix_size); request_size -= suffix_size; } ASSERT(aligned_size == request_size); address_ = static_cast<void*>(aligned_base); size_ = aligned_size; } VirtualMemory::~VirtualMemory() { if (IsReserved()) { bool result = ReleaseRegion(address(), size()); ASSERT(result); USE(result); } } bool VirtualMemory::IsReserved() { return address_ != NULL; } void VirtualMemory::Reset() { address_ = NULL; size_ = 0; } bool VirtualMemory::Commit(void* address, size_t size, bool is_executable) { return CommitRegion(address, size, is_executable); } bool VirtualMemory::Uncommit(void* address, size_t size) { return UncommitRegion(address, size); } bool VirtualMemory::Guard(void* address) { OS::Guard(address, OS::CommitPageSize()); return true; } void* VirtualMemory::ReserveRegion(size_t size) { void* result = mmap(GetRandomMmapAddr(), size, PROT_NONE, MAP_PRIVATE | MAP_ANON | MAP_NORESERVE, kMmapFd, kMmapFdOffset); if (result == MAP_FAILED) return NULL; return result; } bool VirtualMemory::CommitRegion(void* base, size_t size, bool is_executable) { int prot = PROT_READ | PROT_WRITE | (is_executable ? PROT_EXEC : 0); if (MAP_FAILED == mmap(base, size, prot, MAP_PRIVATE | MAP_ANON | MAP_FIXED, kMmapFd, kMmapFdOffset)) { return false; } UpdateAllocatedSpaceLimits(base, size); return true; } bool VirtualMemory::UncommitRegion(void* base, size_t size) { return mmap(base, size, PROT_NONE, MAP_PRIVATE | MAP_ANON | MAP_NORESERVE | MAP_FIXED, kMmapFd, kMmapFdOffset) != MAP_FAILED; } bool VirtualMemory::ReleaseRegion(void* base, size_t size) { return munmap(base, size) == 0; } class Thread::PlatformData : public Malloced { public: PlatformData() : thread_(kNoThread) {} pthread_t thread_; // Thread handle for pthread. }; Thread::Thread(const Options& options) : data_(new PlatformData()), stack_size_(options.stack_size()) { set_name(options.name()); } Thread::~Thread() { delete data_; } static void* ThreadEntry(void* arg) { Thread* thread = reinterpret_cast<Thread*>(arg); // This is also initialized by the first argument to pthread_create() but we // don't know which thread will run first (the original thread or the new // one) so we initialize it here too. #ifdef PR_SET_NAME prctl(PR_SET_NAME, reinterpret_cast<unsigned long>(thread->name()), // NOLINT 0, 0, 0); #endif thread->data()->thread_ = pthread_self(); ASSERT(thread->data()->thread_ != kNoThread); thread->Run(); return NULL; } void Thread::set_name(const char* name) { strncpy(name_, name, sizeof(name_)); name_[sizeof(name_) - 1] = '\0'; } void Thread::Start() { pthread_attr_t* attr_ptr = NULL; pthread_attr_t attr; if (stack_size_ > 0) { pthread_attr_init(&attr); pthread_attr_setstacksize(&attr, static_cast<size_t>(stack_size_)); attr_ptr = &attr; } pthread_create(&data_->thread_, attr_ptr, ThreadEntry, this); ASSERT(data_->thread_ != kNoThread); } void Thread::Join() { pthread_join(data_->thread_, NULL); } Thread::LocalStorageKey Thread::CreateThreadLocalKey() { pthread_key_t key; int result = pthread_key_create(&key, NULL); USE(result); ASSERT(result == 0); return static_cast<LocalStorageKey>(key); } void Thread::DeleteThreadLocalKey(LocalStorageKey key) { pthread_key_t pthread_key = static_cast<pthread_key_t>(key); int result = pthread_key_delete(pthread_key); USE(result); ASSERT(result == 0); } void* Thread::GetThreadLocal(LocalStorageKey key) { pthread_key_t pthread_key = static_cast<pthread_key_t>(key); return pthread_getspecific(pthread_key); } void Thread::SetThreadLocal(LocalStorageKey key, void* value) { pthread_key_t pthread_key = static_cast<pthread_key_t>(key); pthread_setspecific(pthread_key, value); } void Thread::YieldCPU() { sched_yield(); } class OpenBSDMutex : public Mutex { public: OpenBSDMutex() { pthread_mutexattr_t attrs; int result = pthread_mutexattr_init(&attrs); ASSERT(result == 0); result = pthread_mutexattr_settype(&attrs, PTHREAD_MUTEX_RECURSIVE); ASSERT(result == 0); result = pthread_mutex_init(&mutex_, &attrs); ASSERT(result == 0); USE(result); } virtual ~OpenBSDMutex() { pthread_mutex_destroy(&mutex_); } virtual int Lock() { int result = pthread_mutex_lock(&mutex_); return result; } virtual int Unlock() { int result = pthread_mutex_unlock(&mutex_); return result; } virtual bool TryLock() { int result = pthread_mutex_trylock(&mutex_); // Return false if the lock is busy and locking failed. if (result == EBUSY) { return false; } ASSERT(result == 0); // Verify no other errors. return true; } private: pthread_mutex_t mutex_; // Pthread mutex for POSIX platforms. }; Mutex* OS::CreateMutex() { return new OpenBSDMutex(); } class OpenBSDSemaphore : public Semaphore { public: explicit OpenBSDSemaphore(int count) { sem_init(&sem_, 0, count); } virtual ~OpenBSDSemaphore() { sem_destroy(&sem_); } virtual void Wait(); virtual bool Wait(int timeout); virtual void Signal() { sem_post(&sem_); } private: sem_t sem_; }; void OpenBSDSemaphore::Wait() { while (true) { int result = sem_wait(&sem_); if (result == 0) return; // Successfully got semaphore. CHECK(result == -1 && errno == EINTR); // Signal caused spurious wakeup. } } #ifndef TIMEVAL_TO_TIMESPEC #define TIMEVAL_TO_TIMESPEC(tv, ts) do { \ (ts)->tv_sec = (tv)->tv_sec; \ (ts)->tv_nsec = (tv)->tv_usec * 1000; \ } while (false) #endif bool OpenBSDSemaphore::Wait(int timeout) { const long kOneSecondMicros = 1000000; // NOLINT // Split timeout into second and nanosecond parts. struct timeval delta; delta.tv_usec = timeout % kOneSecondMicros; delta.tv_sec = timeout / kOneSecondMicros; struct timeval current_time; // Get the current time. if (gettimeofday(&current_time, NULL) == -1) { return false; } // Calculate time for end of timeout. struct timeval end_time; timeradd(&current_time, &delta, &end_time); struct timespec ts; TIMEVAL_TO_TIMESPEC(&end_time, &ts); int to = ts.tv_sec; while (true) { int result = sem_trywait(&sem_); if (result == 0) return true; // Successfully got semaphore. if (!to) return false; // Timeout. CHECK(result == -1 && errno == EINTR); // Signal caused spurious wakeup. usleep(ts.tv_nsec / 1000); to--; } } Semaphore* OS::CreateSemaphore(int count) { return new OpenBSDSemaphore(count); } static pthread_t GetThreadID() { return pthread_self(); } static void ProfilerSignalHandler(int signal, siginfo_t* info, void* context) { USE(info); if (signal != SIGPROF) return; Isolate* isolate = Isolate::UncheckedCurrent(); if (isolate == NULL || !isolate->IsInitialized() || !isolate->IsInUse()) { // We require a fully initialized and entered isolate. return; } if (v8::Locker::IsActive() && !isolate->thread_manager()->IsLockedByCurrentThread()) { return; } Sampler* sampler = isolate->logger()->sampler(); if (sampler == NULL || !sampler->IsActive()) return; TickSample sample_obj; TickSample* sample = CpuProfiler::TickSampleEvent(isolate); if (sample == NULL) sample = &sample_obj; // Extracting the sample from the context is extremely machine dependent. sample->state = isolate->current_vm_state(); ucontext_t* ucontext = reinterpret_cast<ucontext_t*>(context); #ifdef __NetBSD__ mcontext_t& mcontext = ucontext->uc_mcontext; #if V8_HOST_ARCH_IA32 sample->pc = reinterpret_cast<Address>(mcontext.__gregs[_REG_EIP]); sample->sp = reinterpret_cast<Address>(mcontext.__gregs[_REG_ESP]); sample->fp = reinterpret_cast<Address>(mcontext.__gregs[_REG_EBP]); #elif V8_HOST_ARCH_X64 sample->pc = reinterpret_cast<Address>(mcontext.__gregs[_REG_RIP]); sample->sp = reinterpret_cast<Address>(mcontext.__gregs[_REG_RSP]); sample->fp = reinterpret_cast<Address>(mcontext.__gregs[_REG_RBP]); #endif // V8_HOST_ARCH #else // OpenBSD #if V8_HOST_ARCH_IA32 sample->pc = reinterpret_cast<Address>(ucontext->sc_eip); sample->sp = reinterpret_cast<Address>(ucontext->sc_esp); sample->fp = reinterpret_cast<Address>(ucontext->sc_ebp); #elif V8_HOST_ARCH_X64 sample->pc = reinterpret_cast<Address>(ucontext->sc_rip); sample->sp = reinterpret_cast<Address>(ucontext->sc_rsp); sample->fp = reinterpret_cast<Address>(ucontext->sc_rbp); #endif // V8_HOST_ARCH #endif // __NetBSD__ sampler->SampleStack(sample); sampler->Tick(sample); } class Sampler::PlatformData : public Malloced { public: PlatformData() : vm_tid_(GetThreadID()) {} pthread_t vm_tid() const { return vm_tid_; } private: pthread_t vm_tid_; }; class SignalSender : public Thread { public: enum SleepInterval { HALF_INTERVAL, FULL_INTERVAL }; static const int kSignalSenderStackSize = 64 * KB; explicit SignalSender(int interval) : Thread(Thread::Options("SignalSender", kSignalSenderStackSize)), vm_tgid_(getpid()), interval_(interval) {} static void SetUp() { if (!mutex_) mutex_ = OS::CreateMutex(); } static void TearDown() { delete mutex_; } static void InstallSignalHandler() { struct sigaction sa; sa.sa_sigaction = ProfilerSignalHandler; sigemptyset(&sa.sa_mask); sa.sa_flags = SA_RESTART | SA_SIGINFO; signal_handler_installed_ = (sigaction(SIGPROF, &sa, &old_signal_handler_) == 0); } static void RestoreSignalHandler() { if (signal_handler_installed_) { sigaction(SIGPROF, &old_signal_handler_, 0); signal_handler_installed_ = false; } } static void AddActiveSampler(Sampler* sampler) { ScopedLock lock(mutex_); SamplerRegistry::AddActiveSampler(sampler); if (instance_ == NULL) { // Start a thread that will send SIGPROF signal to VM threads, // when CPU profiling will be enabled. instance_ = new SignalSender(sampler->interval()); instance_->Start(); } else { ASSERT(instance_->interval_ == sampler->interval()); } } static void RemoveActiveSampler(Sampler* sampler) { ScopedLock lock(mutex_); SamplerRegistry::RemoveActiveSampler(sampler); if (SamplerRegistry::GetState() == SamplerRegistry::HAS_NO_SAMPLERS) { RuntimeProfiler::StopRuntimeProfilerThreadBeforeShutdown(instance_); delete instance_; instance_ = NULL; RestoreSignalHandler(); } } // Implement Thread::Run(). virtual void Run() { SamplerRegistry::State state; while ((state = SamplerRegistry::GetState()) != SamplerRegistry::HAS_NO_SAMPLERS) { bool cpu_profiling_enabled = (state == SamplerRegistry::HAS_CPU_PROFILING_SAMPLERS); bool runtime_profiler_enabled = RuntimeProfiler::IsEnabled(); if (cpu_profiling_enabled && !signal_handler_installed_) { InstallSignalHandler(); } else if (!cpu_profiling_enabled && signal_handler_installed_) { RestoreSignalHandler(); } // When CPU profiling is enabled both JavaScript and C++ code is // profiled. We must not suspend. if (!cpu_profiling_enabled) { if (rate_limiter_.SuspendIfNecessary()) continue; } if (cpu_profiling_enabled && runtime_profiler_enabled) { if (!SamplerRegistry::IterateActiveSamplers(&DoCpuProfile, this)) { return; } Sleep(HALF_INTERVAL); if (!SamplerRegistry::IterateActiveSamplers(&DoRuntimeProfile, NULL)) { return; } Sleep(HALF_INTERVAL); } else { if (cpu_profiling_enabled) { if (!SamplerRegistry::IterateActiveSamplers(&DoCpuProfile, this)) { return; } } if (runtime_profiler_enabled) { if (!SamplerRegistry::IterateActiveSamplers(&DoRuntimeProfile, NULL)) { return; } } Sleep(FULL_INTERVAL); } } } static void DoCpuProfile(Sampler* sampler, void* raw_sender) { if (!sampler->IsProfiling()) return; SignalSender* sender = reinterpret_cast<SignalSender*>(raw_sender); sender->SendProfilingSignal(sampler->platform_data()->vm_tid()); } static void DoRuntimeProfile(Sampler* sampler, void* ignored) { if (!sampler->isolate()->IsInitialized()) return; sampler->isolate()->runtime_profiler()->NotifyTick(); } void SendProfilingSignal(pthread_t tid) { if (!signal_handler_installed_) return; pthread_kill(tid, SIGPROF); } void Sleep(SleepInterval full_or_half) { // Convert ms to us and subtract 100 us to compensate delays // occuring during signal delivery. useconds_t interval = interval_ * 1000 - 100; if (full_or_half == HALF_INTERVAL) interval /= 2; int result = usleep(interval); #ifdef DEBUG if (result != 0 && errno != EINTR) { fprintf(stderr, "SignalSender usleep error; interval = %u, errno = %d\n", interval, errno); ASSERT(result == 0 || errno == EINTR); } #endif USE(result); } const int vm_tgid_; const int interval_; RuntimeProfilerRateLimiter rate_limiter_; // Protects the process wide state below. static Mutex* mutex_; static SignalSender* instance_; static bool signal_handler_installed_; static struct sigaction old_signal_handler_; private: DISALLOW_COPY_AND_ASSIGN(SignalSender); }; Mutex* SignalSender::mutex_ = NULL; SignalSender* SignalSender::instance_ = NULL; struct sigaction SignalSender::old_signal_handler_; bool SignalSender::signal_handler_installed_ = false; void OS::SetUp() { // Seed the random number generator. We preserve microsecond resolution. uint64_t seed = Ticks() ^ (getpid() << 16); srandom(static_cast<unsigned int>(seed)); limit_mutex = CreateMutex(); SignalSender::SetUp(); } void OS::TearDown() { SignalSender::TearDown(); delete limit_mutex; } Sampler::Sampler(Isolate* isolate, int interval) : isolate_(isolate), interval_(interval), profiling_(false), active_(false), samples_taken_(0) { data_ = new PlatformData; } Sampler::~Sampler() { ASSERT(!IsActive()); delete data_; } void Sampler::Start() { ASSERT(!IsActive()); SetActive(true); SignalSender::AddActiveSampler(this); } void Sampler::Stop() { ASSERT(IsActive()); SignalSender::RemoveActiveSampler(this); SetActive(false); } } } // namespace v8::internal
[ "jashandeep.s.sohi@gmail.com" ]
jashandeep.s.sohi@gmail.com
8fa4e22ff665542ad4d9a4215a33c92bb1b971cd
9c921f55b53d59f72e6a3b7109a85a71e411086d
/Software/workspace/Gyro/src/Robot.cpp
cdaee6f2017010bf3299a9d73cc14b751b887a07
[]
no_license
BenzeneBots/2017FRC
56cc7edfae8a516995d29d613eaad1c979824ab4
315a240c1f0d8ded2694db8cbe435ad493157e4e
refs/heads/master
2021-03-22T04:17:11.017292
2017-03-28T12:23:55
2017-03-28T12:23:55
78,551,535
0
0
null
null
null
null
UTF-8
C++
false
false
2,384
cpp
#include "WPILib.h" /** * This is a sample program to demonstrate how to use a gyro sensor to make a robot drive * straight. This program uses a joystick to drive forwards and backwards while the gyro * is used for direction keeping. * * WARNING: While it may look like a good choice to use for your code if you're inexperienced, * don't. Unless you know what you are doing, complex code will be much more difficult under * this system. Use IterativeRobot or Command-Based instead if you're new. * * */ class Robot: public SampleRobot { const int gyroChannel = 0; // Analog Input Channel const int joystickChannel = 0; // USB number in DriverStation // Channels for motors const int leftMotorChannel = 1; const int rightMotorChannel = 0; const int leftRearMotorChannel = 3; const int rightRearMotorChannel = 2; double angleSetpoint = 0.0; const double pGain = .005; // Proportional turning constant // Gyro calibration constant, may need to be adjusted. // A gyro value of 360 is set to correspond to one full revolution. const double voltsPerDegreePerSecond = .0128; RobotDrive myRobot; AnalogGyro gyro; Joystick joystick; public: Robot() : // Create the drivetrain from 4 CAN Talon SRXs. myRobot( new Jaguar(leftMotorChannel), new Jaguar(leftRearMotorChannel), new Jaguar(rightMotorChannel), new Jaguar(rightRearMotorChannel)), // Assign the gyro and joystick channels. gyro(gyroChannel), joystick(joystickChannel ) {} /** * Runs during autonomous. */ void Autonomous() { } /** * Sets the gyro sensitivity and drives the robot when the joystick is pushed. The * motor speed is set from the joystick while the RobotDrive turning value is * assigned from the error between the setpoint and the gyro angle. */ void OperatorControl() { double turningValue; gyro.SetSensitivity(voltsPerDegreePerSecond); //calibrates gyro values to equal degrees while ( IsOperatorControl() && IsEnabled() ) { turningValue = (angleSetpoint - gyro.GetAngle()) * pGain; SmartDashboard::PutNumber("Gyro Rate", turningValue); if ( joystick.GetY() <= 0 ) { //forwards myRobot.Drive(joystick.GetY(), turningValue); } else { //backwards myRobot.Drive(joystick.GetY(), -turningValue); } } } /** * Runs during test mode. */ void Test() { gyro.Reset(); } }; START_ROBOT_CLASS(Robot)
[ "jim.kemp@ph-elec.com" ]
jim.kemp@ph-elec.com
2a89bb6a11a280083f4a1a05817300daab202cf9
de7e771699065ec21a340ada1060a3cf0bec3091
/analysis/common/src/test/org/apache/lucene/analysis/core/TestStopAnalyzer.h
c961923548fa308eac5c82f935b437917caf66d9
[]
no_license
sraihan73/Lucene-
0d7290bacba05c33b8d5762e0a2a30c1ec8cf110
1fe2b48428dcbd1feb3e10202ec991a5ca0d54f3
refs/heads/master
2020-03-31T07:23:46.505891
2018-12-08T14:57:54
2018-12-08T14:57:54
152,020,180
7
0
null
null
null
null
UTF-8
C++
false
false
2,001
h
#pragma once #include "../../../../../../../../../test-framework/src/java/org/apache/lucene/analysis/BaseTokenStreamTestCase.h" #include "stringhelper.h" #include <any> #include <memory> #include <stdexcept> #include <string> #include <unordered_set> #include <deque> // C++ NOTE: Forward class declarations: #include "core/src/java/org/apache/lucene/analysis/core/StopAnalyzer.h" /* * Licensed to the Syed Mamun Raihan (sraihan.com) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * sraihan.com licenses this file to You under GPLv3 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 * * https://www.gnu.org/licenses/gpl-3.0.en.html * * 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. */ namespace org::apache::lucene::analysis::core { using BaseTokenStreamTestCase = org::apache::lucene::analysis::BaseTokenStreamTestCase; class TestStopAnalyzer : public BaseTokenStreamTestCase { GET_CLASS_NAME(TestStopAnalyzer) private: std::shared_ptr<StopAnalyzer> stop; std::shared_ptr<Set<std::any>> inValidTokens = std::unordered_set<std::any>(); public: void setUp() override; void tearDown() override; virtual void testDefaults() ; virtual void testStopList() ; virtual void testStopListPositions() ; protected: std::shared_ptr<TestStopAnalyzer> shared_from_this() { return std::static_pointer_cast<TestStopAnalyzer>( org.apache.lucene.analysis.BaseTokenStreamTestCase::shared_from_this()); } }; } // #include "core/src/java/org/apache/lucene/analysis/core/
[ "smamunr@fedora.localdomain" ]
smamunr@fedora.localdomain
e39885503122d3f95fb53fb94e885ff2259326b8
d9e197288fea7783119b8adf81dd34e2619d9fb4
/src/pgen/dust_collision.cpp
8228b73288672759c609ceae4a0ed5f09738ae1b
[ "BSD-3-Clause" ]
permissive
ziyanxu/athena-pp_xu
a2204bb216ac2e91e3075c96bdfaaff41b5e81bd
fce21992cc107aa553e83dd76b8d03ae90e990c7
refs/heads/master
2023-03-05T16:06:38.850733
2021-02-10T13:18:13
2021-02-10T13:18:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,722
cpp
//======================================================================================== // Athena++ astrophysical MHD code // Copyright(C) 2014 James M. Stone <jmstone@princeton.edu> and other code contributors // Licensed under the 3-clause BSD License, see LICENSE file for details //======================================================================================== //! \file visc.cpp // iprob = 0 - test viscous shear flow density column in various coordinate systems // iprob = 1 - test viscous spreading of Keplerain ring // C headers // C++ headers #include <algorithm> // min #include <cmath> // sqrt() #include <cstdlib> // srand #include <cstring> // strcmp() #include <fstream> #include <iostream> // endl #include <sstream> // stringstream #include <stdexcept> // runtime_error #include <string> // c_str() // Athena++ headers #include "../athena.hpp" #include "../athena_arrays.hpp" #include "../bvals/bvals.hpp" #include "../coordinates/coordinates.hpp" #include "../eos/eos.hpp" #include "../field/field.hpp" #include "../globals.hpp" #include "../hydro/hydro.hpp" #include "../mesh/mesh.hpp" #include "../parameter_input.hpp" #include "../dustfluids/dustfluids.hpp" //#if NON_BAROTROPIC_EOS //#error "This problem generator requires isothermal equation of state!" //#endif // problem parameters which are useful to make global to this file namespace { Real v0, t0, x0, user_dt, iso_cs, gamma_gas; Real MyTimeStep(MeshBlock *pmb); } // namespace //======================================================================================== //! \fn void Mesh::InitUserMeshData(ParameterInput *pin) // \brief Function to initialize problem-specific data in mesh class. Can also be used // to initialize variables which are global to (and therefore can be passed to) other // functions in this file. Called in Mesh constructor. //======================================================================================== void Mesh::InitUserMeshData(ParameterInput *pin) { // Get parameters for gravitatonal potential of central point mass user_dt = pin->GetOrAddReal("problem", "user_dt", 1e-1); iso_cs = pin->GetOrAddReal("hydro", "iso_sound_speed", 1e-1); gamma_gas = pin->GetReal("hydro","gamma"); EnrollUserTimeStepFunction(MyTimeStep); return; } namespace { Real MyTimeStep(MeshBlock *pmb) { Real min_user_dt = user_dt; return min_user_dt; } } //======================================================================================== //! \fn void MeshBlock::ProblemGenerator(ParameterInput *pin) // \brief Initializes viscous shear flow. //======================================================================================== void MeshBlock::ProblemGenerator(ParameterInput *pin) { //Real v1=0.0, v2=0.0, v3=0.0; //Real d0 = 1.0; // p0=1.0; Real x1, x2, x3; // x2 and x3 are set but unused // Initialize density and momenta in Cartesian grids for (int k=ks; k<=ke; ++k) { for (int j=js; j<=je; ++j) { for (int i=is; i<=ie; ++i) { x1=pcoord->x1v(i); x2=pcoord->x2v(j); x3=pcoord->x3v(k); if (NDUSTFLUIDS == 1){ //Test 1: gas and 1 dust fludis, NDUSTFLUIDS == 1 phydro->u(IDN,k,j,i) = 0.2; phydro->u(IM1,k,j,i) = phydro->u(IDN,k,j,i)*1.0; phydro->u(IM2,k,j,i) = 0.0; phydro->u(IM3,k,j,i) = 0.0; pdustfluids->df_cons(0,k,j,i) = 1.0; pdustfluids->df_cons(1,k,j,i) = pdustfluids->df_cons(0,k,j,i)*2.0; pdustfluids->df_cons(2,k,j,i) = 0.0; pdustfluids->df_cons(3,k,j,i) = 0.0; if (NON_BAROTROPIC_EOS) { phydro->u(IEN,k,j,i) = SQR(iso_cs)*phydro->u(IDN,k,j,i)/(gamma_gas - 1.0); phydro->u(IEN,k,j,i) += 0.5*(SQR(phydro->u(IM1,k,j,i))+SQR(phydro->u(IM2,k,j,i)) + SQR(phydro->u(IM3,k,j,i)))/phydro->u(IDN,k,j,i); } } if (NDUSTFLUIDS == 2) { // Test 2: gas and 2 dust fludis, NDUSTFLUIDS == 2 phydro->u(IDN,k,j,i) = 0.2; phydro->u(IM1,k,j,i) = phydro->u(IDN,k,j,i)*1.0; phydro->u(IM2,k,j,i) = 0.0; phydro->u(IM3,k,j,i) = 0.0; if (NON_BAROTROPIC_EOS) { phydro->u(IEN,k,j,i) = SQR(iso_cs)*phydro->u(IDN,k,j,i)/(gamma_gas - 1.0); phydro->u(IEN,k,j,i) += 0.5*(SQR(phydro->u(IM1,k,j,i))+SQR(phydro->u(IM2,k,j,i)) + SQR(phydro->u(IM3,k,j,i)))/phydro->u(IDN,k,j,i); } pdustfluids->df_cons(0,k,j,i) = 1.0; pdustfluids->df_cons(1,k,j,i) = pdustfluids->df_cons(0,k,j,i)*2.0; pdustfluids->df_cons(2,k,j,i) = 0.0; pdustfluids->df_cons(3,k,j,i) = 0.0; pdustfluids->df_cons(4,k,j,i) = 1.8; pdustfluids->df_cons(5,k,j,i) = pdustfluids->df_cons(4,k,j,i)*3.0; pdustfluids->df_cons(6,k,j,i) = 0.0; pdustfluids->df_cons(7,k,j,i) = 0.0; } if (NDUSTFLUIDS == 5) { // Test 3: gas and 5 dust fludis, NDUSTFLUIDS == 5 phydro->u(IDN,k,j,i) = 1.; phydro->u(IM1,k,j,i) = phydro->u(IDN,k,j,i)*-1.0; phydro->u(IM2,k,j,i) = 0.0; phydro->u(IM3,k,j,i) = 0.0; if (NON_BAROTROPIC_EOS) { phydro->u(IEN,k,j,i) = SQR(iso_cs)*phydro->u(IDN,k,j,i)/(gamma_gas - 1.0); phydro->u(IEN,k,j,i) += 0.5*(SQR(phydro->u(IM1,k,j,i))+SQR(phydro->u(IM2,k,j,i)) + SQR(phydro->u(IM3,k,j,i)))/phydro->u(IDN,k,j,i); } pdustfluids->df_cons(0,k,j,i) = 1.5; pdustfluids->df_cons(1,k,j,i) = pdustfluids->df_cons(0,k,j,i)*2.0; pdustfluids->df_cons(2,k,j,i) = 0.0; pdustfluids->df_cons(3,k,j,i) = 0.0; pdustfluids->df_cons(4,k,j,i) = 2.0; pdustfluids->df_cons(5,k,j,i) = pdustfluids->df_cons(4,k,j,i)*3.1; pdustfluids->df_cons(6,k,j,i) = 0.0; pdustfluids->df_cons(7,k,j,i) = 0.0; pdustfluids->df_cons(8,k,j,i) = 2.5; pdustfluids->df_cons(9,k,j,i) = pdustfluids->df_cons(8,k,j,i)*-2.5; pdustfluids->df_cons(10,k,j,i) = 0.0; pdustfluids->df_cons(11,k,j,i) = 0.0; pdustfluids->df_cons(12,k,j,i) = 3.0; pdustfluids->df_cons(13,k,j,i) = pdustfluids->df_cons(12,k,j,i)*0.5; pdustfluids->df_cons(14,k,j,i) = 0.0; pdustfluids->df_cons(15,k,j,i) = 0.0; pdustfluids->df_cons(16,k,j,i) = 3.5; pdustfluids->df_cons(17,k,j,i) = pdustfluids->df_cons(16,k,j,i)*-4.1; pdustfluids->df_cons(18,k,j,i) = 0.0; pdustfluids->df_cons(19,k,j,i) = 0.0; } } } } return; }
[ "phhuang10@gmail.com" ]
phhuang10@gmail.com
77620456c321be733dca606b65c49bba8b56ba7a
35c368e050ae742f46498827d9e3da18df547d7b
/libs/ofxDOM/src/Types.cpp
39debd3050357ca758bd2ee63164977292f5fe68
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
bakercp/ofxDOM
aebeb166c67eefd028193142110bf9fdd4ed378e
e1d1c134efac592f52cd7339449ce9ff97e84fbb
refs/heads/master
2021-01-22T19:15:26.608947
2019-03-24T21:29:03
2019-03-24T21:29:03
38,726,822
9
3
null
null
null
null
UTF-8
C++
false
false
203
cpp
// // Copyright (c) 2009 Christopher Baker <https://christopherbaker.net> // // SPDX-License-Identifier: MIT // #include "ofx/DOM/Types.h" namespace ofx { namespace DOM { } } // namespace ofx::DOM
[ "me@christopherbaker.net" ]
me@christopherbaker.net
9252f23203b80b937f6ee7f843994bdede11c910
49320de02672514560790299c290951fc92a0185
/uart/UartServer.h
d273d282f693a73b0126e730b932ec28f447517a
[]
no_license
winnereven/antenna_project
8992177922f253b60b4af8ea55ddcfa230bfddaa
970177253fb63547efb3c5bd3675cbfaf70b9b99
refs/heads/master
2020-03-23T10:08:53.400822
2018-11-02T08:11:12
2018-11-02T08:11:12
141,427,833
0
0
null
null
null
null
GB18030
C++
false
false
6,282
h
/** * File name: UartServer.h * Author: Even * Email: 871454583@qq.com * Version: 1.0 * Created on: 2017年8月31日 * Description: UART数据收发 */ #ifndef UARTSERVER_H_ #define UARTSERVER_H_ #include <fcntl.h> #include <sys/ioctl.h> #include "../common.h" #include "../sys/serial.h" #include "../sys/config.h" #include "UartCache.h" #include "../utils/DevUtils.h" #define DEV_UART3 "/dev/ttySP3"//连接FPGA #define DEV_UART1 "/dev/ttySP1"//连接温度模块 #define DEV_UART4 "/dev/ttySP4"//连接电机保护模块 //#include "../socket/SocketServer.h" class UartServer: IOnFindUartListener { public: UartServer(); ~UartServer(); //串口接收线程开启 void Start(); /* * 读串口 */ void GetUartData(int fd , uchar* buf,int* lenofdata); /* * 通过文件描述符发送 */ int UartSendByfd(int fd,uchar* buf,int len); /* *以消息体的方式发送 */ void SendMsg(Msg *msg); /* * 收到消息的分类处理 */ virtual void onFindUartInstruction(int fd, Msg *msg, void *args); /* * 设置消息侦听函数指针 */ void SetGetDownMsgListener(IOnGetDownCmdListener * listener); /* * 发送到FPGA */ void SendtoFPGA(uint8_t dir,int diffdegree,int currentdegree); //FPGA 句柄 int m_fdFPGA; //需要角度改变 bool needToChange; // int m_fdTEMP,m_fdPROT; // int m_bUartEn; private: uint8_t mSendBuf[BUFFER_SIZE]; uint8_t mRecvBuf[BUFFER_SIZE]; int mSendLen; int datalen; UartCache* mUartCache;//数据处理类 IOnGetDownCmdListener *mGetDownCmdListener; uint8_t mSendtoFPGA[17]; // 串口初始化 // void __InitUART(); void __UpstreamProcessor(int fd,Msg *msg, void *args);//上行数据处理 void __DownstreamProcessor(int fd, Msg *msg, void *args);//下行数据处理 }; //inline UartServer::UartServer():mGetDownCmdListener(NULL),mSendtoFPGA({0x24,0x24,0x51,0x0a,0x00,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x0d}) inline UartServer::UartServer() { mSendLen=0; datalen=0; mUartCache = new UartCache(this); mGetDownCmdListener=NULL; mSendtoFPGA={0x24,0x24,0x51,0x0a,0x00,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x0d}; int ret; m_fdFPGA = DevUtils::OpenDev(DEV_UART3, O_RDWR | O_NOCTTY); ret = set_port_attr(m_fdFPGA, UART_BAUD_RATE, UART_DATA_BIT, UART_STOP_BIT, UART_PARITY, UART_VTIME, UART_VMIN); if (ret < 0) { printf("set uartfpga attr failed m_fdFPGA = %d\n",m_fdFPGA); exit(-1); } needToChange = 0; // m_fdTEMP = open(DEV_UART1, O_RDWR | O_NOCTTY); // ret = set_port_attr(m_fdTEMP, UART_BAUD_RATE, UART_DATA_BIT, UART_STOP_BIT, UART_PARITY, // UART_VTIME, UART_VMIN); // if (ret < 0) { // printf("set uarttemp attr failed \n"); // exit(-1); // } // m_fdPROT = open(DEV_UART4, O_RDWR | O_NOCTTY); // ret = set_port_attr(m_fdPROT, UART_BAUD_RATE, UART_DATA_BIT, UART_STOP_BIT, UART_PARITY, // UART_VTIME, UART_VMIN); // if (ret < 0) { // printf("set uartprot attr failed \n"); // exit(-1); // } //TODO 配置为非阻塞模式 // if(fcntl(m_fdFPGA,F_SETFL,FNDELAY) < 0) // printf("fcntl m_fdDEBUG failed\n"); // // if(fcntl(m_fdTEMP,F_SETFL,FNDELAY) < 0) // printf("fcntl m_fdLIGHT1 failed\n"); // // if(fcntl(m_fdPROT,F_SETFL,FNDELAY) < 0) // printf("fcntl m_fdLIGHT2 failed\n"); // printf("UartServer Object created!\n"); } inline UartServer::~UartServer(){ int ret; // ret = close(m_fdPROT); // if (ret) // handle_error_en(ret, DEV_UART1); // ret = close(m_fdTEMP); // if (ret) // handle_error_en(ret, DEV_UART1); ret = close(m_fdFPGA); if (ret) handle_error_en(ret, DEV_UART1); printf("UartServer Object destroyed!\n"); } inline void UartServer::Start() { // while(true) // { this->GetUartData(m_fdFPGA,mRecvBuf,&datalen); mUartCache->MsgPreParse(m_fdFPGA,mRecvBuf, datalen, NULL); // } } inline void UartServer::SendtoFPGA(uint8_t dir,int diffdegree,int currentdegree){ mSendtoFPGA[4]=dir; if(dir<0x04) needToChange = 1; diffdegree *= 10; mSendtoFPGA[8]=diffdegree/256; mSendtoFPGA[9]=diffdegree%256; currentdegree *= 10; mSendtoFPGA[12]=currentdegree/256; mSendtoFPGA[13]=currentdegree%256; this->UartSendByfd(m_fdFPGA,mSendtoFPGA,17); printf("send to FPGA data :"); for(int i =0 ;i<17;i++) { printf("%x ",mSendtoFPGA[i]); } printf("\n"); } //TODO 发送给FPGA inline int UartServer::UartSendByfd(int fd,uchar* buf,int len){ if(fd>0) return write(fd, buf, len); else return -1; } inline void UartServer::GetUartData(int fd, uchar* buf,int* lenofdata) { *lenofdata = read(fd,buf, BUFFER_SIZE); if(*lenofdata > 0) { if(DEBUG_even){ printf("recive FPGA data :"); for(int i =0 ;i<*lenofdata;i++) { printf("%x ",*(buf+i)); } printf("\n"); } } } inline void UartServer::SetGetDownMsgListener(IOnGetDownCmdListener *listener) { this->mGetDownCmdListener = listener; } inline void UartServer::SendMsg(Msg *msg) { this->__UpstreamProcessor(m_fdFPGA,msg, NULL); } inline void UartServer::onFindUartInstruction(int fd, Msg *msg, void *args) { // log("Parse 1 instruction.cmd:%x dataLen:%d isRecv:%d", msg->cmd, msg->dataLen, msg->isRecv); if (msg->isRecv) { this->__DownstreamProcessor(fd, msg, args); } else { // __UpstreamProcessor(fd, msg, args); } } inline void UartServer::__UpstreamProcessor(int fd,Msg *msg, void *args) { uint8_t sdbuf[SOCKET_MSG_DATA_SIZE]; int len = msg->CopyToBuf(sdbuf, 0); int ret; printf("upstream:"); for (int i = 0; i < len; i++) { printf("%x ", sdbuf[i]); } printf("\n"); if(fd<=0) { printf("ERROR: Uart not connect!\n"); return ; } if ((ret = send(fd, sdbuf, len, 0)) == -1) { printf("ERROR: Failed to sent string.\n"); close(fd); exit(1); } printf("OK: Sent %d bytes successful, please enter again.\n", ret); } inline void UartServer::__DownstreamProcessor(int fd, Msg *msg, void *args) { Msg *backMsg = NULL; if (mGetDownCmdListener != NULL) { backMsg = mGetDownCmdListener->onGetDownCmd(msg); if (backMsg != NULL) { mSendLen += backMsg->CopyToBuf(mSendBuf, mSendLen); delete backMsg; } } } #endif
[ "871454583@qq.com" ]
871454583@qq.com
a664f76ac34fabc01df6355aa4e57a291a94620a
fb612297a449fef921a2f018719b1d5bb74c64a4
/09.cpp
030b811811bd24dfd1ad714eb678213a3905db61
[]
no_license
Xochitl96/WSQ
604cb1ef53e2f52635e264928792913f2b829600
2c37eac78f1af29dac6bf180f581269bca76203d
refs/heads/master
2021-01-01T16:49:21.689710
2015-05-07T03:29:51
2015-05-07T03:29:51
31,439,116
0
0
null
null
null
null
UTF-8
C++
false
false
658
cpp
//WSQ09 //TC1017 #include <iostream> #include <cstdlib> using namespace std; long long int factorial(long n) { if(n==0){ return 1; } if(n>0) { long long int fact=1; for (long i=2;i<=n;i++) { cout << fact << endl; fact=fact*i; } return fact; } } int main(){ long long int number; char resp; do{ cout <<"Dame el numero que deseas calcular el factorial" <<endl; cin >> number; cout<< "El factorial es " <<factorial(number) <<endl; cout <<"¿Deseas repetir el calculo del factorial? si='s' o no= 'n' " <<endl; cin >> resp; } while(resp=='s'); cout <<"¡Que tengas un bonito día" <<endl; return 0; }
[ "a01630174@itesm.mx" ]
a01630174@itesm.mx
a60eac7da5e620c7b18403467ab2e044961a7390
97075fd0c390eb2b0af864fff9a18e3d424d5cd3
/audio_player/audio_player.cpp
f861b289b2637720162a61356cdf4d2ecd6954c5
[ "MIT", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
zealotnt/gr-peach-2017-peach-board
2e5a2679365eaffdb6ff331e8253924a0673cfb3
2ad8cebcd9f776502265d65651b212c7e3248038
refs/heads/master
2021-08-26T09:25:53.260335
2017-11-20T08:57:39
2017-11-20T11:31:04
105,298,470
0
0
null
null
null
null
UTF-8
C++
false
false
2,520
cpp
/* * audio_player.c * * Created on: 12.03.2017 * Author: michaelboeckling */ #include <stdlib.h> #include "audio_player.h" #include "spiram_fifo.h" #include "mp3_decoder.h" #include "mbed.h" #include "TLV320_RBSP.h" #include "cProcess.hpp" #include "mStorage.hpp" #include "mWav.hpp" #include "define.h" #include "rtos.h" #include "grHwSetup.h" #include "grUtility.h" #include "Json.h" #include "cJson.h" #include "cNodeManager.h" #include <string> #define TAG "[audio_player] " #define ESP_LOGI(tag, ...) printf(tag); printf(__VA_ARGS__); printf("\r\n"); #define ESP_LOGE(tag, ...) printf(tag); printf(__VA_ARGS__); printf("\r\n"); // #define PRIO_MAD configMAX_PRIORITIES - 2 static player_t *player_instance = NULL; static component_status_t player_status = UNINITIALIZED; static int start_decoder_task(player_t *player) { ESP_LOGI(TAG, "creating decoder task"); Thread mp3DecoderTask(mp3_decoder_task, (void *)player, osPriorityNormal, 8448*32); return 0; } static int t; /* Writes bytes into the FIFO queue, starts decoder task if necessary. */ int audio_stream_consumer(const char *recv_buf, ssize_t bytes_read, void *user_data) { player_t *player = (player_t *)user_data; // don't bother consuming bytes if stopped if(player->command == CMD_STOP) { player->decoder_command = CMD_STOP; player->command = CMD_NONE; return -1; } if (bytes_read > 0) { spiRamFifoWrite(recv_buf, bytes_read); } int bytes_in_buf = spiRamFifoFill(); uint8_t fill_level = (bytes_in_buf * 100) / spiRamFifoLen(); // seems 4k is enough to prevent initial buffer underflow uint8_t min_fill_lvl = player->buffer_pref == BUF_PREF_FAST ? 20 : 90; bool enough_buffer = fill_level > min_fill_lvl; bool early_start = (bytes_in_buf > 1028 && player->media_stream->eof); t = (t + 1) & 255; if (t == 0) { ESP_LOGI(TAG, "Buffer fill %u%%, %d bytes", fill_level, bytes_in_buf); } return 0; } void audio_player_init(player_t *player) { player_instance = player; player_status = INITIALIZED; } void audio_player_destroy() { // renderer_destroy(); player_status = UNINITIALIZED; } void audio_player_start() { // renderer_start(); player_status = RUNNING; } void audio_player_stop() { // renderer_stop(); player_instance->command = CMD_STOP; // player_status = STOPPED; } component_status_t get_player_status() { return player_status; }
[ "tranminhtam.10192@gmail.com" ]
tranminhtam.10192@gmail.com
71b3f1adc8ff8e952926e473b4ccf989a0c5e289
8947812c9c0be1f0bb6c30d1bb225d4d6aafb488
/01_Develop/libXMGraphics/Source/FTGLES/FTVectoriser.h
4340e8c434e58f5b399723ab6933151b220767f7
[ "MIT" ]
permissive
alissastanderwick/OpenKODE-Framework
cbb298974e7464d736a21b760c22721281b9c7ec
d4382d781da7f488a0e7667362a89e8e389468dd
refs/heads/master
2021-10-25T01:33:37.821493
2016-07-12T01:29:35
2016-07-12T01:29:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,833
h
/* * FTGL - OpenGL font library * * Copyright (c) 2001-2004 Henry Maddocks <ftgl@opengl.geek.nz> * Copyright (c) 2008 Sam Hocevar <sam@zoy.org> * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef __FTVectoriser__ #define __FTVectoriser__ #include <FTGL/ftgles.h> #include "FTContour.h" #include "FTList.h" #include "FTVector.h" #ifndef CALLBACK #define CALLBACK #endif /** * FTTesselation captures points that are output by OpenGL's gluTesselator. */ class FTTesselation { public: /** * Default constructor */ FTTesselation(GLenum m) : meshType(m) { pointList.reserve(128); } /** * Destructor */ ~FTTesselation() { pointList.clear(); } /** * Add a point to the mesh. */ void AddPoint(const FTGL_DOUBLE x, const FTGL_DOUBLE y, const FTGL_DOUBLE z) { pointList.push_back(FTPoint(x, y, z)); } /** * The number of points in this mesh */ size_t PointCount() const { return pointList.size(); } /** * */ const FTPoint& Point(unsigned int index) const { return pointList[index]; } /** * Return the OpenGL polygon type. */ GLenum PolygonType() const { return meshType; } private: /** * Points generated by gluTesselator. */ typedef FTVector<FTPoint> PointVector; PointVector pointList; /** * OpenGL primitive type from gluTesselator. */ GLenum meshType; }; /** * FTMesh is a container of FTTesselation's that make up a polygon glyph */ class FTMesh { typedef FTVector<FTTesselation*> TesselationVector; typedef FTList<FTPoint> PointList; public: /** * Default constructor */ FTMesh(); /** * Destructor */ ~FTMesh(); /** * Add a point to the mesh */ void AddPoint(const FTGL_DOUBLE x, const FTGL_DOUBLE y, const FTGL_DOUBLE z); /** * Create a combine point for the gluTesselator */ const FTGL_DOUBLE* Combine(const FTGL_DOUBLE x, const FTGL_DOUBLE y, const FTGL_DOUBLE z); /** * Begin a new polygon */ void Begin(GLenum meshType); /** * End a polygon */ void End(); /** * Record a gluTesselation error */ void Error(GLenum e) { err = e; } /** * The number of tesselations in the mesh */ size_t TesselationCount() const { return tesselationList.size(); } /** * Get a tesselation by index */ const FTTesselation* const Tesselation(size_t index) const; /** * Return the temporary point list. For testing only. */ const PointList& TempPointList() const { return tempPointList; } /** * Get the GL ERROR returned by the glu tesselator */ GLenum Error() const { return err; } private: /** * The current sub mesh that we are constructing. */ FTTesselation* currentTesselation; /** * Holds each sub mesh that comprises this glyph. */ TesselationVector tesselationList; /** * Holds extra points created by gluTesselator. See ftglCombine. */ PointList tempPointList; /** * GL ERROR returned by the glu tesselator */ GLenum err; }; const FTGL_DOUBLE FTGL_FRONT_FACING = 1.0; const FTGL_DOUBLE FTGL_BACK_FACING = -1.0; /** * FTVectoriser class is a helper class that converts font outlines into * point data. * * @see FTExtrudeGlyph * @see FTOutlineGlyph * @see FTPolygonGlyph * @see FTContour * @see FTPoint * */ class FTVectoriser { public: /** * Constructor * * @param glyph The freetype glyph to be processed */ FTVectoriser(const FT_GlyphSlot glyph); /** * Destructor */ virtual ~FTVectoriser(); /** * Build an FTMesh from the vector outline data. * * @param zNormal The direction of the z axis of the normal * for this mesh * FIXME: change the following for a constant * @param outsetType Specify the outset type contour * 0 : Original * 1 : Front * 2 : Back * @param outsetSize Specify the outset size contour */ void MakeMesh(FTGL_DOUBLE zNormal = FTGL_FRONT_FACING, int outsetType = 0, float outsetSize = 0.0f); /** * Get the current mesh. */ const FTMesh* const GetMesh() const { return mesh; } /** * Get the total count of points in this outline * * @return the number of points */ size_t PointCount(); /** * Get the count of contours in this outline * * @return the number of contours */ size_t ContourCount() const { return ftContourCount; } /** * Return a contour at index * * @return the number of contours */ const FTContour* const Contour(size_t index) const; /** * Get the number of points in a specific contour in this outline * * @param c The contour index * @return the number of points in contour[c] */ size_t ContourSize(int c) const { return contourList[c]->PointCount(); } /** * Get the flag for the tesselation rule for this outline * * @return The contour flag */ int ContourFlag() const { return contourFlag; } private: /** * Process the freetype outline data into contours of points * * @param front front outset distance * @param back back outset distance */ void ProcessContours(); /** * The list of contours in the glyph */ FTContour** contourList; /** * A Mesh for tesselations */ FTMesh* mesh; /** * The number of contours reported by Freetype */ short ftContourCount; /** * A flag indicating the tesselation rule for the glyph */ int contourFlag; /** * A Freetype outline */ FT_Outline outline; }; #endif // __FTVectoriser__
[ "mcodegeeks@gmail.com" ]
mcodegeeks@gmail.com
0fea0486d11b4f53fa9f8299f23a51ddfd2be206
229e544ed658046d688e7c50fbc821fc15359eae
/net/Timer.h
17b91f756aa76463f5542aa915efcd0bfedc125f
[]
no_license
zhuting11/tim
22f15e956e88651079a3ecb947d203bfdc4268ef
3bf6c1272a29129749aa4f6296fd4ba5c61b424d
refs/heads/master
2016-09-06T03:46:39.706678
2015-02-06T09:01:00
2015-02-06T09:01:00
29,857,222
0
0
null
null
null
null
UTF-8
C++
false
false
1,335
h
#ifndef TIM_NET_TIMER_H #define TIM_NET_TIMER_H #include <boost/noncopyable.hpp> #include <tim/base/Atomic.h> #include <tim/base/Timestamp.h> #include <tim/net/Callbacks.h> namespace tim { namespace net { /// /// Internal class for timer event. /// class Timer : boost::noncopyable { public: Timer(const TimerCallback& cb, Timestamp when, double interval) : callback_(cb), expiration_(when), interval_(interval), repeat_(interval > 0.0), sequence_(s_numCreated_.incrementAndGet()) { } #ifdef __GXX_EXPERIMENTAL_CXX0X__ Timer(TimerCallback&& cb, Timestamp when, double interval) : callback_(std::move(cb)), expiration_(when), interval_(interval), repeat_(interval > 0.0), sequence_(s_numCreated_.incrementAndGet()) { } #endif void run() const { callback_(); } Timestamp expiration() const { return expiration_; } bool repeat() const { return repeat_; } int64_t sequence() const { return sequence_; } void restart(Timestamp now); static int64_t numCreated() { return s_numCreated_.get(); } private: const TimerCallback callback_; Timestamp expiration_; const double interval_; const bool repeat_; const int64_t sequence_; //static AtomicInt64 s_numCreated_; static AtomicInt32 s_numCreated_; }; } } #endif // TIM_NET_TIMER_H
[ "zt58233721@163.com" ]
zt58233721@163.com
bba3a4a8a046fec257731a4ed8d9935ade9710f8
121fbaaddc9999c0c56deb3f0c9ec32a155c8466
/extern/polymesh/src/polymesh/detail/permutation.hh
9143c0ca894544be9f234ed6641623276513cad7
[ "MIT" ]
permissive
huzjkevin/portal_maze_zgl
6fc9128793eac545473fe15c51f2e15199740b0d
efb32b1c3430f20638c1401095999ecb4d0af5aa
refs/heads/master
2023-06-15T02:56:56.066983
2021-07-08T15:02:30
2021-07-08T15:02:30
384,133,404
0
0
null
null
null
null
UTF-8
C++
false
false
1,773
hh
#pragma once #include <valarray> #include <vector> namespace polymesh { namespace detail { /// Applies a permutation that is given by a remapping /// p[curr_idx] = new_idx /// Calculates the necessary transpositions and calls s(i, j) for each of it template <class Swap> void apply_permutation(std::vector<int> const& p, Swap&& s); /// Returns true if the parameter is actually a permutation bool is_valid_permutation(std::vector<int> const& p); /// Returns a list of transpositions that result in the given remapping /// p[curr_idx] = new_idx std::vector<std::pair<int, int>> transpositions_of(std::vector<int> const& p); /// ======== IMPLEMENTATION ======== inline bool is_valid_permutation(std::vector<int> const& p) { std::vector<int> r(p.size(), -1); for (auto i = 0u; i < p.size(); ++i) { auto pi = p[i]; if (pi < 0 || pi >= (int)p.size()) return false; // out of bound if (r[pi] != -1) return false; // not injective r[pi] = i; } return true; } template <class Swap> void apply_permutation(std::vector<int> const& p, Swap&& s) { auto size = p.size(); std::valarray<bool> visited(false, size); for (auto pi = 0u; pi < size; ++pi) { auto i = pi; if (visited[i]) continue; visited[i] = true; i = p[i]; while (!visited[i]) { // mark visited[i] = true; // swap s(pi, i); // advance i = p[i]; } } } inline std::vector<std::pair<int, int>> transpositions_of(std::vector<int> const& p) { std::vector<std::pair<int, int>> ts; apply_permutation(p, [&](int i, int j) { ts.emplace_back(i, j); }); return ts; } } }
[ "zhengjiang.hu@rwth-aachen.de" ]
zhengjiang.hu@rwth-aachen.de
3a5c04305843106cb5eda15bdf514bc837e71916
048ee6f28d21ed707e6f03e831df43bc1623af78
/Peggle/Basket.cpp
b211ffc828545616c4ac26e537f44c1f90d14281
[ "MIT" ]
permissive
CollegeBart/TP1_ProgII_E17
b4bd81b24c9eea7196df0d803cc5f7a131d26823
63c685ece38c58eca25844d4a9ec6b65ed5563c4
refs/heads/master
2021-03-27T11:16:18.158408
2017-07-12T03:36:05
2017-07-12T03:36:05
94,902,053
0
0
null
null
null
null
UTF-8
C++
false
false
892
cpp
#include "stdafx.h" #include "Basket.h" #include "D3DApp.h" Basket::Basket() : center(.0f, .0f, .0f) , position(250.0f, 335.0f, .0f) , leftPosition(-250.0f, 335.0f, .0f) , rightPosition(250.0f, 335.0f, .0f) , speed(100.0f, 0.f, 0.f) { HR(D3DXCreateTextureFromFileEx(gD3DDevice, L"basket.png", 0, 0, 1, 0, D3DFMT_UNKNOWN, D3DPOOL_MANAGED, D3DX_FILTER_NONE, D3DX_DEFAULT, D3DCOLOR_XRGB(255, 255, 255), &info, NULL, &texture)); center = D3DXVECTOR3(info.Width / 2, info.Height / 2, 0.f); } Basket::~Basket() { ReleaseCOM(texture); } void Basket::Update() { if (position.x < leftPosition.x || position.x > rightPosition.x ) { speed.x *= -1; } position.x -= speed.x * gD3DApp->GetTimer()->GetDeltaTime(); } void Basket::Draw(ID3DXSprite * spriteBatch) { HR(spriteBatch->Draw(texture, 0, &center, &position, D3DCOLOR_XRGB(255, 255, 255))); HR(spriteBatch->Flush()); }
[ "tonylord.ar@gmail.com" ]
tonylord.ar@gmail.com
8b093c54cc5dc446f7741c27eee79c846849a93e
8a4b2c29950c98405110851b8ff1b741ccd7ae3c
/10950.cpp
2a01a29e14dc31fdddc8cc5085b7a51507bfd155
[]
no_license
hotheadfactory/baekjoon
9512c0eeab83cfbaaa584e86385880b19f6211f9
b33326e9186b0ef4c95d0ba90e10d4c33908560c
refs/heads/master
2021-06-15T05:34:39.414241
2021-03-15T15:30:19
2021-04-30T15:06:20
173,936,427
0
0
null
null
null
null
UTF-8
C++
false
false
237
cpp
//https://www.acmicpc.net/problem/10950 'A+B - 3' #include <iostream> using namespace std; int main() { int n, i, a, b; cin >> n; for(i = 0; i < n; i++) { cin >> a >> b; cout << a+b << endl; } return 0; }
[ "commaniakr@gmail.com" ]
commaniakr@gmail.com
cb7db95e705a8ede51888a00ceafbf453273686e
d6b4bdf418ae6ab89b721a79f198de812311c783
/tke/include/tencentcloud/tke/v20180525/model/SetNodePoolNodeProtectionResponse.h
d26058dc9fba5f3416f7a8b072a954f991be7d69
[ "Apache-2.0" ]
permissive
TencentCloud/tencentcloud-sdk-cpp-intl-en
d0781d461e84eb81775c2145bacae13084561c15
d403a6b1cf3456322bbdfb462b63e77b1e71f3dc
refs/heads/master
2023-08-21T12:29:54.125071
2023-08-21T01:12:39
2023-08-21T01:12:39
277,769,407
2
0
null
null
null
null
UTF-8
C++
false
false
3,935
h
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef TENCENTCLOUD_TKE_V20180525_MODEL_SETNODEPOOLNODEPROTECTIONRESPONSE_H_ #define TENCENTCLOUD_TKE_V20180525_MODEL_SETNODEPOOLNODEPROTECTIONRESPONSE_H_ #include <string> #include <vector> #include <map> #include <tencentcloud/core/AbstractModel.h> namespace TencentCloud { namespace Tke { namespace V20180525 { namespace Model { /** * SetNodePoolNodeProtection response structure. */ class SetNodePoolNodeProtectionResponse : public AbstractModel { public: SetNodePoolNodeProtectionResponse(); ~SetNodePoolNodeProtectionResponse() = default; CoreInternalOutcome Deserialize(const std::string &payload); std::string ToJsonString() const; /** * 获取ID of the node that has successfully set the removal protection Note: this field may return `null`, indicating that no valid values can be obtained. * @return SucceedInstanceIds ID of the node that has successfully set the removal protection Note: this field may return `null`, indicating that no valid values can be obtained. * */ std::vector<std::string> GetSucceedInstanceIds() const; /** * 判断参数 SucceedInstanceIds 是否已赋值 * @return SucceedInstanceIds 是否已赋值 * */ bool SucceedInstanceIdsHasBeenSet() const; /** * 获取ID of the node that fails to set the removal protection Note: this field may return `null`, indicating that no valid values can be obtained. * @return FailedInstanceIds ID of the node that fails to set the removal protection Note: this field may return `null`, indicating that no valid values can be obtained. * */ std::vector<std::string> GetFailedInstanceIds() const; /** * 判断参数 FailedInstanceIds 是否已赋值 * @return FailedInstanceIds 是否已赋值 * */ bool FailedInstanceIdsHasBeenSet() const; private: /** * ID of the node that has successfully set the removal protection Note: this field may return `null`, indicating that no valid values can be obtained. */ std::vector<std::string> m_succeedInstanceIds; bool m_succeedInstanceIdsHasBeenSet; /** * ID of the node that fails to set the removal protection Note: this field may return `null`, indicating that no valid values can be obtained. */ std::vector<std::string> m_failedInstanceIds; bool m_failedInstanceIdsHasBeenSet; }; } } } } #endif // !TENCENTCLOUD_TKE_V20180525_MODEL_SETNODEPOOLNODEPROTECTIONRESPONSE_H_
[ "tencentcloudapi@tencent.com" ]
tencentcloudapi@tencent.com
d00872dcc179285d88370554a1bc4111d819d744
9e68f2878909b2bdd6735bdd97dc33634048861a
/GetNext.cpp
82aebd62cb1ba13a92465a5001d34c54b547c23b
[]
no_license
xidianlina/offer
ae80119c08845a2984ed220040cb68e7c703221f
f2f894b3c09f0a1f0e1433dfb80ff958a722317d
refs/heads/master
2021-01-23T15:27:28.471528
2017-09-25T14:24:34
2017-09-25T14:24:34
93,474,877
0
0
null
null
null
null
GB18030
C++
false
false
1,302
cpp
/* 题目描述:给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。 注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。 */ #include <iostream> using namespace std; struct TreeLinkNode { int val; struct TreeLinkNode* left = NULL; struct TreeLinkNode* right = NULL; struct TreeLinkNode* next = NULL; TreeLinkNode(int x):val(x){} }; class Solution { public: /* 分析二叉树的下一个节点,一共有以下情况: 1.二叉树为空,则返回空; 2.节点右孩子存在,则设置一个指针从该节点的右孩子出发,一直沿着指向左子结点的指针找到的叶子节点即为下一个节点; 3.节点不是根节点。如果该节点是其父节点的左孩子,则返回父节点;否则继续向上遍历其父节点的父节点,重复之前的判断,返回结果。 */ TreeLinkNode* GetNext(TreeLinkNode* pNode) { if (pNode == NULL) return NULL; if (pNode->right != NULL) { pNode = pNode->right; while (pNode->left != NULL) pNode = pNode->left; return pNode; } while (pNode->next != NULL) { TreeLinkNode *root = pNode->next; if (root->left == pNode) return root; pNode = pNode->next; } return NULL; } };
[ "119827599@qq.com" ]
119827599@qq.com
b2fe0f8e24a6959359b0a7c4e237c7758d0c37ed
f5cd4aa57470c77530f83ae0fdad58c9ceb865b4
/tests/performance_tests/performance_utils.h
12de14d4b45d916d558df5dfb97c762c0726971d
[ "BSD-3-Clause" ]
permissive
weirdboy79/fonero
4ff23ddeb4b53cb8f4d5029e85b31ee07685648d
80d5aa64b4a7329222954d504e5d99e3fdd48159
refs/heads/master
2020-03-10T07:38:57.850114
2018-04-11T15:31:50
2018-04-11T15:31:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,206
h
// Copyright (c) 2017-2018, The Fonero Project. // Copyright (c) 2014-2017 The Fonero Project. // Portions Copyright (c) 2012-2013 The Cryptonote developers. // // Redistribution and use in source and binary forms, with or without modification, are // permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other // materials provided with the distribution. // // 3. Neither the name of the 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. // // Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers #pragma once #include <iostream> #include <boost/config.hpp> #ifdef BOOST_WINDOWS #include <windows.h> #endif void set_process_affinity(int core) { #if defined (__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) return; #elif defined(BOOST_WINDOWS) DWORD_PTR mask = 1; for (int i = 0; i < core; ++i) { mask <<= 1; } ::SetProcessAffinityMask(::GetCurrentProcess(), core); #elif defined(BOOST_HAS_PTHREADS) cpu_set_t cpuset; CPU_ZERO(&cpuset); CPU_SET(core, &cpuset); if (0 != ::pthread_setaffinity_np(::pthread_self(), sizeof(cpuset), &cpuset)) { std::cout << "pthread_setaffinity_np - ERROR" << std::endl; } #endif } void set_thread_high_priority() { #if defined(__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) return; #elif defined(BOOST_WINDOWS) ::SetPriorityClass(::GetCurrentProcess(), HIGH_PRIORITY_CLASS); #elif defined(BOOST_HAS_PTHREADS) pthread_attr_t attr; int policy = 0; int max_prio_for_policy = 0; ::pthread_attr_init(&attr); ::pthread_attr_getschedpolicy(&attr, &policy); max_prio_for_policy = ::sched_get_priority_max(policy); if (0 != ::pthread_setschedprio(::pthread_self(), max_prio_for_policy)) { std::cout << "pthread_setschedprio - ERROR" << std::endl; } ::pthread_attr_destroy(&attr); #endif }
[ "dev@fonero.org" ]
dev@fonero.org
4d4aede18c27bbd5fe185bbfe737d55e394985b7
2b5c710c9b372ad7e4d49e16852944aaf8926a07
/DerivedSources/WebCore/JSXMLSerializer.h
b8423f6719dbadb6952ebfe1f417d90562279e0c
[ "Apache-2.0" ]
permissive
FMSoftCN/mdolphin-core
8ce68f1055d3a38f6e46bd311f2c20b7afc183b8
48ffdcf587a48a7bb4345ae469a45c5b64ffad0e
refs/heads/master
2022-04-09T22:16:12.602078
2020-02-11T10:06:11
2020-02-11T10:06:11
92,716,592
5
0
null
null
null
null
UTF-8
C++
false
false
3,659
h
/* This file is part of the WebKit open source project. This file has been generated by generate-bindings.pl. DO NOT MODIFY! This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef JSXMLSerializer_h #define JSXMLSerializer_h #include "JSDOMBinding.h" #include <runtime/JSGlobalObject.h> #include <runtime/JSObjectWithGlobalObject.h> #include <runtime/ObjectPrototype.h> namespace WebCore { class XMLSerializer; class JSXMLSerializer : public DOMObjectWithGlobalPointer { typedef DOMObjectWithGlobalPointer Base; public: JSXMLSerializer(NonNullPassRefPtr<JSC::Structure>, JSDOMGlobalObject*, PassRefPtr<XMLSerializer>); static JSC::JSObject* createPrototype(JSC::ExecState*, JSC::JSGlobalObject*); virtual bool getOwnPropertySlot(JSC::ExecState*, const JSC::Identifier& propertyName, JSC::PropertySlot&); virtual bool getOwnPropertyDescriptor(JSC::ExecState*, const JSC::Identifier& propertyName, JSC::PropertyDescriptor&); static const JSC::ClassInfo s_info; static PassRefPtr<JSC::Structure> createStructure(JSC::JSGlobalData& globalData, JSC::JSValue prototype) { return JSC::Structure::create(globalData, prototype, JSC::TypeInfo(JSC::ObjectType, StructureFlags), AnonymousSlotCount, &s_info); } static JSC::JSValue getConstructor(JSC::ExecState*, JSC::JSGlobalObject*); XMLSerializer* impl() const { return m_impl.get(); } private: RefPtr<XMLSerializer> m_impl; protected: static const unsigned StructureFlags = JSC::OverridesGetOwnPropertySlot | Base::StructureFlags; }; JSC::JSValue toJS(JSC::ExecState*, JSDOMGlobalObject*, XMLSerializer*); XMLSerializer* toXMLSerializer(JSC::JSValue); class JSXMLSerializerPrototype : public JSC::JSObjectWithGlobalObject { typedef JSC::JSObjectWithGlobalObject Base; public: static JSC::JSObject* self(JSC::ExecState*, JSC::JSGlobalObject*); static const JSC::ClassInfo s_info; virtual bool getOwnPropertySlot(JSC::ExecState*, const JSC::Identifier&, JSC::PropertySlot&); virtual bool getOwnPropertyDescriptor(JSC::ExecState*, const JSC::Identifier&, JSC::PropertyDescriptor&); static PassRefPtr<JSC::Structure> createStructure(JSC::JSGlobalData& globalData, JSC::JSValue prototype) { return JSC::Structure::create(globalData, prototype, JSC::TypeInfo(JSC::ObjectType, StructureFlags), AnonymousSlotCount, &s_info); } JSXMLSerializerPrototype(JSC::JSGlobalObject* globalObject, NonNullPassRefPtr<JSC::Structure> structure) : JSC::JSObjectWithGlobalObject(globalObject, structure) { } protected: static const unsigned StructureFlags = JSC::OverridesGetOwnPropertySlot | Base::StructureFlags; }; // Functions JSC::EncodedJSValue JSC_HOST_CALL jsXMLSerializerPrototypeFunctionSerializeToString(JSC::ExecState*); // Attributes JSC::JSValue jsXMLSerializerConstructor(JSC::ExecState*, JSC::JSValue, const JSC::Identifier&); } // namespace WebCore #endif
[ "vincent@minigui.org" ]
vincent@minigui.org
af29d83878116925f80b903d38de1c76fdfc129a
ee9135608b035b164ec89427d45f8468bc203321
/images_change.cpp
daf1a5972b559a01da5e7bab19d71d9fd92b6e55
[]
no_license
xiaoqiangbai/GitHub_Test
449fec21d3732e99639c0769981547b904573b79
5e48369d3db9e54dcd0916add6b7c8cea01014ca
refs/heads/master
2023-02-22T17:27:53.316307
2021-01-13T10:14:07
2021-01-13T10:14:07
324,045,939
0
0
null
null
null
null
UTF-8
C++
false
false
533
cpp
#include "images_change.h" #include "widget.h" #include "ui_widget.h" #include "widget.h" #include "ui_widget.h" Images_Change::Images_Change() { index = -1; } char* Images_Change::NextImage() { if( index >= (IMAGE_MAXNUM - 1)) { index = 0; } else { index++; } return (char *)(images[index]); } char* Images_Change::NextImage2() { if( index >= (IMAGE_MAXNUM - 1)) { index = 0; } else { index++; } return (char *)(images2[index]); }
[ "xiaoqiang@qq.com" ]
xiaoqiang@qq.com
a5134cb2ea05ba47c1c2a35a4a646058d95d5184
711e5c8b643dd2a93fbcbada982d7ad489fb0169
/XPSP1/NT/multimedia/dshow/filterus/dexter/tldb/tldbnode.cpp
63f54066b3a17a199212dc65a5bb404048d45755
[]
no_license
aurantst/windows-XP-SP1
629a7763c082fd04d3b881e0d32a1cfbd523b5ce
d521b6360fcff4294ae6c5651c539f1b9a6cbb49
refs/heads/master
2023-03-21T01:08:39.870106
2020-09-28T08:10:11
2020-09-28T08:10:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
25,219
cpp
//==========================================================================; // // 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) 1992 - 1999 Microsoft Corporation. All Rights Reserved. // //--------------------------------------------------------------------------; #include <streams.h> #include "stdafx.h" #include "tldb.h" //############################################################################ // //############################################################################ CAMTimelineNode::CAMTimelineNode( ) : m_pParent( NULL ) , m_pNext( NULL ) , m_pPrev( NULL ) , m_pKid( NULL ) , m_bPriorityOverTime( FALSE ) { } //############################################################################ // //############################################################################ CAMTimelineNode::~CAMTimelineNode( ) { // the order in which release things is important. Don't do it otherwise m_pParent = NULL; m_pNext = NULL; m_pPrev = NULL; m_pKid = NULL; } //############################################################################ // //############################################################################ HRESULT CAMTimelineNode::XGetParent( IAMTimelineObj ** ppResult ) { CheckPointer( ppResult, E_POINTER ); if( m_pParent ) { *ppResult = m_pParent; (*ppResult)->AddRef( ); } return NOERROR; } HRESULT CAMTimelineNode::XGetParentNoRef( IAMTimelineObj ** ppResult ) { CheckPointer( ppResult, E_POINTER ); if( m_pParent ) { *ppResult = m_pParent; } return NOERROR; } //############################################################################ // //############################################################################ HRESULT CAMTimelineNode::XSetParent( IAMTimelineObj * pObj ) { m_pParent = pObj; return NOERROR; } //############################################################################ // //############################################################################ HRESULT CAMTimelineNode::XGetPrev( IAMTimelineObj ** ppResult ) { CheckPointer( ppResult, E_POINTER ); HRESULT hr = XGetPrevNoRef( ppResult ); if( *ppResult ) { (*ppResult)->AddRef( ); } return hr; } //############################################################################ // //############################################################################ HRESULT CAMTimelineNode::XSetPrev( IAMTimelineObj * pObj ) { m_pPrev = pObj; return NOERROR; } //############################################################################ // //############################################################################ HRESULT CAMTimelineNode::XGetNext( IAMTimelineObj ** ppResult ) { CheckPointer( ppResult, E_POINTER ); HRESULT hr = XGetNextNoRef( ppResult ); if( *ppResult ) { (*ppResult)->AddRef( ); } return hr; } //############################################################################ // //############################################################################ HRESULT CAMTimelineNode::XSetNext( IAMTimelineObj * pObj ) { m_pNext = pObj; return NOERROR; } //############################################################################ // //############################################################################ HRESULT CAMTimelineNode::XKidsOfType( long MajorTypeCombo, long * pVal ) { CheckPointer( pVal, E_POINTER ); // if no kids, return 0 // if( !m_pKid ) { *pVal = 0; return NOERROR; } // since we never use bumping of refcounts in here, don't use a CComPtr // IAMTimelineObj * p = m_pKid; // okay not CComPtr long count = 0; while( p ) { TIMELINE_MAJOR_TYPE Type; p->GetTimelineType( &Type ); if( ( Type & MajorTypeCombo ) == Type ) { count++; } // get the next kid // CComQIPtr< IAMTimelineNode, &IID_IAMTimelineNode > p2( p ); p2->XGetNextNoRef( &p ); } *pVal = count; return NOERROR; } //############################################################################ // //############################################################################ HRESULT CAMTimelineNode::XGetNthKidOfType ( long MajorTypeCombo, long Number, IAMTimelineObj ** ppResult ) { // since we never use bumping of refcounts in here, don't use a CComPtr // IAMTimelineObj * p = m_pKid; // okay not CComPtr while( p ) { // get the type // TIMELINE_MAJOR_TYPE Type; p->GetTimelineType( &Type ); // assume won't fail // found a type that matches, decrement how many we're looking for. // if( ( Type & MajorTypeCombo ) == Type ) { // if Number is 0, then we've found the Xth child, return it. // if( Number == 0 ) { *ppResult = p; (*ppResult)->AddRef( ); return NOERROR; } // not yet, go get the next one // Number--; } // doesn't match our type, get the next one // IAMTimelineNode *p2; // avoid CComPtr for perf p->QueryInterface(IID_IAMTimelineNode, (void **)&p2); p2->XGetNextNoRef( &p ); p2->Release(); } // while p *ppResult = NULL; return S_FALSE; } //############################################################################ // //############################################################################ HRESULT CAMTimelineNode::XSwapKids( long MajorTypeCombo, long KidA, long KidB ) { long KidCount = 0; XKidsOfType( MajorTypeCombo, &KidCount ); if( ( KidA < 0 ) || ( KidB < 0 ) ) { return E_INVALIDARG; } if( ( KidA >= KidCount ) || ( KidB >= KidCount ) ) { return E_INVALIDARG; } // there are two things we can swap so far, tracks and effects, both of them // take priorities. // make this easier on us // long min = min( KidA, KidB ); long max = max( KidA, KidB ); // get the objects themselves // CComPtr< IAMTimelineObj > pMinKid; HRESULT hr; hr = XGetNthKidOfType( MajorTypeCombo, min, &pMinKid ); CComPtr< IAMTimelineObj > pMaxKid; hr = XGetNthKidOfType( MajorTypeCombo, max, &pMaxKid ); CComQIPtr< IAMTimelineNode, &IID_IAMTimelineNode > pMinKidNode( pMinKid ); CComQIPtr< IAMTimelineNode, &IID_IAMTimelineNode > pMaxKidNode( pMaxKid ); // don't compare for being the exact same type, we already know this works // because we got the "nth" kid of the right type // get everyone's neighboors // CComPtr< IAMTimelineObj > pMinKidPrev; hr = pMinKidNode->XGetPrev( &pMinKidPrev ); CComPtr< IAMTimelineObj > pMinKidNext; hr = pMinKidNode->XGetNext( &pMinKidNext ); CComPtr< IAMTimelineObj > pMaxKidPrev; hr = pMaxKidNode->XGetPrev( &pMaxKidPrev ); CComPtr< IAMTimelineObj > pMaxKidNext; hr = pMaxKidNode->XGetNext( &pMaxKidNext ); // what if pMinKid what the first kid? // if( pMinKid == m_pKid ) { m_pKid.Release( ); m_pKid = pMaxKid; } // do something special if we're swapping direct neighboors // if( pMinKidNext == pMaxKid ) { pMaxKidNode->XSetPrev( pMinKidPrev ); pMinKidNode->XSetNext( pMaxKidNext ); pMaxKidNode->XSetNext( pMinKid ); pMinKidNode->XSetPrev( pMaxKid ); if( pMinKidPrev ) { CComQIPtr< IAMTimelineNode, &IID_IAMTimelineNode > pMinKidPrevNode( pMinKidPrev ); pMinKidPrevNode->XSetNext( pMaxKid ); } if( pMaxKidNext ) { CComQIPtr< IAMTimelineNode, &IID_IAMTimelineNode > pMaxKidNextNode( pMaxKidNext ); pMaxKidNextNode->XSetPrev( pMinKid ); } return NOERROR; } pMaxKidNode->XSetPrev( pMinKidPrev ); pMinKidNode->XSetNext( pMaxKidNext ); pMaxKidNode->XSetNext( pMinKidNext ); pMinKidNode->XSetPrev( pMaxKidPrev ); if( pMinKidPrev ) { CComQIPtr< IAMTimelineNode, &IID_IAMTimelineNode > pMinKidPrevNode( pMinKidPrev ); pMinKidPrevNode->XSetNext( pMaxKid ); } CComQIPtr< IAMTimelineNode, &IID_IAMTimelineNode > pMinKidNextNode( pMinKidNext ); pMinKidNextNode->XSetPrev( pMaxKid ); if( pMaxKidNext ) { CComQIPtr< IAMTimelineNode, &IID_IAMTimelineNode > pMaxKidNextNode( pMaxKidNext ); pMaxKidNextNode->XSetPrev( pMinKid ); } CComQIPtr< IAMTimelineNode, &IID_IAMTimelineNode > pMaxKidPrevNode( pMaxKidPrev ); pMaxKidPrevNode->XSetNext( pMinKid ); return NOERROR; } //############################################################################ // //############################################################################ HRESULT CAMTimelineNode::XHaveParent( long * pVal ) { CheckPointer( pVal, E_POINTER ); *pVal = 0; if( m_pParent ) { *pVal = 1; } return NOERROR; } //############################################################################ // //############################################################################ HRESULT CAMTimelineNode::XWhatPriorityAmI( long MajorTypeCombo, long * pVal ) { CheckPointer( pVal, E_POINTER ); IAMTimelineObj * pParent = NULL; // okay not ComPtr XGetParentNoRef( &pParent ); CComQIPtr< IAMTimelineNode, &IID_IAMTimelineNode > pParent2( pParent ); if( NULL == pParent ) { *pVal = -1; return NOERROR; } long counter = 0; CComPtr< IAMTimelineObj > pKid; pParent2->XGetNthKidOfType( MajorTypeCombo, 0, &pKid ); while( 1 ) { // no more kids, and we're still looking, so return -1 // if( pKid == NULL ) { return -1; } CComQIPtr< IAMTimelineNode, &IID_IAMTimelineNode > pKid2( pKid ); // we addreffed it just above // pKid.Release( ); // found it, return how many kids we looked at // if( pKid2 == (IAMTimelineNode*) this ) { *pVal = counter; return NOERROR; } counter++; pKid2->XGetNextOfType( MajorTypeCombo, &pKid ); } // never get here } //############################################################################ // //############################################################################ HRESULT CAMTimelineNode::XGetNextOfType( long MajorTypeCombo, IAMTimelineObj ** ppResult ) { // since we never use bumping of refcounts in here, don't use a CComPtr // IAMTimelineObj * pNext = m_pNext; // okay not CComPtr while( pNext ) { TIMELINE_MAJOR_TYPE Type; pNext->GetTimelineType( &Type ); // if the types match, this is the next we want // if( ( Type & MajorTypeCombo ) == Type ) { *ppResult = pNext; (*ppResult)->AddRef( ); return NOERROR; } IAMTimelineNode *pNextNext; // no CComPtr for perf. pNext->QueryInterface(IID_IAMTimelineNode, (void **)&pNextNext); pNextNext->XGetNextNoRef( &pNext ); pNextNext->Release(); } // didn't find any next of type! // DbgLog((LOG_TRACE, 2, TEXT("XGetNextOfType: Didn't find anything of type %ld" ), MajorTypeCombo )); *ppResult = NULL; return S_FALSE; } //############################################################################ // release all of our references and remove ourselves from the tree. // DO NOT REMOVE KIDS //############################################################################ HRESULT CAMTimelineNode::XRemoveOnlyMe( ) { CComQIPtr< IAMTimelineNode, &IID_IAMTimelineNode > pPrev( m_pPrev ); CComQIPtr< IAMTimelineNode, &IID_IAMTimelineNode > pNext( m_pNext ); CComQIPtr< IAMTimelineNode, &IID_IAMTimelineNode > pParent( m_pParent ); // take care of who points to us as the parent // if we're the first kid, the parent needs // to point to someone else besides us. // if( !m_pPrev ) { if( !m_pParent ) { // no parent is okay, as long as you are the root comp } else { // parent' first kid is not us, that's for sure! // pParent->XResetFirstKid( m_pNext ); m_pParent.Release(); } } CComPtr< IAMTimelineObj > pPrevTemp( m_pPrev ); // take care of who points to us as the prev // if( m_pPrev ) { m_pPrev = NULL; pPrev->XSetNext( m_pNext ); } // take care of who points to us as the next // if( pNext ) { m_pNext = NULL; pNext->XSetPrev( pPrevTemp ); } return NOERROR; } //############################################################################ // release all of our references and remove ourselves from the tree. //############################################################################ HRESULT CAMTimelineNode::XRemove( ) { CComQIPtr< IAMTimelineNode, &IID_IAMTimelineNode > pPrev( m_pPrev ); CComQIPtr< IAMTimelineNode, &IID_IAMTimelineNode > pNext( m_pNext ); CComQIPtr< IAMTimelineNode, &IID_IAMTimelineNode > pParent( m_pParent ); // take care of who points to us as the parent // if we're the first kid, the parent needs // to point to someone else besides us. // if( !m_pPrev ) { if( !m_pParent ) { // no parent is okay, as long as you are the root comp } else { // parent' first kid is not us, that's for sure! // pParent->XResetFirstKid( m_pNext ); m_pParent.Release(); } } CComPtr< IAMTimelineObj > pPrevTemp( m_pPrev ); // take care of who points to us as the prev // if( m_pPrev ) { m_pPrev = NULL; pPrev->XSetNext( m_pNext ); } // take care of who points to us as the next // if( pNext ) { m_pNext = NULL; pNext->XSetPrev( pPrevTemp ); } // remove all of our kids // XClearAllKids( ); // done removing kids, good. return NOERROR; } //############################################################################ // //############################################################################ void CAMTimelineNode::XAddKid ( IAMTimelineObj * pAddor ) { if( !m_pKid ) { m_pKid = pAddor; } else { // find last kid // IAMTimelineObj * pLastKid = XGetLastKidNoRef( ); // okay not CComPtr CComQIPtr< IAMTimelineNode, &IID_IAMTimelineNode > pLastKid2( pLastKid ); pLastKid2->XSetNext( pAddor ); CComQIPtr< IAMTimelineNode, &IID_IAMTimelineNode > pAddor2( pAddor ); pAddor2->XSetPrev( pLastKid ); } CComQIPtr< IAMTimelineObj, &IID_IAMTimelineObj > pParent( (IAMTimelineNode*) this ); CComQIPtr< IAMTimelineNode, &IID_IAMTimelineNode > pKid( pAddor ); pKid->XSetParent( pParent ); } //############################################################################ // //############################################################################ HRESULT CAMTimelineNode::XAddKidByPriority ( long MajorTypeCombo, IAMTimelineObj * pThingToInsert, long Which ) { // -1 means add last // if( Which == -1 ) { XAddKid( pThingToInsert ); return NOERROR; } CComPtr< IAMTimelineObj > pThingBeingAddedTo; XGetNthKidOfType( MajorTypeCombo, Which, &pThingBeingAddedTo ); // we want to insert the new one just before the nth kid we just got. if( !pThingBeingAddedTo ) { // we don't have the one we're looking fer, // so just add it to the end of the list // XAddKid( pThingToInsert ); return NOERROR; } // found who we want to insert in front of. // HRESULT hr = XInsertKidBeforeKid( pThingToInsert, pThingBeingAddedTo ); return hr; } //############################################################################ // //############################################################################ HRESULT CAMTimelineNode::XInsertKidBeforeKid( IAMTimelineObj * pThingToInsert, IAMTimelineObj * pThingBeingAddedTo ) { // we can assume pThingToInsert is a kid of ours // if pThingBeingAddedTo is NULL, then add pThingToInsert at end of list // if( pThingBeingAddedTo == NULL ) { XAddKid( pThingToInsert ); return NOERROR; } // is pThingBeingAddedTo the very first kid? // if( pThingBeingAddedTo == m_pKid ) { // yep, then insert pThingToInsert before that // CComPtr< IAMTimelineObj > pOldFirstKid = m_pKid; m_pKid = pThingToInsert; CComQIPtr< IAMTimelineNode, &IID_IAMTimelineNode > p( m_pKid ); p->XSetNext( pOldFirstKid ); p = pOldFirstKid; p->XSetPrev( m_pKid ); } else { // nope, insert pThingToInsert before the kid // CComPtr< IAMTimelineObj > pPrev; CComQIPtr< IAMTimelineNode, &IID_IAMTimelineNode > p( pThingBeingAddedTo ); // get the thing previous to the addor p->XGetPrev( &pPrev ); p = pPrev; // by setting prev/next, this will temporarily drop the refcount on the old pThingBeingAddedTo, // so we need to addref/release around it pThingBeingAddedTo->AddRef( ); p->XSetNext( pThingToInsert ); p = pThingToInsert; p->XSetPrev( pPrev ); p->XSetNext( pThingBeingAddedTo ); p = pThingBeingAddedTo; p->XSetPrev( pThingToInsert ); pThingBeingAddedTo->Release( ); } CComQIPtr< IAMTimelineObj, &IID_IAMTimelineObj > pParent( (IUnknown*) this ); CComQIPtr< IAMTimelineNode, &IID_IAMTimelineNode > pKid( pThingToInsert ); pKid->XSetParent( pParent ); return NOERROR; } //############################################################################ // //############################################################################ HRESULT CAMTimelineNode::XInsertKidAfterKid( IAMTimelineObj * pThingToInsert, IAMTimelineObj * pThingBeingAddedTo ) { // we can assume pThingToInsert is a kid of ours // if pThingBeingAddedTo is NULL, then add pThingToInsert at end of list // if( pThingBeingAddedTo == NULL ) { XAddKid( pThingToInsert ); return NOERROR; } CComPtr< IAMTimelineObj > pNext; CComQIPtr< IAMTimelineNode, &IID_IAMTimelineNode > p( pThingBeingAddedTo ); // get the thing after the addor p->XGetNext( &pNext ); if (pNext) { p = pNext; p->XSetPrev( pThingToInsert ); } p = pThingToInsert; p->XSetNext( pNext ); p->XSetPrev( pThingBeingAddedTo ); p = pThingBeingAddedTo; p->XSetNext( pThingToInsert ); CComQIPtr< IAMTimelineObj, &IID_IAMTimelineObj > pParent( (IUnknown*) this ); CComQIPtr< IAMTimelineNode, &IID_IAMTimelineNode > pKid( pThingToInsert ); pKid->XSetParent( pParent ); return NOERROR; } //############################################################################ // //############################################################################ IAMTimelineObj * CAMTimelineNode::XGetLastKidNoRef( ) { // no kids = no return // if( !m_pKid ) { return NULL; } // since we never use bumping of refcounts in here, don't use a CComPtr // IAMTimelineObj * pKid = m_pKid; // okay not CComPtr while( 1 ) { CComQIPtr< IAMTimelineNode, &IID_IAMTimelineNode > pKid2( pKid ); IAMTimelineObj * pNext = NULL; // okay not CComPtr pKid2->XGetNextNoRef( &pNext ); if( NULL == pNext ) { return pKid; } pKid = pNext; } // never gets here. } //############################################################################ // //############################################################################ STDMETHODIMP CAMTimelineNode::XClearAllKids( ) { // remove all of our kids // CComPtr< IAMTimelineObj > pKid; while( 1 ) { // kick out of while loop if we've removed all of the kids from the tree // if( !m_pKid ) { break; } // reset pointer, because it may have changed below // pKid = m_pKid; { CComQIPtr< IAMTimelineNode, &IID_IAMTimelineNode > pNode( pKid ); // remove kid from tree, this may change our kid pointer // pNode->XRemove( ); } pKid = NULL; } return NOERROR; } //############################################################################ // //############################################################################ STDMETHODIMP CAMTimelineNode::XGetNextOfTypeNoRef( long MajorType, IAMTimelineObj ** ppResult ) { CheckPointer( ppResult, E_POINTER ); HRESULT hr = XGetNextOfType( MajorType, ppResult ); if( *ppResult ) { (*ppResult)->Release( ); } return hr; } //############################################################################ // //############################################################################ STDMETHODIMP CAMTimelineNode::XGetNextNoRef( IAMTimelineObj ** ppResult ) { CheckPointer( ppResult, E_POINTER ); *ppResult = m_pNext; // since we are making an assignment, no addref return NOERROR; } //############################################################################ // //############################################################################ STDMETHODIMP CAMTimelineNode::XGetPrevNoRef( IAMTimelineObj ** ppResult ) { CheckPointer( ppResult, E_POINTER ); *ppResult = m_pPrev; return NOERROR; } //############################################################################ // //############################################################################ STDMETHODIMP CAMTimelineNode::XResetFirstKid( IAMTimelineObj * pKid ) { m_pKid = pKid; return NOERROR; } //############################################################################ // //############################################################################ STDMETHODIMP CAMTimelineNode::XAddKidByTime( long MajorTypeCombo, IAMTimelineObj * pToAdd ) { HRESULT hr = 0; // no kids = no return // if( !m_pKid ) { XAddKid( pToAdd ); return NOERROR; } REFERENCE_TIME InStart = 0; REFERENCE_TIME InStop = 0; pToAdd->GetStartStop( &InStart, &InStop ); // since we never use bumping of refcounts in here, don't use a CComPtr // IAMTimelineObj * pKid = m_pKid; // okay not CComPtr while( pKid ) { // ask the kid if he's (he?) the right type // TIMELINE_MAJOR_TYPE Type; pKid->GetTimelineType( &Type ); // only consider it if the types match // if( ( Type & MajorTypeCombo ) == Type ) { // ask it for it's times // REFERENCE_TIME Start = 0; REFERENCE_TIME Stop = 0; pKid->GetStartStop( &Start, &Stop ); if( InStop <= Start ) { // found the one to insert into // hr = XInsertKidBeforeKid( pToAdd, pKid ); return hr; } } // get the next one // CComQIPtr< IAMTimelineNode, &IID_IAMTimelineNode > pKid2( pKid ); pKid2->XGetNextNoRef( &pKid ); } // well, didn't find anything that matched, so add it at the end // XAddKid( pToAdd ); return NOERROR; } STDMETHODIMP CAMTimelineNode::XGetPriorityOverTime( BOOL * pResult ) { CheckPointer( pResult, E_POINTER ); *pResult = m_bPriorityOverTime; return NOERROR; } IAMTimelineObj * CAMTimelineNode::XGetFirstKidNoRef( ) { return m_pKid; }
[ "112426112@qq.com" ]
112426112@qq.com
504d3c67de12e600fb8f49b53855f424d0779cdf
e637460f3fa2504b1f4a789d066176d304b03ead
/src/engine/metaprogramming/for-each-type.hpp
19f7ac918fe51f9eec49e807415ca9f35c2501d8
[ "Apache-2.0" ]
permissive
Ghabriel/ecs-arkanoid
9983d79cbcafbd562cd36ca0e840d6342b719f76
af005bc89ce535616c7a006c7c76b2a414c90901
refs/heads/master
2020-06-02T06:16:55.313565
2019-06-22T14:49:52
2019-06-22T14:58:56
191,066,122
1
0
null
null
null
null
UTF-8
C++
false
false
379
hpp
#pragma once #include <tuple> namespace meta { namespace __detail { template<typename F, typename... Ts> void forEachT(F fn, std::tuple<Ts...>*) { (fn.template operator()<Ts>(), ...); } } template<typename Tuple, typename F> void forEachT(F fn) { return __detail::forEachT(fn, static_cast<Tuple*>(nullptr)); } }
[ "ghabriel.nunes@gmail.com" ]
ghabriel.nunes@gmail.com
70484be9b9962e1a91219bfc785540821817e366
ffaff3f22f6610b3a0cd38cccdff7b2438ab36f3
/TMP_2_Prock_OOP/bus.h
e0b3c5667b3bb548ab2ba1586b31a86d3f7fe62d
[]
no_license
Lizzi-2020/tmp_2_prock_oop
b01528c4b9a0afbbd3a5fd7652afc6749a21d380
a2464b558590ed99a3899c9c4047fe5dd8296822
refs/heads/master
2022-09-14T23:56:27.383968
2020-06-02T16:01:15
2020-06-02T16:01:15
268,846,261
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
303
h
#pragma once #include "transport.h" class bus : public transport { int size; public: // переопределяем интерфейс класса void InData(ifstream &ifst); // ввод void Out(ofstream &ofst); // вывод //bus() {} // создание без инициализации. };
[ "liza.erofeeva.2016@mail.ru" ]
liza.erofeeva.2016@mail.ru
494602f5ad4b2a400dc00992a749e26bb89dd3a2
17dbb20d6375bee96241904ca6c5c88926df53d6
/SKA/src/Signals/FFT.cpp
659fbf711214f5a99f38b28ebbf1932f892c0c90
[]
no_license
camcow/SKAstart
5883fb25931a183c43f6c9df19452bd9e8968c97
9d7a5ab3b94fa18a9f36c991d4090ef3e8eadc91
refs/heads/master
2021-01-13T01:40:23.293005
2014-12-09T05:36:11
2014-12-09T05:36:11
27,151,425
1
1
null
null
null
null
UTF-8
C++
false
false
11,124
cpp
//----------------------------------------------------------------------------- // FFT.cpp // Interface to Fast Fourier Transform processing. // This code is non-functional if not linked to FFTW library, // available from www.fftw.org. // See ENABLE_FFTW flag in Core/SystemConfiguration.h. //----------------------------------------------------------------------------- // This software is part of the Skeleton Animation Toolkit (SKA) developed // at the University of the Pacific, under the guidance of Michael Doherty. // For information please contact mdoherty@pacific.edu. //----------------------------------------------------------------------------- // This is open software. You are free to use it as you see fit. // The University of the Pacific and identified authors would appreciate // being credited for any significant use, particularly if used for // commercial projects or academic research publications. //----------------------------------------------------------------------------- // Version 3.1 - September 1, 2014 - Michael Doherty //----------------------------------------------------------------------------- #include <Core/SystemConfiguration.h> #include <cstdio> #include <cstdlib> #include <fstream> using namespace std; #include <Signals/FFT.h> #include <Animation/Skeleton.h> #if ENABLE_FFTW==1 #include <fftw3.h> #endif // Locates strongest signals from a Fourier Transform spectrum // inputs: spectrum: the FT // n: length of the FT // num_signals: number of signals to extract // outputs: signals: the extracted signals // return value: number of signals actually extracted (<= num_signals) // note: phase is currently set for SINE waves int extractSignalsFromSpectrum(complex<float>* spectrum, int n, vector<SignalSpec>& signals, int num_signals) { int i, j, k; int* sig_indexes = new int[num_signals]; float* norms = new float[n]; for (k=0; k<n; k++) norms[k] = norm(spectrum[k]); float max = FLT_MAX; // FIXIT! this is incredibly naive for (i=0; i<num_signals; i++) { int maxk = -1; float best = FLT_MIN; for (k=0; k<n; k++) { if (norms[k] < max) { if (norms[k] > best) { maxk = k; best = norms[k]; } } } sig_indexes[i] = maxk; max = norms[maxk]; // (minus epsilon) } for (j=0; j<i; j++) { complex<float> c = spectrum[sig_indexes[j]]; SignalSpec ss; ss.amplitude = 2.0f*sqrt(c.real()*c.real()+c.imag()*c.imag())/n; ss.frequency = float(sig_indexes[j]*100)/n; ss.phase = atan2(c.real(), -c.imag()); signals.push_back(ss); } delete [] sig_indexes; delete [] norms; return i; } // Structure for converting data to format required by FFTW algorithms #if ENABLE_FFTW==1 struct FFTW_Array { long n; fftw_complex* data; FFTW_Array() { n = 0; data = NULL; } FFTW_Array(long _n) { data = NULL; resize(_n); } ~FFTW_Array() { if (data != NULL) fftw_free(data); } void resize(long _n) { if (data != NULL) fftw_free(data); n = _n; data = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * n); } void load(float* f) { for (long i=0; i<n; i++) { data[i][0] = f[i]; data[i][1] = 0.0; } } void extract(float* f) { for (long i=0; i<n; i++) f[i] = (float)data[i][0]; } void load(complex<float>* f) { for (long i=0; i<n; i++) { data[i][0] = f[i].real(); data[i][1] = f[i].imag(); } } void extract(complex<float>* f) { for (long i=0; i<n; i++) f[i] = complex<float>((float)data[i][0],(float)data[i][1]); } }; #endif // ENABLE_FFTW==1 bool computeFFT(float* signal, complex<float>* spectrum, int n) { #if ENABLE_FFTW==1 FFTW_Array in, out; in.resize(n); out.resize(n); in.load(signal); fftw_plan fwd_plan; fwd_plan = fftw_plan_dft_1d(n, in.data, out.data, FFTW_FORWARD, FFTW_ESTIMATE); fftw_execute(fwd_plan); fftw_destroy_plan(fwd_plan); out.extract(spectrum); return true; #else // ENABLE_FFTW==0 return false; #endif // ENABLE_FFTW } bool computeFFT(complex<float>* signal, complex<float>* spectrum, int n) { #if ENABLE_FFTW==1 FFTW_Array in, out; in.resize(n); out.resize(n); in.load(signal); fftw_plan fwd_plan; fwd_plan = fftw_plan_dft_1d(n, in.data, out.data, FFTW_FORWARD, FFTW_ESTIMATE); fftw_execute(fwd_plan); fftw_destroy_plan(fwd_plan); out.extract(spectrum); return true; #else // ENABLE_FFTW==0 return false; #endif // ENABLE_FFTW } bool computeInverseFFT(complex<float>* spectrum, float* signal,int n) { #if ENABLE_FFTW==1 FFTW_Array in, out; in.resize(n); out.resize(n); in.load(spectrum); fftw_plan bwd_plan; bwd_plan = fftw_plan_dft_1d(n, in.data, out.data, FFTW_BACKWARD, FFTW_ESTIMATE); fftw_execute(bwd_plan); fftw_destroy_plan(bwd_plan); out.extract(signal); for (int i=0; i<n; i++) { signal[i] /= n; } return true; #else // ENABLE_FFTW==0 return false; #endif // ENABLE_FFTW } bool computeInverseFFT(complex<float>* spectrum, complex<float>* signal,int n) { #if ENABLE_FFTW==1 FFTW_Array in, out; in.resize(n); out.resize(n); in.load(spectrum); fftw_plan bwd_plan; bwd_plan = fftw_plan_dft_1d(n, in.data, out.data, FFTW_BACKWARD, FFTW_ESTIMATE); fftw_execute(bwd_plan); fftw_destroy_plan(bwd_plan); out.extract(signal); for (int i=0; i<n; i++) { signal[i] /= complex<float>(float(n),0.0f); } return true; #else // ENABLE_FFTW==0 return false; #endif // ENABLE_FFTW } bool computeInverseFFT(float* input, float* output, int n) { #if ENABLE_FFTW==1 FFTW_Array fft, signal; fft.resize(n); signal.resize(n); fft.load(input); fftw_plan bwd_plan; bwd_plan = fftw_plan_dft_1d(n, fft.data, signal.data, FFTW_BACKWARD, FFTW_ESTIMATE); fftw_execute(bwd_plan); fftw_destroy_plan(bwd_plan); for (int i=0; i<n; i++) { signal.data[i][0] /= n; signal.data[i][1] /= n;} signal.extract(output); return true; #else // ENABLE_FFTW==0 return false; #endif // ENABLE_FFTW } bool computeFFT2(float* input, float* output1, float* output2, int n) { #if ENABLE_FFTW==1 FFTW_Array signal, fft, recon; signal.resize(n); fft.resize(n); recon.resize(n); signal.load(input); fftw_plan fwd_plan; fwd_plan = fftw_plan_dft_1d(n, signal.data, fft.data, FFTW_FORWARD, FFTW_ESTIMATE); fftw_execute(fwd_plan); fftw_destroy_plan(fwd_plan); fft.extract(output1); fftw_plan bwd_plan; bwd_plan = fftw_plan_dft_1d(n, fft.data, recon.data, FFTW_BACKWARD, FFTW_ESTIMATE); fftw_execute(bwd_plan); fftw_destroy_plan(bwd_plan); for (int i=0; i<n; i++) { recon.data[i][0] /= n; recon.data[i][1] /= n;} recon.extract(output2); return true; #else // ENABLE_FFTW==0 return false; #endif // ENABLE_FFTW } #if ENABLE_FFTW==1 static void runFFTwithFilter(FFTW_Array& signal, FFTW_Array& fft, FFTW_Array& recon_signal, int cutoff=-1) { int n = signal.n; fft.resize(n); recon_signal.resize(n); fftw_plan fwd_plan, bwd_plan; fwd_plan = fftw_plan_dft_1d(n, signal.data, fft.data, FFTW_FORWARD, FFTW_ESTIMATE); fftw_execute(fwd_plan); fftw_destroy_plan(fwd_plan); if (cutoff > 0) for (int i=cutoff; i<n; i++) { fft.data[i][0] = fft.data[i][1] = 0.0f; } bwd_plan = fftw_plan_dft_1d(n, fft.data, recon_signal.data, FFTW_BACKWARD, FFTW_ESTIMATE); fftw_execute(bwd_plan); fftw_destroy_plan(bwd_plan); for (int i=0; i<n; i++) { recon_signal.data[i][0] /= n; recon_signal.data[i][1] /= n;} } static void runFFTwithFilter(float* signal, complex<float>* spectrum, float* recon_signal, int n, int cutoff=-1) { computeFFT(signal, spectrum, n); if (cutoff > 0) for (int i=cutoff; i<n; i++) { spectrum[i] = complex<float>(0.0f,0.0f); } computeInverseFFT(spectrum, recon_signal, n); for (int i=0; i<n; i++) { recon_signal[i] /= n; } } #endif // ENABLE_FFTW void FFTfilter::setFilterChannels() { for (int channel=0; channel<num_channels; channel++) { filter_channels[channel] = (channel>=6); } } void FFTfilter::initialize(MotionSequence* _motion) { motion = _motion; num_frames = motion->numFrames(); num_channels = motion->numChannels(); original.resize(num_frames, num_channels); filtered.resize(num_frames, num_channels); setFilterChannels(); for (int channel=0; channel<num_channels; channel++) { float* ptr = motion->getChannelPtr(channel); memcpy(original.getColumnPtr(channel), ptr, num_frames*sizeof(float)); memcpy(filtered.getColumnPtr(channel), ptr, num_frames*sizeof(float)); } } void FFTfilter::runFilters(int cutoff) { printf("FFTfilter running %d\n", cutoff); if (motion==NULL) return; for (int channel=0; channel<num_channels; channel++) if (filter_channels[channel]) runFilter(channel, cutoff); } bool FFTfilter::runFilter(CHANNEL_ID& channel, int cutoff) { short i = motion->getChannelIndex(channel); if (i<0) return false; runFilter(i, cutoff); return true; } void FFTfilter::runFilter(int channel, int cutoff) { float* original_data = original.getColumnPtr(channel); float* filtered_data = filtered.getColumnPtr(channel); #if ENABLE_FFTW==1 if (cutoff < 0) { memcpy(filtered_data, original_data, num_frames*sizeof(float)); } else { FFTW_Array signal, fft, recon_signal; signal.resize(num_frames); fft.resize(num_frames); recon_signal.resize(num_frames); signal.load(original_data); runFFTwithFilter(signal, fft, recon_signal, cutoff); recon_signal.extract(filtered_data); } memcpy(motion->data.getColumnPtr(channel), filtered_data, num_frames*sizeof(float)); #else // ENABLE_FFTW==0 memcpy(filtered_data, original_data, num_frames*sizeof(float)); #endif // ENABLE_FFTW } int FFTfilter::computeFFT(CHANNEL_ID& channel, float result[], int len) { short i = motion->getChannelIndex(channel); if (i<0) return -1; return computeFFT(i, result, len); } int FFTfilter::computeFFT(int channel, float result[], int len) { #if ENABLE_FFTW==1 int n = num_frames; float* original_data = original.getColumnPtr(channel); float* fft_input = new float[n]; memcpy(fft_input, original_data, n*sizeof(float)); float* fft_data = new float[n]; FFTW_Array signal, fft, recon_signal; signal.resize(n); fft.resize(n); signal.load(fft_input); runFFTwithFilter(signal, fft, recon_signal); fft.extract(fft_data); if (n > len) n = len; memcpy(result, fft_data, n*sizeof(float)); delete [] fft_data; return n; #else // ENABLE_FFTW==0 return 0; #endif // ENABLE_FFTW } int FFTfilter::computeFFT(CHANNEL_ID& channel, complex<float> result[], int len) { short i = motion->getChannelIndex(channel); if (i<0) return -1; return computeFFT(i, result, len); } // INWORK - modify this to extract both real and imaginary components int FFTfilter::computeFFT(int channel, complex<float> result[], int len) { #if ENABLE_FFTW==1 int n = num_frames; float* original_data = original.getColumnPtr(channel); float* fft_input = new float[n]; memcpy(fft_input, original_data, n*sizeof(float)); float* fft_data = new float[n]; FFTW_Array signal, fft, recon_signal; signal.resize(n); fft.resize(n); signal.load(fft_input); runFFTwithFilter(signal, fft, recon_signal); fft.extract(fft_data); if (n > len) n = len; memcpy(result, fft_data, n*sizeof(float)); delete [] fft_data; return n; #else // ENABLE_FFTW==0 return 0; #endif // ENABLE_FFTW }
[ "c_cowan1@u.pacific.edu" ]
c_cowan1@u.pacific.edu
5425eafd688d16ffecc52ab7944679f8119a2f5f
1bc87828c32581af45fe6b84702738c10b034d3a
/01_Introductory_Problems/Missing_Number/Missing_Number.cpp
23818e89cf278e13b76873585bb20941c140ae73
[]
no_license
axrdiv/CSES_Problem_Set
90c854fdb65023325755d3265a2db6cd373755c6
5209750c28089708606721b617f404fbb2d67dd7
refs/heads/master
2023-06-28T03:26:08.671394
2021-07-28T19:39:52
2021-07-28T19:39:52
297,074,300
0
0
null
null
null
null
UTF-8
C++
false
false
353
cpp
#include<cstdio> using namespace std; const int maxn = 200000 + 5; bool exist[maxn]; int n, tmp; int main() { scanf("%d", &n); for(int i = 0; i < n; i++) { scanf("%d", &tmp); exist[tmp] = 1; } for(int i = 1; i <= n; i++) { if(exist[i]) continue; printf("%d\n", i); break; } return 0; }
[ "axrdiv@outlook.com" ]
axrdiv@outlook.com