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
b2d8c84a59a7c931ba71139eeeb7b0397fd5a76b
66c5af414ec97bcc48c577341525452b0dee8da4
/CPP_SOLUTIONS/2.cpp
46dd0427ad8d477b98131accc972a3f681eed6bc
[]
no_license
CocoCui/Leetcode_solutions
8b6a46b5767b4352020e89cbd7915db8ab9817ee
7c16598dc187c3db2cc93d0b2690278ff86525d6
refs/heads/master
2021-01-11T23:28:33.217424
2017-04-17T21:50:03
2017-04-17T21:50:03
78,586,946
0
0
null
null
null
null
UTF-8
C++
false
false
1,090
cpp
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { return add(l1, l2, 0); } private: ListNode* add(ListNode* l, ListNode* r, int c) { if(l == NULL && r == NULL) { if(c == 0) return NULL; else return new ListNode(c); } if(l == NULL) { int val = r -> val + c; ListNode* cur = new ListNode(val % 10); cur -> next = add(NULL, r -> next, val / 10); return cur; } else if(r == NULL){ int val = l -> val + c; ListNode* cur = new ListNode(val % 10); cur -> next = add(NULL, l -> next, val / 10); return cur; } else { int val = l -> val + r -> val + c; ListNode* cur = new ListNode(val % 10); cur -> next = add(l -> next, r -> next, val / 10); return cur; } } };
[ "cuiyan@vip.163.com" ]
cuiyan@vip.163.com
4561f6bf413acbb475b0447757dc9930bcce6923
355cbef948a1c2c46046a8f7c4d40b9d0b0d8889
/include/perceptive_mpc/costs/VoxbloxCost.h
33d8f60c941131232592d8c652be87afb5ea33ab
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
leggedrobotics/perceptive_mpc
d4c01298e4ed2fdd62cea0fc0d36731c6ecdabb0
acf0d79714d3d57e5a041d79948fde8e45b36468
refs/heads/master
2022-01-14T04:26:53.480026
2021-12-30T17:11:32
2021-12-30T17:11:32
242,604,483
90
24
null
null
null
null
UTF-8
C++
false
false
5,635
h
/* * Copyright (c) 2020 Johannes Pankert <pankertj@ethz.ch> * 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 this work 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. */ #pragma once #include <ocs2_core/automatic_differentiation/CppAdInterface.h> #include <perceptive_mpc/costs/PointsOnRobot.h> #include "ocs2_core/cost/CostFunctionBase.h" #include "perceptive_mpc/Definitions.h" namespace voxblox { class EsdfCachingVoxel; template <typename VoxelType> class Interpolator; } // namespace voxblox namespace perceptive_mpc { using typename voxblox::EsdfCachingVoxel; using voxblox::Interpolator; struct VoxbloxCostConfig { double mu = 1; double delta = 1e-3; double maxDistance = 2.0; std::shared_ptr<const PointsOnRobot> pointsOnRobot; std::shared_ptr<Interpolator<EsdfCachingVoxel>> interpolator; }; class VoxbloxCost : public ocs2::CostFunctionBase<Definitions::STATE_DIM_, Definitions::INPUT_DIM_> { public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW using Ptr = std::shared_ptr<VoxbloxCost>; using ConstPtr = std::shared_ptr<const VoxbloxCost>; using BASE = CostFunctionBase<Definitions::STATE_DIM_, Definitions::INPUT_DIM_>; using typename BASE::input_vector_t; using typename BASE::scalar_t; using typename BASE::state_matrix_t; using typename BASE::state_vector_t; VoxbloxCost(const VoxbloxCostConfig& config) : CostFunctionBase(), interpolator_(config.interpolator), maxDistance_(config.maxDistance), mu_(config.mu), delta_(config.delta), pointsOnRobot_(config.pointsOnRobot), distances_(pointsOnRobot_->numOfPoints()), gradientsVoxblox_(pointsOnRobot_->numOfPoints(), pointsOnRobot_->numOfPoints() * 3), gradients_(pointsOnRobot_->numOfPoints(), 13) {} VoxbloxCost(const VoxbloxCost& rhs) : CostFunctionBase(), interpolator_(rhs.interpolator_), maxDistance_(rhs.maxDistance_), mu_(rhs.mu_), delta_(rhs.delta_), pointsOnRobot_(new PointsOnRobot(*rhs.pointsOnRobot_)), distances_(rhs.distances_), gradientsVoxblox_(rhs.gradientsVoxblox_), gradients_(rhs.gradients_) {} /** * Destructor */ ~VoxbloxCost() override = default; VoxbloxCost* clone() const override { return new VoxbloxCost(*this); } void setCurrentStateAndControl(const scalar_t& t, const state_vector_t& x, const input_vector_t& u); void getIntermediateCost(scalar_t& L) override; void getIntermediateCostDerivativeState(state_vector_t& dLdx) override; void getIntermediateCostSecondDerivativeState(state_matrix_t& dLdxx) override; void getIntermediateCostDerivativeInput(input_vector_t& dLdu) override; void getIntermediateCostSecondDerivativeInput(input_matrix_t& dLduu) override; void getIntermediateCostDerivativeInputState(input_state_matrix_t& dLdux) override; void getTerminalCost(scalar_t& Phi) override; void getTerminalCostDerivativeState(state_vector_t& dPhidx) override; void getTerminalCostSecondDerivativeState(state_matrix_t& dPhidxx) override; void getIntermediateCostDerivativeTime(scalar_t& dLdt) override; void getTerminalCostDerivativeTime(scalar_t& dPhidt) override; void getIntermediateCostDerivativeStateVerbose(state_vector_t& dLdx); private: scalar_t mu_; scalar_t delta_; scalar_t maxDistance_; std::shared_ptr<const PointsOnRobot> pointsOnRobot_; std::shared_ptr<Interpolator<EsdfCachingVoxel>> interpolator_; Eigen::Matrix<scalar_t, -1, 1> distances_; Eigen::MatrixXd gradientsVoxblox_; Eigen::Matrix<scalar_t, -1, STATE_DIM_> gradients_; scalar_t getPenaltyFunctionValue(scalar_t h) const { if (h > delta_) { return -mu_ * log(h); } else { return mu_ * (-log(delta_) + scalar_t(0.5) * pow((h - 2.0 * delta_) / delta_, 2.0) - scalar_t(0.5)); }; }; scalar_t getPenaltyFunctionDerivative(scalar_t h) const { if (h > delta_) { return -mu_ / h; } else { return mu_ * ((h - 2.0 * delta_) / (delta_ * delta_)); }; }; scalar_t getPenaltyFunctionSecondDerivative(scalar_t h) const { if (h > delta_) { return mu_ / (h * h); } else { return mu_ / (delta_ * delta_); }; }; }; } // namespace perceptive_mpc
[ "Johannes.Pankert@mavt.ethz.ch" ]
Johannes.Pankert@mavt.ethz.ch
387babe0a272f0dc7b0ce722ac989425eef61163
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/mutt/gumtree/mutt_function_68.cpp
7a192150701d37b6d0f946ca73f1fe6700607d42
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,542
cpp
void pgp_signed_handler (BODY *a, STATE *s) { char tempfile[_POSIX_PATH_MAX]; char *protocol; int protocol_major = TYPEOTHER; char *protocol_minor = NULL; BODY *b = a; BODY **signatures = NULL; int sigcnt = 0; int i; short goodsig = 1; protocol = mutt_get_parameter ("protocol", a->parameter); a = a->parts; /* extract the protocol information */ if (protocol) { char major[STRING]; char *t; if ((protocol_minor = strchr(protocol, '/'))) protocol_minor++; strfcpy(major, protocol, sizeof(major)); if((t = strchr(major, '/'))) *t = '\0'; protocol_major = mutt_check_mime_type (major); } /* consistency check */ if (!(a && a->next && a->next->type == protocol_major && !ascii_strcasecmp(a->next->subtype, protocol_minor))) { state_attach_puts(_("[-- Error: Inconsistent multipart/signed structure! --]\n\n"), s); mutt_body_handler (a, s); return; } if(!(protocol_major == TYPEAPPLICATION && !ascii_strcasecmp(protocol_minor, "pgp-signature")) && !(protocol_major == TYPEMULTIPART && !ascii_strcasecmp(protocol_minor, "mixed"))) { state_mark_attach (s); state_printf(s, _("[-- Error: Unknown multipart/signed protocol %s! --]\n\n"), protocol); mutt_body_handler (a, s); return; } if (s->flags & M_DISPLAY) { pgp_fetch_signatures(&signatures, a->next, &sigcnt); if (sigcnt) { mutt_mktemp (tempfile); if (pgp_write_signed (a, s, tempfile) == 0) { for (i = 0; i < sigcnt; i++) { if (signatures[i]->type == TYPEAPPLICATION && !ascii_strcasecmp(signatures[i]->subtype, "pgp-signature")) { if (pgp_verify_one (signatures[i], s, tempfile) != 0) goodsig = 0; } else { state_mark_attach (s); state_printf (s, _("[-- Warning: We can't verify %s/%s signatures. --]\n\n"), TYPE(signatures[i]), signatures[i]->subtype); } } } mutt_unlink (tempfile); b->goodsig = goodsig; dprint (2, (debugfile, "pgp_signed_handler: goodsig = %d\n", goodsig)); /* Now display the signed body */ state_attach_puts (_("[-- The following data is signed --]\n\n"), s); safe_free((void **) &signatures); } else state_attach_puts (_("[-- Warning: Can't find any signatures. --]\n\n"), s); } mutt_body_handler (a, s); if (s->flags & M_DISPLAY && sigcnt) { state_putc ('\n', s); state_attach_puts (_("[-- End of signed data --]\n"), s); } }
[ "993273596@qq.com" ]
993273596@qq.com
639aceb1d9f28b99df1ab795d1989e4fec56e57c
3282ccae547452b96c4409e6b5a447f34b8fdf64
/SimModel_Python_API/simmodel_swig/SimModel_Dll_lib/framework/SimMaterialLayerSet_GlazingLayerSet_CurtainWall.cxx
6e5946a0b464ed540636179ed97bb69e533725f5
[ "MIT" ]
permissive
EnEff-BIM/EnEffBIM-Framework
c8bde8178bb9ed7d5e3e5cdf6d469a009bcb52de
6328d39b498dc4065a60b5cc9370b8c2a9a1cddf
refs/heads/master
2021-01-18T00:16:06.546875
2017-04-18T08:03:40
2017-04-18T08:03:40
28,960,534
3
0
null
2017-04-18T08:03:40
2015-01-08T10:19:18
C++
UTF-8
C++
false
false
23,328
cxx
// Copyright (c) 2005-2014 Code Synthesis Tools CC // // This program was generated by CodeSynthesis XSD, an XML Schema to // C++ data binding compiler. // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License version 2 as // published by the Free Software Foundation. // // 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // // In addition, as a special exception, Code Synthesis Tools CC gives // permission to link this program with the Xerces-C++ library (or with // modified versions of Xerces-C++ that use the same license as Xerces-C++), // and distribute linked combinations including the two. You must obey // the GNU General Public License version 2 in all respects for all of // the code used other than Xerces-C++. If you modify this copy of the // program, you may extend this exception to your version of the program, // but you are not obligated to do so. If you do not wish to do so, delete // this exception statement from your version. // // Furthermore, Code Synthesis Tools CC makes a special exception for // the Free/Libre and Open Source Software (FLOSS) which is described // in the accompanying FLOSSE file. // // Begin prologue. // // // End prologue. #include <xsd/cxx/pre.hxx> #include "SimMaterialLayerSet_GlazingLayerSet_CurtainWall.hxx" namespace schema { namespace simxml { namespace ResourcesGeneral { // SimMaterialLayerSet_GlazingLayerSet_CurtainWall // const SimMaterialLayerSet_GlazingLayerSet_CurtainWall::T24AssmContext_optional& SimMaterialLayerSet_GlazingLayerSet_CurtainWall:: T24AssmContext () const { return this->T24AssmContext_; } SimMaterialLayerSet_GlazingLayerSet_CurtainWall::T24AssmContext_optional& SimMaterialLayerSet_GlazingLayerSet_CurtainWall:: T24AssmContext () { return this->T24AssmContext_; } void SimMaterialLayerSet_GlazingLayerSet_CurtainWall:: T24AssmContext (const T24AssmContext_type& x) { this->T24AssmContext_.set (x); } void SimMaterialLayerSet_GlazingLayerSet_CurtainWall:: T24AssmContext (const T24AssmContext_optional& x) { this->T24AssmContext_ = x; } void SimMaterialLayerSet_GlazingLayerSet_CurtainWall:: T24AssmContext (::std::auto_ptr< T24AssmContext_type > x) { this->T24AssmContext_.set (x); } const SimMaterialLayerSet_GlazingLayerSet_CurtainWall::T24FenestraCertMethod_optional& SimMaterialLayerSet_GlazingLayerSet_CurtainWall:: T24FenestraCertMethod () const { return this->T24FenestraCertMethod_; } SimMaterialLayerSet_GlazingLayerSet_CurtainWall::T24FenestraCertMethod_optional& SimMaterialLayerSet_GlazingLayerSet_CurtainWall:: T24FenestraCertMethod () { return this->T24FenestraCertMethod_; } void SimMaterialLayerSet_GlazingLayerSet_CurtainWall:: T24FenestraCertMethod (const T24FenestraCertMethod_type& x) { this->T24FenestraCertMethod_.set (x); } void SimMaterialLayerSet_GlazingLayerSet_CurtainWall:: T24FenestraCertMethod (const T24FenestraCertMethod_optional& x) { this->T24FenestraCertMethod_ = x; } void SimMaterialLayerSet_GlazingLayerSet_CurtainWall:: T24FenestraCertMethod (::std::auto_ptr< T24FenestraCertMethod_type > x) { this->T24FenestraCertMethod_.set (x); } const SimMaterialLayerSet_GlazingLayerSet_CurtainWall::T24Diffusing_optional& SimMaterialLayerSet_GlazingLayerSet_CurtainWall:: T24Diffusing () const { return this->T24Diffusing_; } SimMaterialLayerSet_GlazingLayerSet_CurtainWall::T24Diffusing_optional& SimMaterialLayerSet_GlazingLayerSet_CurtainWall:: T24Diffusing () { return this->T24Diffusing_; } void SimMaterialLayerSet_GlazingLayerSet_CurtainWall:: T24Diffusing (const T24Diffusing_type& x) { this->T24Diffusing_.set (x); } void SimMaterialLayerSet_GlazingLayerSet_CurtainWall:: T24Diffusing (const T24Diffusing_optional& x) { this->T24Diffusing_ = x; } const SimMaterialLayerSet_GlazingLayerSet_CurtainWall::T24FenestraFrame_optional& SimMaterialLayerSet_GlazingLayerSet_CurtainWall:: T24FenestraFrame () const { return this->T24FenestraFrame_; } SimMaterialLayerSet_GlazingLayerSet_CurtainWall::T24FenestraFrame_optional& SimMaterialLayerSet_GlazingLayerSet_CurtainWall:: T24FenestraFrame () { return this->T24FenestraFrame_; } void SimMaterialLayerSet_GlazingLayerSet_CurtainWall:: T24FenestraFrame (const T24FenestraFrame_type& x) { this->T24FenestraFrame_.set (x); } void SimMaterialLayerSet_GlazingLayerSet_CurtainWall:: T24FenestraFrame (const T24FenestraFrame_optional& x) { this->T24FenestraFrame_ = x; } void SimMaterialLayerSet_GlazingLayerSet_CurtainWall:: T24FenestraFrame (::std::auto_ptr< T24FenestraFrame_type > x) { this->T24FenestraFrame_.set (x); } const SimMaterialLayerSet_GlazingLayerSet_CurtainWall::T24FenestraPanes_optional& SimMaterialLayerSet_GlazingLayerSet_CurtainWall:: T24FenestraPanes () const { return this->T24FenestraPanes_; } SimMaterialLayerSet_GlazingLayerSet_CurtainWall::T24FenestraPanes_optional& SimMaterialLayerSet_GlazingLayerSet_CurtainWall:: T24FenestraPanes () { return this->T24FenestraPanes_; } void SimMaterialLayerSet_GlazingLayerSet_CurtainWall:: T24FenestraPanes (const T24FenestraPanes_type& x) { this->T24FenestraPanes_.set (x); } void SimMaterialLayerSet_GlazingLayerSet_CurtainWall:: T24FenestraPanes (const T24FenestraPanes_optional& x) { this->T24FenestraPanes_ = x; } void SimMaterialLayerSet_GlazingLayerSet_CurtainWall:: T24FenestraPanes (::std::auto_ptr< T24FenestraPanes_type > x) { this->T24FenestraPanes_.set (x); } const SimMaterialLayerSet_GlazingLayerSet_CurtainWall::T24FenestraProdType_optional& SimMaterialLayerSet_GlazingLayerSet_CurtainWall:: T24FenestraProdType () const { return this->T24FenestraProdType_; } SimMaterialLayerSet_GlazingLayerSet_CurtainWall::T24FenestraProdType_optional& SimMaterialLayerSet_GlazingLayerSet_CurtainWall:: T24FenestraProdType () { return this->T24FenestraProdType_; } void SimMaterialLayerSet_GlazingLayerSet_CurtainWall:: T24FenestraProdType (const T24FenestraProdType_type& x) { this->T24FenestraProdType_.set (x); } void SimMaterialLayerSet_GlazingLayerSet_CurtainWall:: T24FenestraProdType (const T24FenestraProdType_optional& x) { this->T24FenestraProdType_ = x; } void SimMaterialLayerSet_GlazingLayerSet_CurtainWall:: T24FenestraProdType (::std::auto_ptr< T24FenestraProdType_type > x) { this->T24FenestraProdType_.set (x); } const SimMaterialLayerSet_GlazingLayerSet_CurtainWall::T24FenestraTint_optional& SimMaterialLayerSet_GlazingLayerSet_CurtainWall:: T24FenestraTint () const { return this->T24FenestraTint_; } SimMaterialLayerSet_GlazingLayerSet_CurtainWall::T24FenestraTint_optional& SimMaterialLayerSet_GlazingLayerSet_CurtainWall:: T24FenestraTint () { return this->T24FenestraTint_; } void SimMaterialLayerSet_GlazingLayerSet_CurtainWall:: T24FenestraTint (const T24FenestraTint_type& x) { this->T24FenestraTint_.set (x); } void SimMaterialLayerSet_GlazingLayerSet_CurtainWall:: T24FenestraTint (const T24FenestraTint_optional& x) { this->T24FenestraTint_ = x; } void SimMaterialLayerSet_GlazingLayerSet_CurtainWall:: T24FenestraTint (::std::auto_ptr< T24FenestraTint_type > x) { this->T24FenestraTint_.set (x); } const SimMaterialLayerSet_GlazingLayerSet_CurtainWall::T24GreenhouseGardenWindow_optional& SimMaterialLayerSet_GlazingLayerSet_CurtainWall:: T24GreenhouseGardenWindow () const { return this->T24GreenhouseGardenWindow_; } SimMaterialLayerSet_GlazingLayerSet_CurtainWall::T24GreenhouseGardenWindow_optional& SimMaterialLayerSet_GlazingLayerSet_CurtainWall:: T24GreenhouseGardenWindow () { return this->T24GreenhouseGardenWindow_; } void SimMaterialLayerSet_GlazingLayerSet_CurtainWall:: T24GreenhouseGardenWindow (const T24GreenhouseGardenWindow_type& x) { this->T24GreenhouseGardenWindow_.set (x); } void SimMaterialLayerSet_GlazingLayerSet_CurtainWall:: T24GreenhouseGardenWindow (const T24GreenhouseGardenWindow_optional& x) { this->T24GreenhouseGardenWindow_ = x; } const SimMaterialLayerSet_GlazingLayerSet_CurtainWall::T24SHGCCenterOfGlass_optional& SimMaterialLayerSet_GlazingLayerSet_CurtainWall:: T24SHGCCenterOfGlass () const { return this->T24SHGCCenterOfGlass_; } SimMaterialLayerSet_GlazingLayerSet_CurtainWall::T24SHGCCenterOfGlass_optional& SimMaterialLayerSet_GlazingLayerSet_CurtainWall:: T24SHGCCenterOfGlass () { return this->T24SHGCCenterOfGlass_; } void SimMaterialLayerSet_GlazingLayerSet_CurtainWall:: T24SHGCCenterOfGlass (const T24SHGCCenterOfGlass_type& x) { this->T24SHGCCenterOfGlass_.set (x); } void SimMaterialLayerSet_GlazingLayerSet_CurtainWall:: T24SHGCCenterOfGlass (const T24SHGCCenterOfGlass_optional& x) { this->T24SHGCCenterOfGlass_ = x; } const SimMaterialLayerSet_GlazingLayerSet_CurtainWall::T24FenestraSkyltCurb_optional& SimMaterialLayerSet_GlazingLayerSet_CurtainWall:: T24FenestraSkyltCurb () const { return this->T24FenestraSkyltCurb_; } SimMaterialLayerSet_GlazingLayerSet_CurtainWall::T24FenestraSkyltCurb_optional& SimMaterialLayerSet_GlazingLayerSet_CurtainWall:: T24FenestraSkyltCurb () { return this->T24FenestraSkyltCurb_; } void SimMaterialLayerSet_GlazingLayerSet_CurtainWall:: T24FenestraSkyltCurb (const T24FenestraSkyltCurb_type& x) { this->T24FenestraSkyltCurb_.set (x); } void SimMaterialLayerSet_GlazingLayerSet_CurtainWall:: T24FenestraSkyltCurb (const T24FenestraSkyltCurb_optional& x) { this->T24FenestraSkyltCurb_ = x; } void SimMaterialLayerSet_GlazingLayerSet_CurtainWall:: T24FenestraSkyltCurb (::std::auto_ptr< T24FenestraSkyltCurb_type > x) { this->T24FenestraSkyltCurb_.set (x); } const SimMaterialLayerSet_GlazingLayerSet_CurtainWall::T24FenestraSkyltGlaze_optional& SimMaterialLayerSet_GlazingLayerSet_CurtainWall:: T24FenestraSkyltGlaze () const { return this->T24FenestraSkyltGlaze_; } SimMaterialLayerSet_GlazingLayerSet_CurtainWall::T24FenestraSkyltGlaze_optional& SimMaterialLayerSet_GlazingLayerSet_CurtainWall:: T24FenestraSkyltGlaze () { return this->T24FenestraSkyltGlaze_; } void SimMaterialLayerSet_GlazingLayerSet_CurtainWall:: T24FenestraSkyltGlaze (const T24FenestraSkyltGlaze_type& x) { this->T24FenestraSkyltGlaze_.set (x); } void SimMaterialLayerSet_GlazingLayerSet_CurtainWall:: T24FenestraSkyltGlaze (const T24FenestraSkyltGlaze_optional& x) { this->T24FenestraSkyltGlaze_ = x; } void SimMaterialLayerSet_GlazingLayerSet_CurtainWall:: T24FenestraSkyltGlaze (::std::auto_ptr< T24FenestraSkyltGlaze_type > x) { this->T24FenestraSkyltGlaze_.set (x); } } } } #include <xsd/cxx/xml/dom/parsing-source.hxx> #include <xsd/cxx/tree/type-factory-map.hxx> namespace _xsd { static const ::xsd::cxx::tree::type_factory_plate< 0, char > type_factory_plate_init; } namespace schema { namespace simxml { namespace ResourcesGeneral { // SimMaterialLayerSet_GlazingLayerSet_CurtainWall // SimMaterialLayerSet_GlazingLayerSet_CurtainWall:: SimMaterialLayerSet_GlazingLayerSet_CurtainWall () : ::schema::simxml::ResourcesGeneral::SimMaterialLayerSet_GlazingLayerSet (), T24AssmContext_ (this), T24FenestraCertMethod_ (this), T24Diffusing_ (this), T24FenestraFrame_ (this), T24FenestraPanes_ (this), T24FenestraProdType_ (this), T24FenestraTint_ (this), T24GreenhouseGardenWindow_ (this), T24SHGCCenterOfGlass_ (this), T24FenestraSkyltCurb_ (this), T24FenestraSkyltGlaze_ (this) { } SimMaterialLayerSet_GlazingLayerSet_CurtainWall:: SimMaterialLayerSet_GlazingLayerSet_CurtainWall (const RefId_type& RefId) : ::schema::simxml::ResourcesGeneral::SimMaterialLayerSet_GlazingLayerSet (RefId), T24AssmContext_ (this), T24FenestraCertMethod_ (this), T24Diffusing_ (this), T24FenestraFrame_ (this), T24FenestraPanes_ (this), T24FenestraProdType_ (this), T24FenestraTint_ (this), T24GreenhouseGardenWindow_ (this), T24SHGCCenterOfGlass_ (this), T24FenestraSkyltCurb_ (this), T24FenestraSkyltGlaze_ (this) { } SimMaterialLayerSet_GlazingLayerSet_CurtainWall:: SimMaterialLayerSet_GlazingLayerSet_CurtainWall (const SimMaterialLayerSet_GlazingLayerSet_CurtainWall& x, ::xml_schema::flags f, ::xml_schema::container* c) : ::schema::simxml::ResourcesGeneral::SimMaterialLayerSet_GlazingLayerSet (x, f, c), T24AssmContext_ (x.T24AssmContext_, f, this), T24FenestraCertMethod_ (x.T24FenestraCertMethod_, f, this), T24Diffusing_ (x.T24Diffusing_, f, this), T24FenestraFrame_ (x.T24FenestraFrame_, f, this), T24FenestraPanes_ (x.T24FenestraPanes_, f, this), T24FenestraProdType_ (x.T24FenestraProdType_, f, this), T24FenestraTint_ (x.T24FenestraTint_, f, this), T24GreenhouseGardenWindow_ (x.T24GreenhouseGardenWindow_, f, this), T24SHGCCenterOfGlass_ (x.T24SHGCCenterOfGlass_, f, this), T24FenestraSkyltCurb_ (x.T24FenestraSkyltCurb_, f, this), T24FenestraSkyltGlaze_ (x.T24FenestraSkyltGlaze_, f, this) { } SimMaterialLayerSet_GlazingLayerSet_CurtainWall:: SimMaterialLayerSet_GlazingLayerSet_CurtainWall (const ::xercesc::DOMElement& e, ::xml_schema::flags f, ::xml_schema::container* c) : ::schema::simxml::ResourcesGeneral::SimMaterialLayerSet_GlazingLayerSet (e, f | ::xml_schema::flags::base, c), T24AssmContext_ (this), T24FenestraCertMethod_ (this), T24Diffusing_ (this), T24FenestraFrame_ (this), T24FenestraPanes_ (this), T24FenestraProdType_ (this), T24FenestraTint_ (this), T24GreenhouseGardenWindow_ (this), T24SHGCCenterOfGlass_ (this), T24FenestraSkyltCurb_ (this), T24FenestraSkyltGlaze_ (this) { if ((f & ::xml_schema::flags::base) == 0) { ::xsd::cxx::xml::dom::parser< char > p (e, true, false, true); this->parse (p, f); } } void SimMaterialLayerSet_GlazingLayerSet_CurtainWall:: parse (::xsd::cxx::xml::dom::parser< char >& p, ::xml_schema::flags f) { this->::schema::simxml::ResourcesGeneral::SimMaterialLayerSet_GlazingLayerSet::parse (p, f); for (; p.more_content (); p.next_content (false)) { const ::xercesc::DOMElement& i (p.cur_element ()); const ::xsd::cxx::xml::qualified_name< char > n ( ::xsd::cxx::xml::dom::name< char > (i)); // T24AssmContext // if (n.name () == "T24AssmContext" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral") { ::std::auto_ptr< T24AssmContext_type > r ( T24AssmContext_traits::create (i, f, this)); if (!this->T24AssmContext_) { this->T24AssmContext_.set (r); continue; } } // T24FenestraCertMethod // if (n.name () == "T24FenestraCertMethod" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral") { ::std::auto_ptr< T24FenestraCertMethod_type > r ( T24FenestraCertMethod_traits::create (i, f, this)); if (!this->T24FenestraCertMethod_) { this->T24FenestraCertMethod_.set (r); continue; } } // T24Diffusing // if (n.name () == "T24Diffusing" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral") { if (!this->T24Diffusing_) { this->T24Diffusing_.set (T24Diffusing_traits::create (i, f, this)); continue; } } // T24FenestraFrame // if (n.name () == "T24FenestraFrame" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral") { ::std::auto_ptr< T24FenestraFrame_type > r ( T24FenestraFrame_traits::create (i, f, this)); if (!this->T24FenestraFrame_) { this->T24FenestraFrame_.set (r); continue; } } // T24FenestraPanes // if (n.name () == "T24FenestraPanes" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral") { ::std::auto_ptr< T24FenestraPanes_type > r ( T24FenestraPanes_traits::create (i, f, this)); if (!this->T24FenestraPanes_) { this->T24FenestraPanes_.set (r); continue; } } // T24FenestraProdType // if (n.name () == "T24FenestraProdType" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral") { ::std::auto_ptr< T24FenestraProdType_type > r ( T24FenestraProdType_traits::create (i, f, this)); if (!this->T24FenestraProdType_) { this->T24FenestraProdType_.set (r); continue; } } // T24FenestraTint // if (n.name () == "T24FenestraTint" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral") { ::std::auto_ptr< T24FenestraTint_type > r ( T24FenestraTint_traits::create (i, f, this)); if (!this->T24FenestraTint_) { this->T24FenestraTint_.set (r); continue; } } // T24GreenhouseGardenWindow // if (n.name () == "T24GreenhouseGardenWindow" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral") { if (!this->T24GreenhouseGardenWindow_) { this->T24GreenhouseGardenWindow_.set (T24GreenhouseGardenWindow_traits::create (i, f, this)); continue; } } // T24SHGCCenterOfGlass // if (n.name () == "T24SHGCCenterOfGlass" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral") { if (!this->T24SHGCCenterOfGlass_) { this->T24SHGCCenterOfGlass_.set (T24SHGCCenterOfGlass_traits::create (i, f, this)); continue; } } // T24FenestraSkyltCurb // if (n.name () == "T24FenestraSkyltCurb" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral") { ::std::auto_ptr< T24FenestraSkyltCurb_type > r ( T24FenestraSkyltCurb_traits::create (i, f, this)); if (!this->T24FenestraSkyltCurb_) { this->T24FenestraSkyltCurb_.set (r); continue; } } // T24FenestraSkyltGlaze // if (n.name () == "T24FenestraSkyltGlaze" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral") { ::std::auto_ptr< T24FenestraSkyltGlaze_type > r ( T24FenestraSkyltGlaze_traits::create (i, f, this)); if (!this->T24FenestraSkyltGlaze_) { this->T24FenestraSkyltGlaze_.set (r); continue; } } break; } } SimMaterialLayerSet_GlazingLayerSet_CurtainWall* SimMaterialLayerSet_GlazingLayerSet_CurtainWall:: _clone (::xml_schema::flags f, ::xml_schema::container* c) const { return new class SimMaterialLayerSet_GlazingLayerSet_CurtainWall (*this, f, c); } SimMaterialLayerSet_GlazingLayerSet_CurtainWall& SimMaterialLayerSet_GlazingLayerSet_CurtainWall:: operator= (const SimMaterialLayerSet_GlazingLayerSet_CurtainWall& x) { if (this != &x) { static_cast< ::schema::simxml::ResourcesGeneral::SimMaterialLayerSet_GlazingLayerSet& > (*this) = x; this->T24AssmContext_ = x.T24AssmContext_; this->T24FenestraCertMethod_ = x.T24FenestraCertMethod_; this->T24Diffusing_ = x.T24Diffusing_; this->T24FenestraFrame_ = x.T24FenestraFrame_; this->T24FenestraPanes_ = x.T24FenestraPanes_; this->T24FenestraProdType_ = x.T24FenestraProdType_; this->T24FenestraTint_ = x.T24FenestraTint_; this->T24GreenhouseGardenWindow_ = x.T24GreenhouseGardenWindow_; this->T24SHGCCenterOfGlass_ = x.T24SHGCCenterOfGlass_; this->T24FenestraSkyltCurb_ = x.T24FenestraSkyltCurb_; this->T24FenestraSkyltGlaze_ = x.T24FenestraSkyltGlaze_; } return *this; } SimMaterialLayerSet_GlazingLayerSet_CurtainWall:: ~SimMaterialLayerSet_GlazingLayerSet_CurtainWall () { } } } } #include <istream> #include <xsd/cxx/xml/sax/std-input-source.hxx> #include <xsd/cxx/tree/error-handler.hxx> namespace schema { namespace simxml { namespace ResourcesGeneral { } } } #include <xsd/cxx/post.hxx> // Begin epilogue. // // // End epilogue.
[ "PRemmen@eonerc.rwth-aachen.de" ]
PRemmen@eonerc.rwth-aachen.de
63314a87aae5cee2a073d6d962c909b061fbfa4a
7eaf2de685952a6b7a5dbed790ef1bd08bceb905
/inc/analyzer.h
e819ad81618e7542f6c657427630ebe24d346f6b
[]
no_license
lynnkse/TreeEx
050241c9718336c4bcfa73199fa9a46d64e51024
ab9eb18b540da7d47366782e35516e4508a7a327
refs/heads/master
2021-01-24T01:59:16.444226
2018-02-25T12:24:49
2018-02-25T12:24:49
122,829,846
0
0
null
null
null
null
UTF-8
C++
false
false
238
h
#ifndef ANALYZER #define ANALYZER #include <vector> class Analyzer { public: explicit Analyzer(size_t _n); size_t GetResult(const Node * const _tree); private: const size_t N; std::vector<int> vec; }; #endif //ANALYZER
[ "lynnkse@gmail.com" ]
lynnkse@gmail.com
d98724fc932408e454f2ed80e1b304e27b478bdd
ad95c7ce4f523f0fa7bcb145955a7081caee5dc6
/duilib2/src/Controls/Button.cpp
c714b84b61072f48bdea203d8d0eb979b108001e
[ "MIT" ]
permissive
w1146869587/DuilibEditor
c369ce9c43cf1eabd4077c9996dec746e7f4c790
b23c1f362a1e691e2101b1d5b8642639a349b540
refs/heads/master
2021-06-17T04:34:50.164429
2017-02-16T14:59:08
2017-02-16T14:59:08
111,431,048
1
0
null
2017-11-20T15:51:49
2017-11-20T15:51:49
null
UTF-8
C++
false
false
2,053
cpp
#include <Controls/Button.h> namespace duilib2 { static String gButtonProperties[][3] = { // name value type {"normalimage", "", "Image"}, {"hotimage", "", "Image"}, {"pushedimage", "", "Image"}, {"focusedimage", "", "Image"}, {"disabledimage", "", "Image"}, {"hottextcolor", "0x00000000", "Color"}, {"pushedtextcolor", "0x00000000", "Color"}, {"focusedtextcolor", "0x00000000", "Color"}, {"", "", ""} }; String Button::sTypeName = "Button"; Button::Button(const String& name) : Label(name) , mButtonStatus(BS_NORMAL) { String* property = &gButtonProperties[0][0]; while (!property->isEmpty()) { addProperty(property[0], property[1], property[2]); property += 3; } } Button::~Button() { } String Button::getType() const { return sTypeName; } int Button::getWidth() const { return 0; } int Button::getHeight() const { return 0; } Point Button::getPosition() const { return Point(); } void Button::drawStatusImage(RenderSystem* rs) { String propertyName; switch (mButtonStatus) { case BS_NORMAL: propertyName = "normalimage"; break; case BS_HOT: propertyName = "hotimage"; break; case BS_PUSHED: propertyName = "pushedimage"; break; case BS_FOCUSED: propertyName = "focusedimage"; break; case BS_DISABLE: propertyName = "disabledimage"; break; default: return; } Image image = getProperty(propertyName).getAnyValue<Image>(); // rs->drawImage(x, y, width, height); } void Button::drawText(RenderSystem* rs) { } ButtonFactory::ButtonFactory() { } ButtonFactory::~ButtonFactory() { } String ButtonFactory::getType() const { return String("Button"); } Window* ButtonFactory::createInstance(const String& name) { return new Button(name); } void ButtonFactory::destroyInstance(Window* window) { delete window; } } // namespace duilib2
[ "761225349@qq.com" ]
761225349@qq.com
17fd1eb5095013466ce6e76ccc8cc92c1432b80a
b33a9177edaaf6bf185ef20bf87d36eada719d4f
/qtbase/src/gui/painting/qoutlinemapper.cpp
84061a5c2524a4a30dccaa0f8ae6e1443cab3b50
[ "LicenseRef-scancode-proprietary-license", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-commercial-license", "LGPL-2.0-or-later", "LGPL-2.1-only", "GFDL-1.3-only", "LicenseRef-scancode-qt-commercial-1.1", "LGPL-3.0-only", "LicenseRef-scancode-qt-company-exception-lgpl-2.1", ...
permissive
wgnet/wds_qt
ab8c093b8c6eead9adf4057d843e00f04915d987
8db722fd367d2d0744decf99ac7bafaba8b8a3d3
refs/heads/master
2021-04-02T11:07:10.181067
2020-06-02T10:29:03
2020-06-02T10:34:19
248,267,925
1
0
Apache-2.0
2020-04-30T12:16:53
2020-03-18T15:20:38
null
UTF-8
C++
false
false
13,242
cpp
/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing/ ** ** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL21$ ** 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 http://www.qt.io/terms-conditions. For further ** information use the contact form at http://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 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** As a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qoutlinemapper_p.h" #include <private/qpainterpath_p.h> #include "qmath.h" #include <private/qbezier_p.h> #include <stdlib.h> QT_BEGIN_NAMESPACE #define qreal_to_fixed_26_6(f) (qRound(f * 64)) static const QRectF boundingRect(const QPointF *points, int pointCount) { const QPointF *e = points; const QPointF *last = points + pointCount; qreal minx, maxx, miny, maxy; minx = maxx = e->x(); miny = maxy = e->y(); while (++e < last) { if (e->x() < minx) minx = e->x(); else if (e->x() > maxx) maxx = e->x(); if (e->y() < miny) miny = e->y(); else if (e->y() > maxy) maxy = e->y(); } return QRectF(QPointF(minx, miny), QPointF(maxx, maxy)); } void QOutlineMapper::curveTo(const QPointF &cp1, const QPointF &cp2, const QPointF &ep) { #ifdef QT_DEBUG_CONVERT printf("QOutlineMapper::curveTo() (%f, %f)\n", ep.x(), ep.y()); #endif QBezier bezier = QBezier::fromPoints(m_elements.last(), cp1, cp2, ep); bezier.addToPolygon(m_elements, m_curve_threshold); m_element_types.reserve(m_elements.size()); for (int i = m_elements.size() - m_element_types.size(); i; --i) m_element_types << QPainterPath::LineToElement; Q_ASSERT(m_elements.size() == m_element_types.size()); } QT_FT_Outline *QOutlineMapper::convertPath(const QPainterPath &path) { Q_ASSERT(!path.isEmpty()); int elmCount = path.elementCount(); #ifdef QT_DEBUG_CONVERT printf("QOutlineMapper::convertPath(), size=%d\n", elmCount); #endif beginOutline(path.fillRule()); for (int index=0; index<elmCount; ++index) { const QPainterPath::Element &elm = path.elementAt(index); switch (elm.type) { case QPainterPath::MoveToElement: if (index == elmCount - 1) continue; moveTo(elm); break; case QPainterPath::LineToElement: lineTo(elm); break; case QPainterPath::CurveToElement: curveTo(elm, path.elementAt(index + 1), path.elementAt(index + 2)); index += 2; break; default: break; // This will never hit.. } } endOutline(); return outline(); } QT_FT_Outline *QOutlineMapper::convertPath(const QVectorPath &path) { int count = path.elementCount(); #ifdef QT_DEBUG_CONVERT printf("QOutlineMapper::convertPath(VP), size=%d\n", count); #endif beginOutline(path.hasWindingFill() ? Qt::WindingFill : Qt::OddEvenFill); if (path.elements()) { // TODO: if we do closing of subpaths in convertElements instead we // could avoid this loop const QPainterPath::ElementType *elements = path.elements(); const QPointF *points = reinterpret_cast<const QPointF *>(path.points()); for (int index = 0; index < count; ++index) { switch (elements[index]) { case QPainterPath::MoveToElement: if (index == count - 1) continue; moveTo(points[index]); break; case QPainterPath::LineToElement: lineTo(points[index]); break; case QPainterPath::CurveToElement: curveTo(points[index], points[index+1], points[index+2]); index += 2; break; default: break; // This will never hit.. } } } else { // ### We can kill this copying and just use the buffer straight... m_elements.resize(count); if (count) memcpy(m_elements.data(), path.points(), count* sizeof(QPointF)); m_element_types.resize(0); } endOutline(); return outline(); } void QOutlineMapper::endOutline() { closeSubpath(); if (m_elements.isEmpty()) { memset(&m_outline, 0, sizeof(m_outline)); return; } QPointF *elements = m_elements.data(); // Transform the outline if (m_txop == QTransform::TxNone) { // Nothing to do. } else if (m_txop == QTransform::TxTranslate) { for (int i = 0; i < m_elements.size(); ++i) { QPointF &e = elements[i]; e = QPointF(e.x() + m_dx, e.y() + m_dy); } } else if (m_txop == QTransform::TxScale) { for (int i = 0; i < m_elements.size(); ++i) { QPointF &e = elements[i]; e = QPointF(m_m11 * e.x() + m_dx, m_m22 * e.y() + m_dy); } } else if (m_txop < QTransform::TxProject) { for (int i = 0; i < m_elements.size(); ++i) { QPointF &e = elements[i]; e = QPointF(m_m11 * e.x() + m_m21 * e.y() + m_dx, m_m22 * e.y() + m_m12 * e.x() + m_dy); } } else { const QVectorPath vp((qreal *)elements, m_elements.size(), m_element_types.size() ? m_element_types.data() : 0); QPainterPath path = vp.convertToPainterPath(); path = QTransform(m_m11, m_m12, m_m13, m_m21, m_m22, m_m23, m_dx, m_dy, m_m33).map(path); if (!(m_outline.flags & QT_FT_OUTLINE_EVEN_ODD_FILL)) path.setFillRule(Qt::WindingFill); uint old_txop = m_txop; m_txop = QTransform::TxNone; if (path.isEmpty()) m_valid = false; else convertPath(path); m_txop = old_txop; return; } controlPointRect = boundingRect(elements, m_elements.size()); #ifdef QT_DEBUG_CONVERT printf(" - control point rect (%.2f, %.2f) %.2f x %.2f, clip=(%d,%d, %dx%d)\n", controlPointRect.x(), controlPointRect.y(), controlPointRect.width(), controlPointRect.height(), m_clip_rect.x(), m_clip_rect.y(), m_clip_rect.width(), m_clip_rect.height()); #endif // Check for out of dev bounds... const bool do_clip = !m_in_clip_elements && ((controlPointRect.left() < -QT_RASTER_COORD_LIMIT || controlPointRect.right() > QT_RASTER_COORD_LIMIT || controlPointRect.top() < -QT_RASTER_COORD_LIMIT || controlPointRect.bottom() > QT_RASTER_COORD_LIMIT || controlPointRect.width() > QT_RASTER_COORD_LIMIT || controlPointRect.height() > QT_RASTER_COORD_LIMIT)); if (do_clip) { clipElements(elements, elementTypes(), m_elements.size()); } else { convertElements(elements, elementTypes(), m_elements.size()); } } void QOutlineMapper::convertElements(const QPointF *elements, const QPainterPath::ElementType *types, int element_count) { if (types) { // Translate into FT coords const QPointF *e = elements; for (int i=0; i<element_count; ++i) { switch (*types) { case QPainterPath::MoveToElement: { QT_FT_Vector pt_fixed = { qreal_to_fixed_26_6(e->x()), qreal_to_fixed_26_6(e->y()) }; if (i != 0) m_contours << m_points.size() - 1; m_points << pt_fixed; m_tags << QT_FT_CURVE_TAG_ON; } break; case QPainterPath::LineToElement: { QT_FT_Vector pt_fixed = { qreal_to_fixed_26_6(e->x()), qreal_to_fixed_26_6(e->y()) }; m_points << pt_fixed; m_tags << QT_FT_CURVE_TAG_ON; } break; case QPainterPath::CurveToElement: { QT_FT_Vector cp1_fixed = { qreal_to_fixed_26_6(e->x()), qreal_to_fixed_26_6(e->y()) }; ++e; QT_FT_Vector cp2_fixed = { qreal_to_fixed_26_6((e)->x()), qreal_to_fixed_26_6((e)->y()) }; ++e; QT_FT_Vector ep_fixed = { qreal_to_fixed_26_6((e)->x()), qreal_to_fixed_26_6((e)->y()) }; m_points << cp1_fixed << cp2_fixed << ep_fixed; m_tags << QT_FT_CURVE_TAG_CUBIC << QT_FT_CURVE_TAG_CUBIC << QT_FT_CURVE_TAG_ON; types += 2; i += 2; } break; default: break; } ++types; ++e; } } else { // Plain polygon... const QPointF *last = elements + element_count; const QPointF *e = elements; while (e < last) { QT_FT_Vector pt_fixed = { qreal_to_fixed_26_6(e->x()), qreal_to_fixed_26_6(e->y()) }; m_points << pt_fixed; m_tags << QT_FT_CURVE_TAG_ON; ++e; } } // close the very last subpath m_contours << m_points.size() - 1; m_outline.n_contours = m_contours.size(); m_outline.n_points = m_points.size(); m_outline.points = m_points.data(); m_outline.tags = m_tags.data(); m_outline.contours = m_contours.data(); #ifdef QT_DEBUG_CONVERT printf("QOutlineMapper::endOutline\n"); printf(" - contours: %d\n", m_outline.n_contours); for (int i=0; i<m_outline.n_contours; ++i) { printf(" - %d\n", m_outline.contours[i]); } printf(" - points: %d\n", m_outline.n_points); for (int i=0; i<m_outline.n_points; ++i) { printf(" - %d -- %.2f, %.2f, (%d, %d)\n", i, (double) (m_outline.points[i].x / 64.0), (double) (m_outline.points[i].y / 64.0), (int) m_outline.points[i].x, (int) m_outline.points[i].y); } #endif } void QOutlineMapper::clipElements(const QPointF *elements, const QPainterPath::ElementType *types, int element_count) { // We could save a bit of time by actually implementing them fully // instead of going through convenience functionallity, but since // this part of code hardly every used, it shouldn't matter. m_in_clip_elements = true; QPainterPath path; if (!(m_outline.flags & QT_FT_OUTLINE_EVEN_ODD_FILL)) path.setFillRule(Qt::WindingFill); if (types) { for (int i=0; i<element_count; ++i) { switch (types[i]) { case QPainterPath::MoveToElement: path.moveTo(elements[i]); break; case QPainterPath::LineToElement: path.lineTo(elements[i]); break; case QPainterPath::CurveToElement: path.cubicTo(elements[i], elements[i+1], elements[i+2]); i += 2; break; default: break; } } } else { path.moveTo(elements[0]); for (int i=1; i<element_count; ++i) path.lineTo(elements[i]); } QPainterPath clipPath; clipPath.addRect(m_clip_rect); QPainterPath clippedPath = path.intersected(clipPath); uint old_txop = m_txop; m_txop = QTransform::TxNone; if (clippedPath.isEmpty()) m_valid = false; else convertPath(clippedPath); m_txop = old_txop; m_in_clip_elements = false; } QT_END_NAMESPACE
[ "p_pavlov@wargaming.net" ]
p_pavlov@wargaming.net
b35e784a92e0f390fbe6f41db53822a257505179
dd6b6da760c32ac6830c52aa2f4d5cce17e4d408
/magma-2.5.0/sparse/src/zpbicgstab.cpp
613ecdd554597bf8e2f5e79b22770f6c440bce46
[]
no_license
uumami/hit_and_run
81584b4f68cf25a2a1140baa3ee88f9e1844b672
dfda812a52bbd65e02753b9abcb9f54aeb4e8184
refs/heads/master
2023-03-13T16:48:37.975390
2023-02-28T05:04:58
2023-02-28T05:04:58
139,909,134
1
0
null
null
null
null
UTF-8
C++
false
false
8,802
cpp
/* -- MAGMA (version 2.5.0) -- Univ. of Tennessee, Knoxville Univ. of California, Berkeley Univ. of Colorado, Denver @date January 2019 @precisions normal z -> s d c @author Hartwig Anzt */ #include "magmasparse_internal.h" #define RTOLERANCE lapackf77_dlamch( "E" ) #define ATOLERANCE lapackf77_dlamch( "E" ) /** Purpose ------- Solves a system of linear equations A * X = B where A is a complex N-by-N general matrix. This is a GPU implementation of the preconditioned Biconjugate Gradient Stabelized method. Arguments --------- @param[in] A magma_z_matrix input matrix A @param[in] b magma_z_matrix RHS b @param[in,out] x magma_z_matrix* solution approximation @param[in,out] solver_par magma_z_solver_par* solver parameters @param[in] precond_par magma_z_preconditioner* preconditioner parameters @param[in] queue magma_queue_t Queue to execute in. @ingroup magmasparse_zgesv ********************************************************************/ extern "C" magma_int_t magma_zpbicgstab( magma_z_matrix A, magma_z_matrix b, magma_z_matrix *x, magma_z_solver_par *solver_par, magma_z_preconditioner *precond_par, magma_queue_t queue ) { magma_int_t info = MAGMA_NOTCONVERGED; // prepare solver feedback solver_par->solver = Magma_PBICGSTAB; solver_par->numiter = 0; solver_par->spmv_count = 0; // some useful variables magmaDoubleComplex c_zero = MAGMA_Z_ZERO; magmaDoubleComplex c_one = MAGMA_Z_ONE; magmaDoubleComplex c_neg_one = MAGMA_Z_NEG_ONE; magma_int_t dofs = A.num_rows*b.num_cols; // workspace magma_z_matrix r={Magma_CSR}, rr={Magma_CSR}, p={Magma_CSR}, v={Magma_CSR}, s={Magma_CSR}, t={Magma_CSR}, ms={Magma_CSR}, mt={Magma_CSR}, y={Magma_CSR}, z={Magma_CSR}; CHECK( magma_zvinit( &r, Magma_DEV, A.num_rows, b.num_cols, c_zero, queue )); CHECK( magma_zvinit( &rr,Magma_DEV, A.num_rows, b.num_cols, c_zero, queue )); CHECK( magma_zvinit( &p, Magma_DEV, A.num_rows, b.num_cols, c_zero, queue )); CHECK( magma_zvinit( &v, Magma_DEV, A.num_rows, b.num_cols, c_zero, queue )); CHECK( magma_zvinit( &s, Magma_DEV, A.num_rows, b.num_cols, c_zero, queue )); CHECK( magma_zvinit( &t, Magma_DEV, A.num_rows, b.num_cols, c_zero, queue )); CHECK( magma_zvinit( &ms,Magma_DEV, A.num_rows, b.num_cols, c_zero, queue )); CHECK( magma_zvinit( &mt,Magma_DEV, A.num_rows, b.num_cols, c_zero, queue )); CHECK( magma_zvinit( &y, Magma_DEV, A.num_rows, b.num_cols, c_zero, queue )); CHECK( magma_zvinit( &z, Magma_DEV, A.num_rows, b.num_cols, c_zero, queue )); // solver variables magmaDoubleComplex alpha, beta, omega, rho_old, rho_new; double betanom, nom0, r0, res, nomb; res=0; //double den; // solver setup CHECK( magma_zresidualvec( A, b, *x, &r, &nom0, queue)); magma_zcopy( dofs, r.dval, 1, rr.dval, 1, queue ); // rr = r betanom = nom0; rho_new = omega = alpha = MAGMA_Z_MAKE( 1.0, 0. ); solver_par->init_res = nom0; nomb = magma_dznrm2( dofs, b.dval, 1, queue ); if ( nomb == 0.0 ){ nomb=1.0; } if ( (r0 = nomb * solver_par->rtol) < ATOLERANCE ){ r0 = ATOLERANCE; } solver_par->final_res = solver_par->init_res; solver_par->iter_res = solver_par->init_res; if ( solver_par->verbose > 0 ) { solver_par->res_vec[0] = nom0; solver_par->timing[0] = 0.0; } if ( nomb < r0 ) { info = MAGMA_SUCCESS; goto cleanup; } //Chronometry real_Double_t tempo1, tempo2; tempo1 = magma_sync_wtime( queue ); solver_par->numiter = 0; solver_par->spmv_count = 0; // start iteration do { solver_par->numiter++; rho_old = rho_new; // rho_old=rho rho_new = magma_zdotc( dofs, rr.dval, 1, r.dval, 1, queue ); // rho=<rr,r> beta = rho_new/rho_old * alpha/omega; // beta=rho/rho_old *alpha/omega if( magma_z_isnan_inf( beta ) ){ info = MAGMA_DIVERGENCE; break; } magma_zscal( dofs, beta, p.dval, 1, queue ); // p = beta*p magma_zaxpy( dofs, c_neg_one * omega * beta, v.dval, 1 , p.dval, 1, queue ); // p = p-omega*beta*v magma_zaxpy( dofs, c_one, r.dval, 1, p.dval, 1, queue ); // p = p+r // preconditioner CHECK( magma_z_applyprecond_left( MagmaNoTrans, A, p, &mt, precond_par, queue )); CHECK( magma_z_applyprecond_right( MagmaNoTrans, A, mt, &y, precond_par, queue )); CHECK( magma_z_spmv( c_one, A, y, c_zero, v, queue )); // v = Ap solver_par->spmv_count++; alpha = rho_new / magma_zdotc( dofs, rr.dval, 1, v.dval, 1, queue ); if( magma_z_isnan_inf( alpha ) ){ info = MAGMA_DIVERGENCE; break; } magma_zcopy( dofs, r.dval, 1 , s.dval, 1, queue ); // s=r magma_zaxpy( dofs, c_neg_one * alpha, v.dval, 1 , s.dval, 1, queue ); // s=s-alpha*v // preconditioner CHECK( magma_z_applyprecond_left( MagmaNoTrans, A, s, &ms, precond_par, queue )); CHECK( magma_z_applyprecond_right( MagmaNoTrans, A, ms, &z, precond_par, queue )); CHECK( magma_z_spmv( c_one, A, z, c_zero, t, queue )); // t=As solver_par->spmv_count++; // omega = <s,t>/<t,t> omega = magma_zdotc( dofs, t.dval, 1, s.dval, 1, queue ) / magma_zdotc( dofs, t.dval, 1, t.dval, 1, queue ); magma_zaxpy( dofs, alpha, y.dval, 1 , x->dval, 1, queue ); // x=x+alpha*p magma_zaxpy( dofs, omega, z.dval, 1 , x->dval, 1, queue ); // x=x+omega*s magma_zcopy( dofs, s.dval, 1 , r.dval, 1, queue ); // r=s magma_zaxpy( dofs, c_neg_one * omega, t.dval, 1 , r.dval, 1, queue ); // r=r-omega*t res = betanom = magma_dznrm2( dofs, r.dval, 1, queue ); if ( solver_par->verbose > 0 ) { tempo2 = magma_sync_wtime( queue ); if ( (solver_par->numiter)%solver_par->verbose==0 ) { solver_par->res_vec[(solver_par->numiter)/solver_par->verbose] = (real_Double_t) res; solver_par->timing[(solver_par->numiter)/solver_par->verbose] = (real_Double_t) tempo2-tempo1; } } if ( res/nomb <= solver_par->rtol || res <= solver_par->atol ){ break; } } while ( solver_par->numiter+1 <= solver_par->maxiter ); tempo2 = magma_sync_wtime( queue ); solver_par->runtime = (real_Double_t) tempo2-tempo1; double residual; CHECK( magma_zresidualvec( A, b, *x, &r, &residual, queue)); solver_par->final_res = residual; solver_par->iter_res = res; if ( solver_par->numiter < solver_par->maxiter && info == MAGMA_SUCCESS ) { info = MAGMA_SUCCESS; } else if ( solver_par->init_res > solver_par->final_res ) { if ( solver_par->verbose > 0 ) { if ( (solver_par->numiter)%solver_par->verbose==0 ) { solver_par->res_vec[(solver_par->numiter)/solver_par->verbose] = (real_Double_t) betanom; solver_par->timing[(solver_par->numiter)/solver_par->verbose] = (real_Double_t) tempo2-tempo1; } } info = MAGMA_SLOW_CONVERGENCE; if( solver_par->iter_res < solver_par->rtol*nomb || solver_par->iter_res < solver_par->atol ) { info = MAGMA_SUCCESS; } } else { if ( solver_par->verbose > 0 ) { if ( (solver_par->numiter)%solver_par->verbose==0 ) { solver_par->res_vec[(solver_par->numiter)/solver_par->verbose] = (real_Double_t) betanom; solver_par->timing[(solver_par->numiter)/solver_par->verbose] = (real_Double_t) tempo2-tempo1; } } info = MAGMA_DIVERGENCE; } cleanup: magma_zmfree(&r, queue ); magma_zmfree(&rr, queue ); magma_zmfree(&p, queue ); magma_zmfree(&v, queue ); magma_zmfree(&s, queue ); magma_zmfree(&t, queue ); magma_zmfree(&ms, queue ); magma_zmfree(&mt, queue ); magma_zmfree(&y, queue ); magma_zmfree(&z, queue ); solver_par->info = info; return info; } /* magma_zbicgstab */
[ "vazcorm@gmail.com" ]
vazcorm@gmail.com
55c9fd8f270339a808fc136c461f5a987a209f03
2f45b99b684f62b2e9413a302a22a7677c22580c
/frameworks/native/libs/gui/Surface.cpp
d7590f013c14af0264f58c451109be3256d8c519
[ "LicenseRef-scancode-unicode", "Apache-2.0" ]
permissive
b2gdev/Android-JB-4.1.2
05e15a4668781cd9c9f63a1fa96bf08d9bdf91de
e66aea986bbf29ff70e5ec4440504ca24f8104e1
refs/heads/user
2020-04-06T05:44:17.217452
2018-04-13T15:43:57
2018-04-13T15:43:57
35,256,753
3
12
null
2020-03-09T00:08:24
2015-05-08T03:32:21
null
UTF-8
C++
false
false
12,308
cpp
/* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #define LOG_TAG "Surface" #include <stdint.h> #include <errno.h> #include <sys/types.h> #include <sys/stat.h> #include <android/native_window.h> #include <utils/CallStack.h> #include <utils/Errors.h> #include <utils/Log.h> #include <utils/threads.h> #include <binder/IPCThreadState.h> #include <ui/DisplayInfo.h> #include <ui/GraphicBuffer.h> #include <ui/Rect.h> #include <gui/ISurface.h> #include <gui/ISurfaceComposer.h> #include <gui/Surface.h> #include <gui/SurfaceComposerClient.h> #include <gui/SurfaceTextureClient.h> namespace android { // ============================================================================ // SurfaceControl // ============================================================================ SurfaceControl::SurfaceControl( const sp<SurfaceComposerClient>& client, const sp<ISurface>& surface, const ISurfaceComposerClient::surface_data_t& data) : mClient(client), mSurface(surface), mToken(data.token), mIdentity(data.identity) { } SurfaceControl::~SurfaceControl() { destroy(); } void SurfaceControl::destroy() { if (isValid()) { mClient->destroySurface(mToken); } // clear all references and trigger an IPC now, to make sure things // happen without delay, since these resources are quite heavy. mClient.clear(); mSurface.clear(); IPCThreadState::self()->flushCommands(); } void SurfaceControl::clear() { // here, the window manager tells us explicitly that we should destroy // the surface's resource. Soon after this call, it will also release // its last reference (which will call the dtor); however, it is possible // that a client living in the same process still holds references which // would delay the call to the dtor -- that is why we need this explicit // "clear()" call. destroy(); } bool SurfaceControl::isSameSurface( const sp<SurfaceControl>& lhs, const sp<SurfaceControl>& rhs) { if (lhs == 0 || rhs == 0) return false; return lhs->mSurface->asBinder() == rhs->mSurface->asBinder(); } status_t SurfaceControl::setLayer(int32_t layer) { status_t err = validate(); if (err < 0) return err; const sp<SurfaceComposerClient>& client(mClient); return client->setLayer(mToken, layer); } status_t SurfaceControl::setPosition(int32_t x, int32_t y) { status_t err = validate(); if (err < 0) return err; const sp<SurfaceComposerClient>& client(mClient); return client->setPosition(mToken, x, y); } status_t SurfaceControl::setSize(uint32_t w, uint32_t h) { status_t err = validate(); if (err < 0) return err; const sp<SurfaceComposerClient>& client(mClient); return client->setSize(mToken, w, h); } status_t SurfaceControl::hide() { status_t err = validate(); if (err < 0) return err; const sp<SurfaceComposerClient>& client(mClient); return client->hide(mToken); } status_t SurfaceControl::show(int32_t layer) { status_t err = validate(); if (err < 0) return err; const sp<SurfaceComposerClient>& client(mClient); return client->show(mToken, layer); } status_t SurfaceControl::freeze() { status_t err = validate(); if (err < 0) return err; const sp<SurfaceComposerClient>& client(mClient); return client->freeze(mToken); } status_t SurfaceControl::unfreeze() { status_t err = validate(); if (err < 0) return err; const sp<SurfaceComposerClient>& client(mClient); return client->unfreeze(mToken); } status_t SurfaceControl::setFlags(uint32_t flags, uint32_t mask) { status_t err = validate(); if (err < 0) return err; const sp<SurfaceComposerClient>& client(mClient); return client->setFlags(mToken, flags, mask); } status_t SurfaceControl::setTransparentRegionHint(const Region& transparent) { status_t err = validate(); if (err < 0) return err; const sp<SurfaceComposerClient>& client(mClient); return client->setTransparentRegionHint(mToken, transparent); } status_t SurfaceControl::setAlpha(float alpha) { status_t err = validate(); if (err < 0) return err; const sp<SurfaceComposerClient>& client(mClient); return client->setAlpha(mToken, alpha); } status_t SurfaceControl::setMatrix(float dsdx, float dtdx, float dsdy, float dtdy) { status_t err = validate(); if (err < 0) return err; const sp<SurfaceComposerClient>& client(mClient); return client->setMatrix(mToken, dsdx, dtdx, dsdy, dtdy); } status_t SurfaceControl::setFreezeTint(uint32_t tint) { status_t err = validate(); if (err < 0) return err; const sp<SurfaceComposerClient>& client(mClient); return client->setFreezeTint(mToken, tint); } status_t SurfaceControl::setCrop(const Rect& crop) { status_t err = validate(); if (err < 0) return err; const sp<SurfaceComposerClient>& client(mClient); return client->setCrop(mToken, crop); } status_t SurfaceControl::validate() const { if (mToken<0 || mClient==0) { ALOGE("invalid token (%d, identity=%u) or client (%p)", mToken, mIdentity, mClient.get()); return NO_INIT; } return NO_ERROR; } status_t SurfaceControl::writeSurfaceToParcel( const sp<SurfaceControl>& control, Parcel* parcel) { sp<ISurface> sur; uint32_t identity = 0; if (SurfaceControl::isValid(control)) { sur = control->mSurface; identity = control->mIdentity; } parcel->writeStrongBinder(sur!=0 ? sur->asBinder() : NULL); parcel->writeStrongBinder(NULL); // NULL ISurfaceTexture in this case. parcel->writeInt32(identity); return NO_ERROR; } sp<Surface> SurfaceControl::getSurface() const { Mutex::Autolock _l(mLock); if (mSurfaceData == 0) { sp<SurfaceControl> surface_control(const_cast<SurfaceControl*>(this)); mSurfaceData = new Surface(surface_control); } return mSurfaceData; } // ============================================================================ // Surface // ============================================================================ // --------------------------------------------------------------------------- Surface::Surface(const sp<SurfaceControl>& surface) : SurfaceTextureClient(), mSurface(surface->mSurface), mIdentity(surface->mIdentity) { sp<ISurfaceTexture> st; if (mSurface != NULL) { st = mSurface->getSurfaceTexture(); } init(st); } Surface::Surface(const Parcel& parcel, const sp<IBinder>& ref) : SurfaceTextureClient() { mSurface = interface_cast<ISurface>(ref); sp<IBinder> st_binder(parcel.readStrongBinder()); sp<ISurfaceTexture> st; if (st_binder != NULL) { st = interface_cast<ISurfaceTexture>(st_binder); } else if (mSurface != NULL) { st = mSurface->getSurfaceTexture(); } mIdentity = parcel.readInt32(); init(st); } Surface::Surface(const sp<ISurfaceTexture>& st) : SurfaceTextureClient(), mSurface(NULL), mIdentity(0) { init(st); } status_t Surface::writeToParcel( const sp<Surface>& surface, Parcel* parcel) { sp<ISurface> sur; sp<ISurfaceTexture> st; uint32_t identity = 0; if (Surface::isValid(surface)) { sur = surface->mSurface; st = surface->getISurfaceTexture(); identity = surface->mIdentity; } else if (surface != 0 && (surface->mSurface != NULL || surface->getISurfaceTexture() != NULL)) { ALOGE("Parceling invalid surface with non-NULL ISurface/ISurfaceTexture as NULL: " "mSurface = %p, surfaceTexture = %p, mIdentity = %d, ", surface->mSurface.get(), surface->getISurfaceTexture().get(), surface->mIdentity); } parcel->writeStrongBinder(sur != NULL ? sur->asBinder() : NULL); parcel->writeStrongBinder(st != NULL ? st->asBinder() : NULL); parcel->writeInt32(identity); return NO_ERROR; } Mutex Surface::sCachedSurfacesLock; DefaultKeyedVector<wp<IBinder>, wp<Surface> > Surface::sCachedSurfaces; sp<Surface> Surface::readFromParcel(const Parcel& data) { Mutex::Autolock _l(sCachedSurfacesLock); sp<IBinder> binder(data.readStrongBinder()); sp<Surface> surface = sCachedSurfaces.valueFor(binder).promote(); if (surface == 0) { surface = new Surface(data, binder); sCachedSurfaces.add(binder, surface); } else { // The Surface was found in the cache, but we still should clear any // remaining data from the parcel. data.readStrongBinder(); // ISurfaceTexture data.readInt32(); // identity } if (surface->mSurface == NULL && surface->getISurfaceTexture() == NULL) { surface = 0; } cleanCachedSurfacesLocked(); return surface; } // Remove the stale entries from the surface cache. This should only be called // with sCachedSurfacesLock held. void Surface::cleanCachedSurfacesLocked() { for (int i = sCachedSurfaces.size()-1; i >= 0; --i) { wp<Surface> s(sCachedSurfaces.valueAt(i)); if (s == 0 || s.promote() == 0) { sCachedSurfaces.removeItemsAt(i); } } } void Surface::init(const sp<ISurfaceTexture>& surfaceTexture) { if (mSurface != NULL || surfaceTexture != NULL) { ALOGE_IF(surfaceTexture==0, "got a NULL ISurfaceTexture from ISurface"); if (surfaceTexture != NULL) { setISurfaceTexture(surfaceTexture); setUsage(GraphicBuffer::USAGE_HW_RENDER); } DisplayInfo dinfo; SurfaceComposerClient::getDisplayInfo(0, &dinfo); const_cast<float&>(ANativeWindow::xdpi) = dinfo.xdpi; const_cast<float&>(ANativeWindow::ydpi) = dinfo.ydpi; const_cast<uint32_t&>(ANativeWindow::flags) = 0; } } Surface::~Surface() { // clear all references and trigger an IPC now, to make sure things // happen without delay, since these resources are quite heavy. mSurface.clear(); IPCThreadState::self()->flushCommands(); } bool Surface::isValid() { return getISurfaceTexture() != NULL; } sp<ISurfaceTexture> Surface::getSurfaceTexture() { return getISurfaceTexture(); } sp<IBinder> Surface::asBinder() const { return mSurface!=0 ? mSurface->asBinder() : 0; } // ---------------------------------------------------------------------------- int Surface::query(int what, int* value) const { switch (what) { case NATIVE_WINDOW_CONCRETE_TYPE: *value = NATIVE_WINDOW_SURFACE; return NO_ERROR; } return SurfaceTextureClient::query(what, value); } // ---------------------------------------------------------------------------- status_t Surface::lock(SurfaceInfo* other, Region* inOutDirtyRegion) { ANativeWindow_Buffer outBuffer; ARect temp; ARect* inOutDirtyBounds = NULL; if (inOutDirtyRegion) { temp = inOutDirtyRegion->getBounds(); inOutDirtyBounds = &temp; } status_t err = SurfaceTextureClient::lock(&outBuffer, inOutDirtyBounds); if (err == NO_ERROR) { other->w = uint32_t(outBuffer.width); other->h = uint32_t(outBuffer.height); other->s = uint32_t(outBuffer.stride); other->usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN; other->format = uint32_t(outBuffer.format); other->bits = outBuffer.bits; } if (inOutDirtyRegion) { inOutDirtyRegion->set( static_cast<Rect const&>(temp) ); } return err; } status_t Surface::unlockAndPost() { return SurfaceTextureClient::unlockAndPost(); } // ---------------------------------------------------------------------------- }; // namespace android
[ "ruvindad@zone24x7.com" ]
ruvindad@zone24x7.com
4a845ac6169711f25f4c90484b446df5f91a9ebc
1e88fd48f4cbfab5567b6b5052114b0a72b86c6a
/system/public/DemoSystem.h
7d8ac7c35e0a2ea8a685f30638d4e33ba68ef8ec
[]
no_license
csbgh/GraphicsDemos
501917156ffed64a6442f7b8df90d98f2449846d
6a5b27ef305865d58ac8747950731fe2e6252d9b
refs/heads/master
2021-01-22T02:53:33.925243
2017-02-06T11:32:33
2017-02-06T11:32:33
81,080,693
0
0
null
null
null
null
UTF-8
C++
false
false
3,027
h
#ifndef _DEMO_SYSTEM_H #define _DEMO_SYSTEM_H #pragma once #include <SDL.h> #include <SDL_syswm.h> #include <imgui\imgui.h> #include "DemoCommon.h" #include "Input.h" #include "IGraphicsDevice.h" #include <map> #include <vector> #if defined(_DEBUG) #define CHECK_SDL(_call) \ { \ int32 res = _call; \ if(res < 0) \ { \ HRESULT hr = _call; \ Log::WriteError("SDL Error on line %i of file %s", __LINE__, __FILE__); \ Log::WriteError(SDL_GetError()); \ } \ } #else #define CHECK_SDL(_call) (_call) #endif class Demo; class Texture; enum class GraphicsAPIOptions { None, DirectX11, OpenGL3 }; struct PerFrameUniforms { glm::mat4 viewProjection; glm::mat4 uiOrthoProjection; }; enum class FullscreenMode { Windowed = 0, BorderlessWindowed = 1, Fullscreen = 2 }; ENUM_FLAGS(FullscreenMode) struct DisplaySettings { DisplaySettings() { width = 1366; height = 768; refreshRate = 60; vsync = true; fullscreenMode = FullscreenMode::Windowed; windowTitle = "Window"; } int32 width; int32 height; int32 refreshRate; bool vsync; FullscreenMode fullscreenMode; std::string windowTitle; }; struct DisplayMode { DisplayMode(uint32 width, uint32 height, uint32 refreshRate) : width(width), height(height), refreshRate(refreshRate) { displayModeStr = std::to_string(width) + "x" + std::to_string(height) + " @ " + std::to_string(refreshRate); } //SDL_DisplayMode displayMode; uint32 width; uint32 height; uint32 refreshRate; std::string displayModeStr; }; //typedef std::vector<SDL_DisplayMode> DisplayModeList; class DemoSystem { public: DemoSystem(); ~DemoSystem(); void Initialize(); void Update(); void Destroy(); void SetDemo(Demo* newDemo); void SetGraphicsAPI(GraphicsAPIOptions api); IGraphicsDevice* GetGraphicsDevice(); void Clear(); void Present(); void MakeWindow(const DisplaySettings &newSettings); // Setters void SetDisplaySettings(const DisplaySettings &newSettings); void SetFOV(float newFOV); void SetClipboardText(const char* text); // Gettters void GetDisplaySize(uint32* width, uint32* height); const DisplaySettings& GetDisplaySettings(); const std::vector<DisplayMode>& GetAvailableDisplayModes(); const char* GetClipboardText(); Texture* LoadTexture(std::string fileName); bool IsRunning(); void SetRunning(bool IsRunning); Input input; private: void CreateResources(); void ReleaseResources(); void OnRenderAPIChanged(); // UI void DrawBaseUI(); bool running; Demo* curDemo; IGraphicsDevice* curGraphicsDevice; GraphicsAPIOptions curAPIOption; // Display DisplaySettings curDisplaySettings; std::vector<DisplayMode> displayModeList; float fov = 70.0f; SDL_Window* sdlWindow; SDL_DisplayMode displayMode; SDL_SysWMinfo sdlInfo; // Uniform Buffers PerFrameUniforms perFrameUniform; Buffer* perFrameBuffer; }; #endif // _DEMO_SYSTEM_H
[ "csb.github@gmail.com" ]
csb.github@gmail.com
8716a2e12f8949a3b4e8039f3d9255ca59301594
1a2ab1b714d521cc63c7f9fcc5d879e7dbe53d16
/GameTest/myLevel.h
801be505852af91459d58de8c81d747e9f68ae6d
[]
no_license
KJTang/SimpleGE
f504a27f881cf74b8906bd090f3d4bf419c07043
bb7bb3d5aaba04a5da4acce9fcf196f7270706e5
refs/heads/master
2021-01-10T16:40:54.743245
2016-01-29T09:30:58
2016-01-29T09:30:58
46,039,053
1
3
null
null
null
null
UTF-8
C++
false
false
2,946
h
#pragma once #include "SimpleGE.h" /************** WQY *************/ #define dY 50 #define Y0 30 #define dX 150 #define X0 130 #define BGSIZE 400 #define SIZE 70 class LevelZero : public Level { private: int count; GameObject *go; public: LevelZero(){} ~LevelZero(){} CREATE_FUNC(LevelZero); virtual bool init(); virtual void update(); }; class LoadingLevel : public Level { private: int count; bool quit; public: LoadingLevel(); ~LoadingLevel(); CREATE_FUNC(LoadingLevel); virtual bool init(); virtual void update(); void callback(void *data); // when loaded, call this }; class LevelOne : public Level { private: int count; int monsterCount; public: LevelOne(); ~LevelOne(); CREATE_FUNC(LevelOne); virtual bool init(); virtual void update(); void createMonster(); void minusMonster(); }; class LevelTwo : public Level { private: int count; int monsterCount; GameObject *introduction; public: LevelTwo(); ~LevelTwo(); CREATE_FUNC(LevelTwo); virtual bool init(); virtual void update(); void createMonster(); void minusMonster(); }; class LevelThree : public Level { private: int count; public: LevelThree(); ~LevelThree(); CREATE_FUNC(LevelThree); virtual bool init(); virtual void update(); }; /************ WDP ***************/ class LevelGameInfo :public Level { private: int count; GameObject *go; public: LevelGameInfo(); ~LevelGameInfo(); CREATE_FUNC(LevelGameInfo); virtual bool init(); virtual void update(); }; class LevelTeamInfo :public Level { private: GameObject *go; public: LevelTeamInfo(){} ~LevelTeamInfo(){} CREATE_FUNC(LevelTeamInfo); virtual bool init(); virtual void update(); }; class LevelSuccess :public Level { private: GameObject *go; std::vector<GameObject *> choice; public: LevelSuccess(){} ~LevelSuccess(){} CREATE_FUNC(LevelSuccess); virtual bool init(); virtual void update(); }; class LevelFail :public Level { private: GameObject *go; std::vector<GameObject *> choice; public: LevelFail() {} ~LevelFail() {} CREATE_FUNC(LevelFail); virtual bool init(); virtual void update(); }; class LevelFail2 :public Level { private: GameObject *go; std::vector<GameObject *> choice; public: LevelFail2() {} ~LevelFail2() {} CREATE_FUNC(LevelFail2); virtual bool init(); virtual void update(); }; class LevelP1win :public Level { private: GameObject *go; std::vector<GameObject *> choice; public: LevelP1win() {} ~LevelP1win() {} CREATE_FUNC(LevelP1win); virtual bool init(); virtual void update(); }; class LevelP2win :public Level { private: GameObject *go; std::vector<GameObject *> choice; public: LevelP2win() {} ~LevelP2win() {} CREATE_FUNC(LevelP2win); virtual bool init(); virtual void update(); };
[ "178061543@qq.com" ]
178061543@qq.com
89a26a440a0b62b144ee5fb3577b407829323673
04cab23f26ac2968be827577c5a0a688d70e9617
/16433.cpp
e2357276adcad2a3e8ecb78719fe16fc3e4c61d3
[]
no_license
gusrb3164/gusrb_algorithm
ebeffb271effdbf446b88f037ba7caf6cb320314
63991f9094ab61e7de20acafe30f9f5e46144635
refs/heads/master
2020-08-09T10:51:49.698866
2020-04-10T05:20:15
2020-04-10T05:20:15
214,071,884
0
0
null
null
null
null
UTF-8
C++
false
false
467
cpp
#include<iostream> using namespace std; int main() { int N; int x, y; cin >> N >> x >> y; if ((x + y) % 2 == 0) { for (int i = 1; i <= N; i++) { for (int j = 1; j <= N; j++) { if ((i + j) % 2 == 0) cout << 'v'; else cout << '.'; } cout << "\n"; } } else { for (int i = 1; i <= N; i++) { for (int j = 1; j <= N; j++) { if ((i + j) % 2 == 0) cout << '.'; else cout << 'v'; } cout << "\n"; } } }
[ "gusrb3164@gmail.com" ]
gusrb3164@gmail.com
abd686743b9401d74f8893284359bc4689ca15aa
6c77cf237697f252d48b287ae60ccf61b3220044
/aws-cpp-sdk-sagemaker/include/aws/sagemaker/model/CreateTransformJobRequest.h
6632e967e2acc2ef33898f7e90c0a3dc1553568b
[ "MIT", "Apache-2.0", "JSON" ]
permissive
Gohan/aws-sdk-cpp
9a9672de05a96b89d82180a217ccb280537b9e8e
51aa785289d9a76ac27f026d169ddf71ec2d0686
refs/heads/master
2020-03-26T18:48:43.043121
2018-11-09T08:44:41
2018-11-09T08:44:41
145,232,234
1
0
Apache-2.0
2018-08-30T13:42:27
2018-08-18T15:42:39
C++
UTF-8
C++
false
false
25,436
h
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #pragma once #include <aws/sagemaker/SageMaker_EXPORTS.h> #include <aws/sagemaker/SageMakerRequest.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/sagemaker/model/BatchStrategy.h> #include <aws/core/utils/memory/stl/AWSMap.h> #include <aws/sagemaker/model/TransformInput.h> #include <aws/sagemaker/model/TransformOutput.h> #include <aws/sagemaker/model/TransformResources.h> #include <aws/core/utils/memory/stl/AWSVector.h> #include <aws/sagemaker/model/Tag.h> #include <utility> namespace Aws { namespace SageMaker { namespace Model { /** */ class AWS_SAGEMAKER_API CreateTransformJobRequest : public SageMakerRequest { public: CreateTransformJobRequest(); // Service request name is the Operation name which will send this request out, // each operation should has unique request name, so that we can get operation's name from this request. // Note: this is not true for response, multiple operations may have the same response name, // so we can not get operation's name from response. inline virtual const char* GetServiceRequestName() const override { return "CreateTransformJob"; } Aws::String SerializePayload() const override; Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override; /** * <p>The name of the transform job. The name must be unique within an AWS Region * in an AWS account. </p> */ inline const Aws::String& GetTransformJobName() const{ return m_transformJobName; } /** * <p>The name of the transform job. The name must be unique within an AWS Region * in an AWS account. </p> */ inline void SetTransformJobName(const Aws::String& value) { m_transformJobNameHasBeenSet = true; m_transformJobName = value; } /** * <p>The name of the transform job. The name must be unique within an AWS Region * in an AWS account. </p> */ inline void SetTransformJobName(Aws::String&& value) { m_transformJobNameHasBeenSet = true; m_transformJobName = std::move(value); } /** * <p>The name of the transform job. The name must be unique within an AWS Region * in an AWS account. </p> */ inline void SetTransformJobName(const char* value) { m_transformJobNameHasBeenSet = true; m_transformJobName.assign(value); } /** * <p>The name of the transform job. The name must be unique within an AWS Region * in an AWS account. </p> */ inline CreateTransformJobRequest& WithTransformJobName(const Aws::String& value) { SetTransformJobName(value); return *this;} /** * <p>The name of the transform job. The name must be unique within an AWS Region * in an AWS account. </p> */ inline CreateTransformJobRequest& WithTransformJobName(Aws::String&& value) { SetTransformJobName(std::move(value)); return *this;} /** * <p>The name of the transform job. The name must be unique within an AWS Region * in an AWS account. </p> */ inline CreateTransformJobRequest& WithTransformJobName(const char* value) { SetTransformJobName(value); return *this;} /** * <p>The name of the model that you want to use for the transform job. * <code>ModelName</code> must be the name of an existing Amazon SageMaker model * within an AWS Region in an AWS account.</p> */ inline const Aws::String& GetModelName() const{ return m_modelName; } /** * <p>The name of the model that you want to use for the transform job. * <code>ModelName</code> must be the name of an existing Amazon SageMaker model * within an AWS Region in an AWS account.</p> */ inline void SetModelName(const Aws::String& value) { m_modelNameHasBeenSet = true; m_modelName = value; } /** * <p>The name of the model that you want to use for the transform job. * <code>ModelName</code> must be the name of an existing Amazon SageMaker model * within an AWS Region in an AWS account.</p> */ inline void SetModelName(Aws::String&& value) { m_modelNameHasBeenSet = true; m_modelName = std::move(value); } /** * <p>The name of the model that you want to use for the transform job. * <code>ModelName</code> must be the name of an existing Amazon SageMaker model * within an AWS Region in an AWS account.</p> */ inline void SetModelName(const char* value) { m_modelNameHasBeenSet = true; m_modelName.assign(value); } /** * <p>The name of the model that you want to use for the transform job. * <code>ModelName</code> must be the name of an existing Amazon SageMaker model * within an AWS Region in an AWS account.</p> */ inline CreateTransformJobRequest& WithModelName(const Aws::String& value) { SetModelName(value); return *this;} /** * <p>The name of the model that you want to use for the transform job. * <code>ModelName</code> must be the name of an existing Amazon SageMaker model * within an AWS Region in an AWS account.</p> */ inline CreateTransformJobRequest& WithModelName(Aws::String&& value) { SetModelName(std::move(value)); return *this;} /** * <p>The name of the model that you want to use for the transform job. * <code>ModelName</code> must be the name of an existing Amazon SageMaker model * within an AWS Region in an AWS account.</p> */ inline CreateTransformJobRequest& WithModelName(const char* value) { SetModelName(value); return *this;} /** * <p>The maximum number of parallel requests that can be sent to each instance in * a transform job. This is good for algorithms that implement multiple workers on * larger instances . The default value is <code>1</code>. To allow Amazon * SageMaker to determine the appropriate number for * <code>MaxConcurrentTransforms</code>, set the value to <code>0</code>.</p> */ inline int GetMaxConcurrentTransforms() const{ return m_maxConcurrentTransforms; } /** * <p>The maximum number of parallel requests that can be sent to each instance in * a transform job. This is good for algorithms that implement multiple workers on * larger instances . The default value is <code>1</code>. To allow Amazon * SageMaker to determine the appropriate number for * <code>MaxConcurrentTransforms</code>, set the value to <code>0</code>.</p> */ inline void SetMaxConcurrentTransforms(int value) { m_maxConcurrentTransformsHasBeenSet = true; m_maxConcurrentTransforms = value; } /** * <p>The maximum number of parallel requests that can be sent to each instance in * a transform job. This is good for algorithms that implement multiple workers on * larger instances . The default value is <code>1</code>. To allow Amazon * SageMaker to determine the appropriate number for * <code>MaxConcurrentTransforms</code>, set the value to <code>0</code>.</p> */ inline CreateTransformJobRequest& WithMaxConcurrentTransforms(int value) { SetMaxConcurrentTransforms(value); return *this;} /** * <p>The maximum payload size allowed, in MB. A payload is the data portion of a * record (without metadata). The value in <code>MaxPayloadInMB</code> must be * greater or equal to the size of a single record. You can approximate the size of * a record by dividing the size of your dataset by the number of records. Then * multiply this value by the number of records you want in a mini-batch. It is * recommended to enter a value slightly larger than this to ensure the records fit * within the maximum payload size. The default value is <code>6</code> MB. For an * unlimited payload size, set the value to <code>0</code>.</p> */ inline int GetMaxPayloadInMB() const{ return m_maxPayloadInMB; } /** * <p>The maximum payload size allowed, in MB. A payload is the data portion of a * record (without metadata). The value in <code>MaxPayloadInMB</code> must be * greater or equal to the size of a single record. You can approximate the size of * a record by dividing the size of your dataset by the number of records. Then * multiply this value by the number of records you want in a mini-batch. It is * recommended to enter a value slightly larger than this to ensure the records fit * within the maximum payload size. The default value is <code>6</code> MB. For an * unlimited payload size, set the value to <code>0</code>.</p> */ inline void SetMaxPayloadInMB(int value) { m_maxPayloadInMBHasBeenSet = true; m_maxPayloadInMB = value; } /** * <p>The maximum payload size allowed, in MB. A payload is the data portion of a * record (without metadata). The value in <code>MaxPayloadInMB</code> must be * greater or equal to the size of a single record. You can approximate the size of * a record by dividing the size of your dataset by the number of records. Then * multiply this value by the number of records you want in a mini-batch. It is * recommended to enter a value slightly larger than this to ensure the records fit * within the maximum payload size. The default value is <code>6</code> MB. For an * unlimited payload size, set the value to <code>0</code>.</p> */ inline CreateTransformJobRequest& WithMaxPayloadInMB(int value) { SetMaxPayloadInMB(value); return *this;} /** * <p>Determines the number of records included in a single mini-batch. * <code>SingleRecord</code> means only one record is used per mini-batch. * <code>MultiRecord</code> means a mini-batch is set to contain as many records * that can fit within the <code>MaxPayloadInMB</code> limit.</p> <p>Batch * transform will automatically split your input data into whatever payload size is * specified if you set <code>SplitType</code> to <code>Line</code> and * <code>BatchStrategy</code> to <code>MultiRecord</code>. There's no need to split * the dataset into smaller files or to use larger payload sizes unless the records * in your dataset are very large.</p> */ inline const BatchStrategy& GetBatchStrategy() const{ return m_batchStrategy; } /** * <p>Determines the number of records included in a single mini-batch. * <code>SingleRecord</code> means only one record is used per mini-batch. * <code>MultiRecord</code> means a mini-batch is set to contain as many records * that can fit within the <code>MaxPayloadInMB</code> limit.</p> <p>Batch * transform will automatically split your input data into whatever payload size is * specified if you set <code>SplitType</code> to <code>Line</code> and * <code>BatchStrategy</code> to <code>MultiRecord</code>. There's no need to split * the dataset into smaller files or to use larger payload sizes unless the records * in your dataset are very large.</p> */ inline void SetBatchStrategy(const BatchStrategy& value) { m_batchStrategyHasBeenSet = true; m_batchStrategy = value; } /** * <p>Determines the number of records included in a single mini-batch. * <code>SingleRecord</code> means only one record is used per mini-batch. * <code>MultiRecord</code> means a mini-batch is set to contain as many records * that can fit within the <code>MaxPayloadInMB</code> limit.</p> <p>Batch * transform will automatically split your input data into whatever payload size is * specified if you set <code>SplitType</code> to <code>Line</code> and * <code>BatchStrategy</code> to <code>MultiRecord</code>. There's no need to split * the dataset into smaller files or to use larger payload sizes unless the records * in your dataset are very large.</p> */ inline void SetBatchStrategy(BatchStrategy&& value) { m_batchStrategyHasBeenSet = true; m_batchStrategy = std::move(value); } /** * <p>Determines the number of records included in a single mini-batch. * <code>SingleRecord</code> means only one record is used per mini-batch. * <code>MultiRecord</code> means a mini-batch is set to contain as many records * that can fit within the <code>MaxPayloadInMB</code> limit.</p> <p>Batch * transform will automatically split your input data into whatever payload size is * specified if you set <code>SplitType</code> to <code>Line</code> and * <code>BatchStrategy</code> to <code>MultiRecord</code>. There's no need to split * the dataset into smaller files or to use larger payload sizes unless the records * in your dataset are very large.</p> */ inline CreateTransformJobRequest& WithBatchStrategy(const BatchStrategy& value) { SetBatchStrategy(value); return *this;} /** * <p>Determines the number of records included in a single mini-batch. * <code>SingleRecord</code> means only one record is used per mini-batch. * <code>MultiRecord</code> means a mini-batch is set to contain as many records * that can fit within the <code>MaxPayloadInMB</code> limit.</p> <p>Batch * transform will automatically split your input data into whatever payload size is * specified if you set <code>SplitType</code> to <code>Line</code> and * <code>BatchStrategy</code> to <code>MultiRecord</code>. There's no need to split * the dataset into smaller files or to use larger payload sizes unless the records * in your dataset are very large.</p> */ inline CreateTransformJobRequest& WithBatchStrategy(BatchStrategy&& value) { SetBatchStrategy(std::move(value)); return *this;} /** * <p>The environment variables to set in the Docker container. We support up to 16 * key and values entries in the map.</p> */ inline const Aws::Map<Aws::String, Aws::String>& GetEnvironment() const{ return m_environment; } /** * <p>The environment variables to set in the Docker container. We support up to 16 * key and values entries in the map.</p> */ inline void SetEnvironment(const Aws::Map<Aws::String, Aws::String>& value) { m_environmentHasBeenSet = true; m_environment = value; } /** * <p>The environment variables to set in the Docker container. We support up to 16 * key and values entries in the map.</p> */ inline void SetEnvironment(Aws::Map<Aws::String, Aws::String>&& value) { m_environmentHasBeenSet = true; m_environment = std::move(value); } /** * <p>The environment variables to set in the Docker container. We support up to 16 * key and values entries in the map.</p> */ inline CreateTransformJobRequest& WithEnvironment(const Aws::Map<Aws::String, Aws::String>& value) { SetEnvironment(value); return *this;} /** * <p>The environment variables to set in the Docker container. We support up to 16 * key and values entries in the map.</p> */ inline CreateTransformJobRequest& WithEnvironment(Aws::Map<Aws::String, Aws::String>&& value) { SetEnvironment(std::move(value)); return *this;} /** * <p>The environment variables to set in the Docker container. We support up to 16 * key and values entries in the map.</p> */ inline CreateTransformJobRequest& AddEnvironment(const Aws::String& key, const Aws::String& value) { m_environmentHasBeenSet = true; m_environment.emplace(key, value); return *this; } /** * <p>The environment variables to set in the Docker container. We support up to 16 * key and values entries in the map.</p> */ inline CreateTransformJobRequest& AddEnvironment(Aws::String&& key, const Aws::String& value) { m_environmentHasBeenSet = true; m_environment.emplace(std::move(key), value); return *this; } /** * <p>The environment variables to set in the Docker container. We support up to 16 * key and values entries in the map.</p> */ inline CreateTransformJobRequest& AddEnvironment(const Aws::String& key, Aws::String&& value) { m_environmentHasBeenSet = true; m_environment.emplace(key, std::move(value)); return *this; } /** * <p>The environment variables to set in the Docker container. We support up to 16 * key and values entries in the map.</p> */ inline CreateTransformJobRequest& AddEnvironment(Aws::String&& key, Aws::String&& value) { m_environmentHasBeenSet = true; m_environment.emplace(std::move(key), std::move(value)); return *this; } /** * <p>The environment variables to set in the Docker container. We support up to 16 * key and values entries in the map.</p> */ inline CreateTransformJobRequest& AddEnvironment(const char* key, Aws::String&& value) { m_environmentHasBeenSet = true; m_environment.emplace(key, std::move(value)); return *this; } /** * <p>The environment variables to set in the Docker container. We support up to 16 * key and values entries in the map.</p> */ inline CreateTransformJobRequest& AddEnvironment(Aws::String&& key, const char* value) { m_environmentHasBeenSet = true; m_environment.emplace(std::move(key), value); return *this; } /** * <p>The environment variables to set in the Docker container. We support up to 16 * key and values entries in the map.</p> */ inline CreateTransformJobRequest& AddEnvironment(const char* key, const char* value) { m_environmentHasBeenSet = true; m_environment.emplace(key, value); return *this; } /** * <p>Describes the input source and the way the transform job consumes it.</p> */ inline const TransformInput& GetTransformInput() const{ return m_transformInput; } /** * <p>Describes the input source and the way the transform job consumes it.</p> */ inline void SetTransformInput(const TransformInput& value) { m_transformInputHasBeenSet = true; m_transformInput = value; } /** * <p>Describes the input source and the way the transform job consumes it.</p> */ inline void SetTransformInput(TransformInput&& value) { m_transformInputHasBeenSet = true; m_transformInput = std::move(value); } /** * <p>Describes the input source and the way the transform job consumes it.</p> */ inline CreateTransformJobRequest& WithTransformInput(const TransformInput& value) { SetTransformInput(value); return *this;} /** * <p>Describes the input source and the way the transform job consumes it.</p> */ inline CreateTransformJobRequest& WithTransformInput(TransformInput&& value) { SetTransformInput(std::move(value)); return *this;} /** * <p>Describes the results of the transform job.</p> */ inline const TransformOutput& GetTransformOutput() const{ return m_transformOutput; } /** * <p>Describes the results of the transform job.</p> */ inline void SetTransformOutput(const TransformOutput& value) { m_transformOutputHasBeenSet = true; m_transformOutput = value; } /** * <p>Describes the results of the transform job.</p> */ inline void SetTransformOutput(TransformOutput&& value) { m_transformOutputHasBeenSet = true; m_transformOutput = std::move(value); } /** * <p>Describes the results of the transform job.</p> */ inline CreateTransformJobRequest& WithTransformOutput(const TransformOutput& value) { SetTransformOutput(value); return *this;} /** * <p>Describes the results of the transform job.</p> */ inline CreateTransformJobRequest& WithTransformOutput(TransformOutput&& value) { SetTransformOutput(std::move(value)); return *this;} /** * <p>Describes the resources, including ML instance types and ML instance count, * to use for the transform job.</p> */ inline const TransformResources& GetTransformResources() const{ return m_transformResources; } /** * <p>Describes the resources, including ML instance types and ML instance count, * to use for the transform job.</p> */ inline void SetTransformResources(const TransformResources& value) { m_transformResourcesHasBeenSet = true; m_transformResources = value; } /** * <p>Describes the resources, including ML instance types and ML instance count, * to use for the transform job.</p> */ inline void SetTransformResources(TransformResources&& value) { m_transformResourcesHasBeenSet = true; m_transformResources = std::move(value); } /** * <p>Describes the resources, including ML instance types and ML instance count, * to use for the transform job.</p> */ inline CreateTransformJobRequest& WithTransformResources(const TransformResources& value) { SetTransformResources(value); return *this;} /** * <p>Describes the resources, including ML instance types and ML instance count, * to use for the transform job.</p> */ inline CreateTransformJobRequest& WithTransformResources(TransformResources&& value) { SetTransformResources(std::move(value)); return *this;} /** * <p>An array of key-value pairs. Adding tags is optional. For more information, * see <a * href="http://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/cost-alloc-tags.html#allocation-what">Using * Cost Allocation Tags</a> in the <i>AWS Billing and Cost Management User * Guide</i>.</p> */ inline const Aws::Vector<Tag>& GetTags() const{ return m_tags; } /** * <p>An array of key-value pairs. Adding tags is optional. For more information, * see <a * href="http://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/cost-alloc-tags.html#allocation-what">Using * Cost Allocation Tags</a> in the <i>AWS Billing and Cost Management User * Guide</i>.</p> */ inline void SetTags(const Aws::Vector<Tag>& value) { m_tagsHasBeenSet = true; m_tags = value; } /** * <p>An array of key-value pairs. Adding tags is optional. For more information, * see <a * href="http://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/cost-alloc-tags.html#allocation-what">Using * Cost Allocation Tags</a> in the <i>AWS Billing and Cost Management User * Guide</i>.</p> */ inline void SetTags(Aws::Vector<Tag>&& value) { m_tagsHasBeenSet = true; m_tags = std::move(value); } /** * <p>An array of key-value pairs. Adding tags is optional. For more information, * see <a * href="http://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/cost-alloc-tags.html#allocation-what">Using * Cost Allocation Tags</a> in the <i>AWS Billing and Cost Management User * Guide</i>.</p> */ inline CreateTransformJobRequest& WithTags(const Aws::Vector<Tag>& value) { SetTags(value); return *this;} /** * <p>An array of key-value pairs. Adding tags is optional. For more information, * see <a * href="http://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/cost-alloc-tags.html#allocation-what">Using * Cost Allocation Tags</a> in the <i>AWS Billing and Cost Management User * Guide</i>.</p> */ inline CreateTransformJobRequest& WithTags(Aws::Vector<Tag>&& value) { SetTags(std::move(value)); return *this;} /** * <p>An array of key-value pairs. Adding tags is optional. For more information, * see <a * href="http://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/cost-alloc-tags.html#allocation-what">Using * Cost Allocation Tags</a> in the <i>AWS Billing and Cost Management User * Guide</i>.</p> */ inline CreateTransformJobRequest& AddTags(const Tag& value) { m_tagsHasBeenSet = true; m_tags.push_back(value); return *this; } /** * <p>An array of key-value pairs. Adding tags is optional. For more information, * see <a * href="http://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/cost-alloc-tags.html#allocation-what">Using * Cost Allocation Tags</a> in the <i>AWS Billing and Cost Management User * Guide</i>.</p> */ inline CreateTransformJobRequest& AddTags(Tag&& value) { m_tagsHasBeenSet = true; m_tags.push_back(std::move(value)); return *this; } private: Aws::String m_transformJobName; bool m_transformJobNameHasBeenSet; Aws::String m_modelName; bool m_modelNameHasBeenSet; int m_maxConcurrentTransforms; bool m_maxConcurrentTransformsHasBeenSet; int m_maxPayloadInMB; bool m_maxPayloadInMBHasBeenSet; BatchStrategy m_batchStrategy; bool m_batchStrategyHasBeenSet; Aws::Map<Aws::String, Aws::String> m_environment; bool m_environmentHasBeenSet; TransformInput m_transformInput; bool m_transformInputHasBeenSet; TransformOutput m_transformOutput; bool m_transformOutputHasBeenSet; TransformResources m_transformResources; bool m_transformResourcesHasBeenSet; Aws::Vector<Tag> m_tags; bool m_tagsHasBeenSet; }; } // namespace Model } // namespace SageMaker } // namespace Aws
[ "magmarco@amazon.com" ]
magmarco@amazon.com
db2c7e2ccbdad42991d2f28464963a2458ab275d
15a7b4cbf97b803775b26d8a1a7094cea114cff2
/libraries/protocol/include/BuffRequest.h
b92f3d755cdcf13c0524bf598d8b64aa3082643a
[]
no_license
AGuismo/G-BALLS-Rtype
5ba71039a5b7c5bc31f950ff5e6f8758f4e963e5
75ba8ee5cded3e450c884a1c222699b8415e5973
refs/heads/master
2021-01-17T02:34:34.274163
2014-12-30T20:46:31
2014-12-30T20:46:31
13,957,123
0
0
null
null
null
null
UTF-8
C++
false
false
553
h
#pragma once #include "Protocol.hpp" #include "AGameRequest.hh" class BuffRequest : public AGameRequest { public: BuffRequest(); BuffRequest(Ruint16 id, Rint8 type); ~BuffRequest(); BuffRequest(BuffRequest const&); BuffRequest& operator=(BuffRequest const&); public: Protocol &serialize(Protocol &) const; Protocol &unserialize(Protocol &); ARequest *clone(); public: Ruint16 ID() const; void ID(Ruint16 id); Rint8 type() const; void type(Rint8 type); private: Ruint16 _id; Rint8 _type; };
[ "kev993@hotmail.com" ]
kev993@hotmail.com
932707dfa9860050daa1a98283b24e3ddad1198b
d7c07075e0c6acedf2270611e739beac422186f4
/environment_analysis/kinematics/MatrixMath.h
8bdb3100878b4727bb30f360df240edd7086aa46
[]
no_license
KB9/BraccioVisualAttention
d5b55deac81923cbd5311020a2f0486aa4705b0d
9128e5fb224704f5d4c7493d824be74e923c709f
refs/heads/master
2021-09-11T00:10:06.218786
2018-04-04T18:30:44
2018-04-04T18:30:44
106,980,988
0
0
null
2018-04-04T18:30:45
2017-10-15T03:32:28
Python
UTF-8
C++
false
false
1,108
h
/* * MatrixMath.h Library for Matrix Math * * Created by Charlie Matlack on 12/18/10. * Modified from code by RobH45345 on Arduino Forums, algorithm from * NUMERICAL RECIPES: The Art of Scientific Computing. * Modified to work with Arduino 1.0/1.5 by randomvibe & robtillaart * Made into a real library on GitHub by Vasilis Georgitzikis (tzikis) * so that it's easy to use and install (March 2015) */ #ifndef MatrixMath_h #define MatrixMath_h #if defined(ARDUINO) && ARDUINO >= 100 #include "Arduino.h" #else //#include "WProgram.h" #include <iostream> #include <string> #include <cmath> #endif class MatrixMath { public: //MatrixMath(); void Print(float* A, int m, int n, std::string label); void Copy(float* A, int n, int m, float* B); void Multiply(float* A, float* B, int m, int p, int n, float* C); void Add(float* A, float* B, int m, int n, float* C); void Subtract(float* A, float* B, int m, int n, float* C); void Transpose(float* A, int m, int n, float* C); void Scale(float* A, int m, int n, float k); int Invert(float* A, int n); }; extern MatrixMath Matrix; #endif
[ "kavanbickerstaff@googlemail.com" ]
kavanbickerstaff@googlemail.com
60cef48083c32bdc89e088474ff70cdc3787e79c
dd994c1dcf4ac94c15f1ebe4caba322de70b0d9e
/105/Server/GameEngine/Test/TestThread.h
99f652d5104fbd31753f25cdda24bff64007d715
[]
no_license
coderguang/miniGameEngine
8a870a5b9e4f92065d4cb44a69d44348911382d2
93eb522b74c5763941d45d3afdfa6793efeba253
refs/heads/master
2022-02-16T07:31:43.983958
2019-08-22T09:53:17
2019-08-22T09:53:17
113,191,648
0
0
null
null
null
null
UTF-8
C++
false
false
9,145
h
#ifndef _TEST_TEST_THREAD_H_ #define _TEST_TEST_THREAD_H_ #include <thread> #include "framework/counter/counterHandler.h" #include "framework/log/Log.h" #include <thread> #include "framework/io/PrintIOHandler.h" #include "framework/datetime/datetime.h" #include "engine/lock/lock.h" #include "engine/lock/lockObjectManager.h" #include <set> #include "engine/thread/thread.h" #include <mutex> #include "engine/thread/task.h" #include "engine/baseServer/updateDtTask.h" #include "engine/thread/threadManager.h" using namespace csg; std::atomic<bool> ready; void printObject(int v) { static int counter = 0; for ( int i = 0; i < v; i++ ) { counter++; std::cout << ",count=" << counter << std::endl; } /* static CCounterHandler t("test"); CPrintIOHandler* log = new CPrintIOHandler(); t.print(log); */ } void testCounter(int num) { CCounterHandler t("test"); for ( int i = 0; i <= num; i++ ) { std::cout << ",thread=" << i << std::endl; std::thread t2(printObject,100); t2.detach(); } } void updateSysDt(int loop) { int i = 0; while ( true ) { if ( loop == i++ ) { i = 0; CDateTime::updateThreadDt(); } } } int updateSysDtByThread(void *args) { CDateTime now; std::cout << "updateDt thread_id=" << CThread::threadId()<<"now is "<<now.asString()<<std::endl; int *uDt = (int*) args; while ( true ) { if ( CDateTime().getTotalSecond() - now.getTotalSecond() > 10 ) { if ( !ready ) { ready = true; } } CThread::sleep_for(*uDt); CDateTime::updateThreadDt(); //std::cout << "updateDt thread_id=" << std::this_thread::threadId(); } return 0; } void testUpdateDt() { std::thread dtTask(updateSysDt ,1000); char ch; do { std::cout << "n for continue,b for break:" << std::endl; ch = cin.get(); if ( ch == 'b' ) { break; } CDateTime dt; std::cout << "now my data is " << dt.asString() << std::endl; using std::chrono::system_clock; system_clock::time_point today = system_clock::now(); time_t tt = system_clock::to_time_t(today); std::cout << "system date is: " << ctime(&tt); } while ( true ); } int printHello(void *arg) { int *pDt = (int*) arg; do { CDateTime now; CThread::sleep_for(*pDt); std::cout << "hello,now is "<<now.asString() << std::endl; } while ( true ); } int printHelloEx(void *arg) { int *pDt = (int*) arg; while ( !ready ) { CThread::yeild(); } CDateTime now; do { CThread::sleep_until(now); std::cout << "hello,now is " << CDateTime().asString() << std::endl; now += CInterval(*pDt ,0); } while ( true ); } static int threadAddSum = 0; static std::set<int> numset; void addSum(int flag) { while ( true ) { //CAutoLock l(CLockObjectManager::getSingletonLock()); threadAddSum++; //std::cout <<"flag:"<<flag<< "threadSum=" << threadAddSum << std::endl; std::cout<< "threadSum=" << threadAddSum << std::endl; std::cout.flush(); if ( numset.count(threadAddSum) > 1 ) assert(false); numset.insert(threadAddSum); // if ( threadAddSum>10000 ) { // break; // } } } void testNormalThread() { std::thread dtTask(updateSysDt ,1000); std::cout << "main start" << std::endl; std::thread t(addSum ,111); std::thread t2(addSum ,222); std::thread t3(addSum ,333); //std::thread t3(addSum); //t.detach(); dtTask.join(); t.join(); t2.detach(); t3.detach(); std::cout << "main end" << std::endl; } void printTime() { char ch; do { std::cout << "n for continue,b for break:" << std::endl; ch = cin.get(); if ( ch == 'b' ) { break; } CDateTime dt; std::cout << "now my data is " << dt.asString() << std::endl; using std::chrono::system_clock; system_clock::time_point today = system_clock::now(); time_t tt = system_clock::to_time_t(today); std::cout << "system date is: " << ctime(&tt); } while ( true ); } void testMyThread() { /* int uDt= 500; int pDt = 2; ready = false; std::cout << "pid is " << CThread::pid() << std::endl; csg_thread thr; CThread::InitTask(updateSysDtByThread ,(void*)&uDt,thr); csg_thread thrEx; CThread::InitTask(printHelloEx ,(void*) &pDt,thrEx); std::cout << "main run ,thread="<<std::this_thread::threadId()<<std::endl; thr.detach(); thrEx.join(); printTime(); */ } std::mutex lockEE; int counterLock = 0; int printLockHello(void *dt) { std::cout << "thread_id= " << CThread::threadId() << " start " << std::endl; //CAutoLock lock(CLockObjectManager::getSingletonLock()); //std::lock_guard<std::mutex> l(lockEE); do { { CThread::sleep_for(1000); CAutoLock lock(CLockObjectManager::getSingletonLock()); counterLock++; CDateTime dt; std::cout << "thread_id=" << CThread::threadId() << ",now my data is " << dt.asString() << ",num=" << counterLock << std::endl; } } while ( true ); } int printLockHelloByMain() { char ch; do { ch = cin.get(); if ( 'n' == ch ) { CDateTime dt; std::cout << "thread_id=" << CThread::threadId() << ",now my data is " << dt.asString() << ",num=" << counterLock << std::endl; } else if ( 'b' == ch ) { break; } } while ( true ); return 0; } void testLock() { int uDt = 500; std::cout << "pid is " << CThread::pid() << std::endl; // csg_thread thr = CThread::InitTask(updateSysDtByThread ,(void*) &uDt); // csg_thread thrEx= CThread::InitTask(printLockHello ,(void*) &uDt); // csg_thread thrEx2 = CThread::InitTask(printLockHello ,(void*) &uDt); // csg_thread thrEx3 = CThread::InitTask(printLockHello ,(void*) &uDt); // csg_thread thrEx4 = CThread::InitTask(printLockHello ,(void*) &uDt); // csg_thread thrEx5 = CThread::InitTask(printLockHello ,(void*) &uDt); // csg_thread thrEx6 = CThread::InitTask(printLockHello ,(void*) &uDt); // // thr.join(); } void testTask() { int uDt = 500; // CTask task(updateSysDtByThread ,(void*) &uDt); // { // CTask taskEx(printLockHello ,(void*) &uDt); // task.active(); // } //taskEx.active(5); //task.join(); } void testTaskEx() { int threadCount = 3; int uDt = 500; CSG_THREAD_FUN _func = printLockHello; void *_args = (void*) &uDt; std::cout << "pid is " << CThread::pid() << std::endl; return; } void testTask2() { int uDt = 500; //CTask task(updateSysDtByThread ,(void*) &uDt); //task.active(1); } void testUpdateDtTask() { CUpdateDtTask dtTask; //dtTask.active(1); char ch; do { ch = cin.get(); if ( 'b' == ch ) { break; } else if ( 's' == ch ) { //dtTask.setExit(); }else { CDateTime dt; std::cout << "thread_id=" << CThread::threadId() << ",now my data is " << dt.asString() << ",num=" << counterLock << std::endl; } } while ( true ); } void testNotify() { CUpdateDtTask dtTask; //dtTask.active(1); char ch; do { ch = cin.get(); if ( 'b' == ch ) { break; } else if ( 's' == ch ) { //dtTask.setStop(); } else if ( 't' == ch ) { //dtTask.runFromStop(); } else if ( 'e' == ch ) { //dtTask.setExit(); } else { CDateTime dt; std::cout << "thread_id=" << CThread::threadId() << ",now my data is " << dt.asString() << ",num=" << counterLock << std::endl; } } while ( true ); } void testTaskMgr() { CUpdateDtTask dtTask; //dtTask.active(3); //CThreadManager::instance()->addTask(dtTask); std::string taskName = "CUpdateDtTask"; char ch; do { ch = cin.get(); if ( 'b' == ch ) { break; } else if ( 's' == ch ) { CThreadManager::instance()->stopTaskByType(EBaseServerUpdateDt); } else if ( 't' == ch ) { CThreadManager::instance()->runTaskFromStopByType(EBaseServerUpdateDt); } else if ( 'e' == ch ) { CThreadManager::instance()->killTaskByType(EBaseServerUpdateDt); } else { CDateTime dt; std::cout << "thread_id=" << CThread::threadId() << ",now my data is " << dt.asString() << ",num=" << counterLock << std::endl; } } while ( true ); } void testTaskMgrEx() { //CUpdateDtTask dtTask; //dtTask.active(1); //CThreadManager::instance()->addTask(dtTask); CThreadManager::instance()->activeBaseServer(EBaseServerUpdateDt); std::string taskName = "CUpdateDtTask"; char ch; do { ch = cin.get(); if ( 'b' == ch ) { break; } else if ( 's' == ch ) { CThreadManager::instance()->stopAllTask(); } else if ( 't' == ch ) { CThreadManager::instance()->runAllTaskFromStop(); } else if ( 'e' == ch ) { CThreadManager::instance()->killAllTask(); } else { CDateTime dt; std::string printLog = " now my data is "+dt.asString();; //CLogManager::instance()->add(printLog); } } while ( true ); CThreadManager::instance()->killAllTask(); } void testThread() { testTaskMgrEx(); //testNotify(); //testUpdateDtTask(); //testTaskEx(); //testTask(); //testLock(); //testMyThread(); } #endif
[ "royalchen@royalchen.com" ]
royalchen@royalchen.com
137d8d06cf729ebcc2e0fad1c9850f47fa044715
7b74fda44b216bba18c9dae5bc8653f6f7dfe5a5
/githubLeetcode/Yi Zhang sourcecode/排序sort and partition/count_sort, quick_sort.cpp
2c04c4f688aac27d0974d90b5bbf9e7219a81449
[]
no_license
ryudo87/CPP
685fcb1547681d96d0082980729457de3ef1f217
67dccebe87b5317557cc83697b445b637e6dc351
refs/heads/master
2022-04-29T17:44:53.336906
2022-04-03T02:13:58
2022-04-03T02:13:58
200,724,141
0
0
null
null
null
null
UTF-8
C++
false
false
758
cpp
int arr[]={3,2,8,1,1}; void swap(int left,int right) { int tmp=arr[left];arr[left]=arr[right];arr[right]=tmp; } void quick_sort(int first, int last) { if(first>=last) return; int pivot=arr[first]; int left=first; int right=last; while(left<right) { while(left<right&&arr[right]>pivot) --right; if(left<right) swap(left++,right); while(left<right&&arr[left]<=pivot) left++; if(left<right) swap(left,right--); } quick_sort(first,left-1); quick_sort(left+1,last); } void count_sort() { int num[8]={0}; for(size_t i=0;i<5;++i) num[arr[i]-1]++; for(size_t i=0,j=0;i<5,j<8;) { while(num[j]--){ arr[i++]=j+1; } j++; } } int main() { quick_sort(0,4); count_sort(); }
[ "yizhang@Yis-MacBook-Pro.fios-router.home" ]
yizhang@Yis-MacBook-Pro.fios-router.home
4edf46cf840fedba6731772a87a9da16a4b4adad
66ea31cadaec228b9abf9a2ca83b469af9dc1d0a
/src/Core/Matlab/matlabarray.cc
86ea5ac1f2afa606e2eecf1902313884e44fa02b
[ "MIT" ]
permissive
lsptb/SCIRun
2e2857411346f0b3a02a429089a5f693bae32dc9
fafd58173c20b7b14ed700dc978da649c328c014
refs/heads/master
2021-01-17T11:17:47.765711
2015-03-12T18:07:35
2015-03-12T18:07:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
31,041
cc
/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2009 Scientific Computing and Imaging Institute, University of Utah. 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. */ // NOTE: This MatlabIO file is used in different projects as well. Please, do not // make it depend on other scirun code. This way it is easier to maintain matlabIO // code among different projects. Thank you. /* * FILE: matlabarray.h * AUTH: Jeroen G Stinstra * DATE: 16 MAY 2005 */ #include <Core/Matlab/matlabarray.h> #include <boost/algorithm/string/predicate.hpp> #include <iostream> #include <sstream> using namespace SCIRun::MatlabIO; // matlabarray management functions // constructor/destructor // assignment/copy constructor // clear // constructor // creates on the place holder for the matlabarray matlabarray::matlabarray() : m_(0) { } // destructor matlabarray::~matlabarray() { if (m_ != 0) { // delete the attached structure if necessary m_->ref_--; if (m_->ref_ == 0) { delete m_; } m_ = 0; } } // copy constructor matlabarray::matlabarray(const matlabarray &m) { m_ = 0; // reference the same structure as the matlabarray we are copying if (m.m_ != 0) { m_ = m.m_; m_->ref_++; } } // assignment matlabarray& matlabarray::operator= (const matlabarray &m) { // the same construction as the previous function is used // to create a copy // if m = m we have to do nothing if (this != &m) { if (m_ != 0) { // delete the attached structure if necessary m_->ref_--; if (m_->ref_ == 0) { delete m_; } m_ = 0; } if (m.m_ != 0) { m_ = m.m_; m_->ref_++; } } return *this; } // clear and empty // Clear: this function is for clearing the contents of the matrix and dereferencing // the handle properly. In the matrix nothing needs to be destroyed as all elements // have their own destructors, hence deleting the object will invoke all routines // for cleaning up memory void matlabarray::clear() { if (m_ != 0) { // delete the attached structure if necessary m_->ref_--; if (m_->ref_ == 0) { delete m_; } m_ = 0; } } // This function can be used to test whether the matrix contains any data // If not do not try to access the matrix components. This will result in // an internal_error exception bool matlabarray::isempty() const { if (m_ == 0) return(true); if (!issparse()) if (getnumelements() == 0) return(true); return(false); } matlabarray matlabarray::clone() const { matlabarray ma; if (isempty()) return(ma); ma.m_ = new mxarray; ma.m_->ref_ = 1; ma.m_->class_ = m_->class_; ma.m_->type_ = m_->type_; ma.m_->flags_ = m_->flags_; ma.m_->dims_ = m_->dims_; ma.m_->name_ = m_->name_; ma.m_->classname_ = m_->classname_; ma.m_->string_ = m_->string_; ma.m_->fieldnames_ = m_->fieldnames_; ma.m_->subarray_.resize(m_->subarray_.size()); for (int p=0;p<static_cast<int>(m_->subarray_.size());p++) { ma.m_->subarray_[p] = m_->subarray_[p].clone(); } ma.m_->preal_ = m_->preal_.clone(); ma.m_->pimag_ = m_->pimag_.clone(); ma.m_->prows_ = m_->prows_.clone(); ma.m_->pcols_ = m_->pcols_.clone(); return(ma); } // functions to maintain the matlabarray // General functions to maintain matrix names class names and // matrix types/ dimensions. These functions can only be // called if there is a matrix associated with the matlabarray // handle. // // If an internal_error is thrown it means that the emptiness // is not checked before calling these functions matlabarray::mlclass matlabarray::getclass() const { if (m_ == 0) return(mlUNKNOWN); return(m_->class_); } matlabarray::mitype matlabarray::gettype() const { if (m_ == 0) { std::cerr << "internal error in gettype()\n"; throw internal_error(); } return(m_->type_); } std::string matlabarray::getclassname() const { if (m_ == 0) { std::cerr << "internal error in getclassname()\n"; throw internal_error(); } return(m_->classname_); } void matlabarray::setclassname(const std::string& classname) { if (m_ == 0) { std::cerr << "internal error in setclassname()\n"; throw internal_error(); } m_->classname_ = classname; } std::string matlabarray::getname() const { if (m_ == 0) { std::cerr << "internal error in getname()\n"; throw internal_error(); } return(m_->name_); } void matlabarray::setname(const std::string& name) { if (m_ == 0) { std::cerr << "internal error in setname()\n"; throw internal_error(); } m_->name_ = name; } void matlabarray::setdims(const std::vector<int> &dims) { if (m_ == 0) { std::cerr << "internal error in setdims()\n"; throw internal_error(); } if (dims.size() == 0) { std::vector<int> ndims(2); ndims[0] = 0; ndims[1] = 0; m_->dims_ = ndims; return; } if (dims.size() == 1) { std::vector<int> ndims(2); ndims[0] = dims[0]; ndims[1] = 1; m_->dims_ = ndims; return; } m_->dims_ = dims; } void matlabarray::settype(matlabarray::mitype type) { if (m_ == 0) { std::cerr << "internal error in settype()\n"; throw internal_error(); } m_->type_ = type; } std::vector<int> matlabarray::getdims() const { if (m_ == 0) { std::cerr << "internal error in getdims()\n"; throw internal_error(); } return(m_->dims_); } int matlabarray::getnumdims() const { if (m_ == 0) { std::cerr << "internal error in getnumdims()\n"; throw internal_error(); } return(static_cast<int>(m_->dims_.size())); } int matlabarray::getnumelements() const { if (m_ == 0) return(0); if ((m_->class_ == mlSTRUCT)||(m_->class_ == mlOBJECT)) { if(m_->fieldnames_.size() == 0) return(0); } if (m_->class_ != mlSPARSE) { int numel = 1; int ndims = static_cast<int>(m_->dims_.size()); for (int p=0; p<ndims;p++) { numel *= m_->dims_[p]; } return (numel); } else { return(getnnz()); } } int matlabarray::getm() const { if (m_ == 0) return(0); return(m_->dims_[0]); } int matlabarray::getn() const { if (m_ == 0) return(0); return(m_->dims_[1]); } // Functions to calculate the index into an array // Matlab uses the fortran way of numbering the dimensions // No attempt is made in this to transpose matrices at // this point. int matlabarray::sub2index(const std::vector<int> &vec) const { if (m_ == 0) { std::cerr << "internal error in sub2index()\n"; throw internal_error(); } int index = 0; int ndims = static_cast<int>(m_->dims_.size()); std::vector<int> proddims(ndims); proddims[0] = 1; for (int p=1;p<ndims;p++) { proddims[p] = m_->dims_[p-1]*proddims[p-1]; } for (int p=0;p<ndims;p++) { index += proddims[p]*vec[p];} return(index); } std::vector<int> matlabarray::index2sub(int index) const { if (m_ == 0) { std::cerr << "internal error in index2sub()\n"; throw internal_error(); } int ndims = static_cast<int>(m_->dims_.size()); std::vector<int> vec(ndims); std::vector<int> proddims(ndims); proddims[0] = 1; for (int p=1;p<ndims;p++) { proddims[p] = m_->dims_[p-1]*proddims[p-1]; } ldiv_t q; for (int p=(ndims-1);p>=0;p--) { q = ldiv(index,proddims[p]); index = static_cast<int>(q.rem); vec[p]= static_cast<int>(q.quot); } return(vec); } // cell specific functions matlabarray matlabarray::getcell(int index) const { if (m_ == 0) { std::cerr << "internal error in getcell()\n"; throw internal_error(); } // No more out of range, but an empty array if ((index >= static_cast<int>(m_->subarray_.size()))||(index < 0)) {matlabarray ma; return(ma);} return(m_->subarray_[index]); } matlabarray matlabarray::getcell(const std::vector<int> &indexvec) const { return(getcell(sub2index(indexvec))); } void matlabarray::setcell(int index, const matlabarray& m) { if (m_ == 0) { std::cerr << "internal error in setcell()\n"; throw internal_error(); } if ((index >= static_cast<int>(m_->subarray_.size()))||(index < 0)) throw out_of_range(); m_->subarray_[index] = m; } void matlabarray::setcell(const std::vector<int> &indexvec, const matlabarray& m) { setcell(sub2index(indexvec),m); } // struct specific functions std::vector<std::string> matlabarray::getfieldnames() const { if (m_ == 0) { std::cerr << "internal error in getfieldnames()\n"; throw internal_error(); } if ((m_->class_ != mlSTRUCT)&&(m_->class_ != mlOBJECT)) throw internal_error(); return(m_->fieldnames_); } int matlabarray::getnumfields() const { if (m_ == 0) { std::cerr << "internal error in getnumfields()\n"; throw internal_error(); } return(static_cast<int>(m_->fieldnames_.size())); } std::string matlabarray::getfieldname(int index) const { if (m_ == 0) { std::cerr << "internal error in getfieldname()\n"; throw internal_error(); } if ((m_->class_ != mlSTRUCT)&&(m_->class_ != mlOBJECT)) throw internal_error(); if ((index >= static_cast<int>(m_->fieldnames_.size()))||(index < 0)) throw out_of_range(); return(m_->fieldnames_[index]); } int matlabarray::getfieldnameindex(const std::string& fieldname) const { if (m_ == 0) { std::cerr << "internal error in getfieldnameindex()\n"; throw internal_error(); } if ((m_->class_ != mlSTRUCT)&&(m_->class_ != mlOBJECT)) throw internal_error(); int index = -1; for (int p = 0;p<static_cast<int>(m_->fieldnames_.size());p++) { if (m_->fieldnames_[p] == fieldname) { index = p; break;} } return(index); } int matlabarray::getfieldnameindexCI(const std::string& fieldname) const { if (m_ == 0) { std::cerr << "internal error in getfieldnameindexCI()\n"; throw internal_error(); } if ((m_->class_ != mlSTRUCT)&&(m_->class_ != mlOBJECT)) throw internal_error(); int index = -1; for (int p = 0;p< static_cast<int>(m_->fieldnames_.size());p++) { if ( boost::iequals(m_->fieldnames_[p],fieldname)) { index = p; break;} } return(index); } void matlabarray::setfieldname(int index,const std::string& fieldname) { if (m_ == 0) { std::cerr << "internal error in setfieldname()\n"; throw internal_error(); } if ((m_->class_ != mlSTRUCT)&&(m_->class_ != mlOBJECT)) throw internal_error(); if ((index >= static_cast<int>(m_->fieldnames_.size()))||(index < 0)) throw out_of_range(); m_->fieldnames_[index] = fieldname; } matlabarray matlabarray::getfield(int index,int fieldnameindex) const { if (m_ == 0) { std::cerr << "internal error in getfield()\n"; throw internal_error(); } if ((m_->class_ != mlSTRUCT)&&(m_->class_ != mlOBJECT)) { std::cerr << "internal error in getfield()\n"; throw internal_error(); } // if out of range just return an empty array if ((fieldnameindex < 0)||(fieldnameindex > static_cast<int>(m_->fieldnames_.size()))) { matlabarray ma; return(ma);} index = (index * static_cast<int>(m_->fieldnames_.size())) + fieldnameindex; return(getcell(index)); } matlabarray matlabarray::getfield(int index,const std::string& fieldname) const { return(getfield(index,getfieldnameindex(fieldname))); } matlabarray matlabarray::getfield(const std::vector<int> &indexvec,const std::string& fieldname) const { return(getfield(sub2index(indexvec),getfieldnameindex(fieldname))); } matlabarray matlabarray::getfieldCI(int index,const std::string& fieldname) const { return(getfield(index,getfieldnameindexCI(fieldname))); } matlabarray matlabarray::getfieldCI(const std::vector<int> &indexvec,const std::string& fieldname) const { return(getfield(sub2index(indexvec),getfieldnameindexCI(fieldname))); } matlabarray matlabarray::getfield(const std::vector<int> &indexvec,int fieldnameindex) const { return(getfield(sub2index(indexvec),fieldnameindex)); } void matlabarray::setfield(int index,int fieldnameindex,const matlabarray& m) { if (m_ == 0) { std::cerr << "internal error in setfield()\n"; throw internal_error(); } if ((m_->class_ != mlSTRUCT)&&(m_->class_ != mlOBJECT)) { std::cerr << "internal error in setfield()\n"; throw internal_error(); } if ((fieldnameindex < 0)||(fieldnameindex > static_cast<int>(m_->fieldnames_.size()))) throw out_of_range(); index = (index * static_cast<int>(m_->fieldnames_.size())) + fieldnameindex; setcell(index,m); } void matlabarray::setfield(int index,const std::string& fieldname,const matlabarray& m) { int fieldindex = getfieldnameindex(fieldname); if (fieldindex == -1) { fieldindex = addfieldname(fieldname); } setfield(index,fieldindex,m); } void matlabarray::setfield(const std::vector<int> &indexvec,const std::string& fieldname,const matlabarray& m) { int fieldindex = getfieldnameindex(fieldname); if (fieldindex == -1) { fieldindex = addfieldname(fieldname); } setfield(sub2index(indexvec),fieldindex,m); } void matlabarray::setfield(const std::vector<int> &indexvec,int fieldnameindex,const matlabarray& m) { setfield(sub2index(indexvec),fieldnameindex,m); } int matlabarray::addfieldname(const std::string& fieldname) { if (m_ == 0) { std::cerr << "internal error in addfieldname()\n"; throw internal_error(); } if ((m_->class_ != mlSTRUCT)&&(m_->class_ != mlOBJECT)) { std::cerr << "internal error in addfieldname()\n"; throw internal_error(); } // Reorder the fieldname array int newfieldnum = static_cast<int>(m_->fieldnames_.size()); m_->fieldnames_.resize(newfieldnum+1); m_->fieldnames_[newfieldnum] = fieldname; // Reorder the subarray int newsize = (newfieldnum+1)*getnumelements(); std::vector<matlabarray> subarray(newsize); for (int p=0,q=0,r=0;p<newsize;p++,q++) { if (q == newfieldnum) { q =0; } else { subarray[p] = m_->subarray_[r]; r++; } } m_->subarray_ = subarray; return(newfieldnum); } void matlabarray::removefieldname(int fieldnameindex) { if (m_ == 0) { std::cerr << "internal error in removefieldname()\n"; throw internal_error(); } if ((m_->class_ != mlSTRUCT)&&(m_->class_ != mlOBJECT)) { std::cerr << "internal error in removefieldname()\n"; throw internal_error(); } // Reorder the fieldname vector int numfields = static_cast<int>(m_->fieldnames_.size()); std::vector<std::string> fieldnames(numfields-1); for (int p=0,r=0;p<numfields;p++) { if (r != fieldnameindex) { fieldnames[r] = m_->fieldnames_[p]; r++; }} m_->fieldnames_ = fieldnames; // Reorder the subarray vector numfields = (static_cast<int>(m_->fieldnames_.size())*getnumelements()); std::vector<matlabarray> subarray; for (int p=0,q=0,r=0;p<numfields;p++,q++) { if (q == numfields) {q=0;} if (q != fieldnameindex) { subarray[r] = m_->subarray_[p]; r++; } } m_->subarray_ = subarray; } void matlabarray::removefieldname(const std::string& fieldname) { removefieldname(getfieldnameindex(fieldname)); } // String specific functions // The user can alter the contents of a // string array any time std::string matlabarray::getstring() const { if (m_ == 0) { std::cerr << "internal error in getstring()\n"; throw internal_error(); } return(m_->string_); } void matlabarray::setstring(const std::string& str) { if (m_ == 0) { std::cerr << "internal error setstring()\n"; throw internal_error(); } m_->string_ = str; std::vector<int> dims(2); dims[0] = 1; dims[1] = static_cast<int>(str.size()); setdims(dims); } // quick function for creating a double scalar void matlabarray::createdoublescalar(double value) { std::vector<int> dims(2); dims[0] = 1; dims[1] = 1; createdensearray(dims,miDOUBLE); setnumericarray(&value,1); } void matlabarray::createdoublevector(const std::vector<double> &values) { std::vector<int> dims(2); dims[0] = 1; dims[1] = static_cast<int>(values.size()); createdensearray(dims,miDOUBLE); setnumericarray(values); } void matlabarray::createdoublevector(int n, const double *values) { std::vector<int> dims(2); dims[0] = 1; dims[1] = n; createdensearray(dims,miDOUBLE); setnumericarray(values,n); } void matlabarray::createdoublematrix(const std::vector<double> &values, const std::vector<int> &dims) { createdensearray(dims,miDOUBLE); setnumericarray(values); } void matlabarray::createdoublematrix(int m,int n, const double *values) { std::vector<int> dims(2); dims[0] = m; dims[1] = n; createdensearray(dims,miDOUBLE); setnumericarray(values,m*n); } // quick function for creating a int scalar void matlabarray::createintscalar(int value) { std::vector<int> dims(2); dims[0] = 1; dims[1] = 1; createdensearray(dims,miINT32); setnumericarray(&value,1); } void matlabarray::createintvector(const std::vector<int> &values) { std::vector<int> dims(2); dims[0] = 1; dims[1] = static_cast<int>(values.size()); createdensearray(dims,miINT32); setnumericarray(values); } void matlabarray::createintvector(int n, const int *values) { std::vector<int> dims(2); dims[0] = 1; dims[1] = n; createdensearray(dims,miINT32); setnumericarray(values,n); } void matlabarray::createintmatrix(const std::vector<int> &values, const std::vector<int> &dims) { createdensearray(dims,miINT32); setnumericarray(values); } void matlabarray::createintmatrix(int m,int n, const int *values) { std::vector<int> dims(2); dims[0] = m; dims[1] = n; createdensearray(dims,miINT32); setnumericarray(values,m*n); } // creation functions void matlabarray::createdensearray(const std::vector<int> &dims,mitype type) { // function only works for numeric types clear(); // make sure there is no data m_ = new mxarray; m_->ref_ = 1; m_->class_ = mlDENSE; m_->type_ = type; m_->flags_ = 0; setdims(dims); // the numeric data can be inserted later } void matlabarray::createdensearray(int m,int n,mitype type) { std::vector<int> dims(2); dims[0] = m; dims[1] = n; // function only works for numeric types clear(); // make sure there is no data m_ = new mxarray; m_->ref_ = 1; m_->class_ = mlDENSE; m_->type_ = type; m_->flags_ = 0; setdims(dims); // the numeric data can be inserted later } void matlabarray::createsparsearray(const std::vector<int> &dims,mitype type) { clear(); // make sure there is no data m_ = new mxarray; m_->ref_ = 1; m_->class_ = mlSPARSE; m_->type_ = type; // need to add some type checking here m_->flags_ = 0; setdims(dims); // actual data can be added lateron } void matlabarray::createsparsearray(int m,int n,mitype type) { std::vector<int> dims(2); dims[0] = m; dims[1] = n; clear(); // make sure there is no data m_ = new mxarray; m_->ref_ = 1; m_->class_ = mlSPARSE; m_->type_ = type; // need to add some type checking here m_->flags_ = 0; setdims(dims); // actual data can be added lateron } void matlabarray::createcellarray(const std::vector<int> &dims) { clear(); // make sure there is no data m_ = new mxarray; m_->ref_ = 1; m_->class_ = mlCELL; m_->type_ = miMATRIX; // need to add some type checking here m_->flags_ = 0; setdims(dims); m_->subarray_.clear(); m_->subarray_.resize(getnumelements()); } void matlabarray::createstructarray(const std::vector<std::string> &fieldnames) { std::vector<int> dims(2); dims[0] = 1; dims[1] = 1; createstructarray(dims,fieldnames); } void matlabarray::createstructarray(const std::vector<int> &dims, const std::vector<std::string> &fieldnames) { clear(); // make sure there is no data m_ = new mxarray; m_->ref_ = 1; m_->class_ = mlSTRUCT; m_->type_ = miMATRIX; // need to add some type checking here m_->flags_ = 0; setdims(dims); m_->fieldnames_ = fieldnames; m_->subarray_.clear(); m_->subarray_.resize(getnumelements()*getnumfields()); } void matlabarray::createstructarray() { clear(); // make sure there is no data m_ = new mxarray; m_->ref_ = 1; m_->class_ = mlSTRUCT; m_->type_ = miMATRIX; // need to add some type checking here m_->flags_ = 0; std::vector<int> dims(2); dims[0] = 1; dims[1] = 1; setdims(dims); m_->fieldnames_.resize(0); m_->subarray_.clear(); m_->subarray_.resize(0); } void matlabarray::createclassarray(const std::vector<std::string> &fieldnames,const std::string& classname) { std::vector<int> dims(2); dims[0] = 1; dims[1] = 1; createclassarray(dims,fieldnames,classname); } void matlabarray::createclassarray(const std::vector<int> &dims,const std::vector<std::string> &fieldnames,const std::string& classname) { clear(); // make sure there is no data m_ = new mxarray; m_->ref_ = 1; m_->class_ = mlOBJECT; m_->type_ = miMATRIX; // need to add some type checking here m_->flags_ = 0; setdims(dims); m_->classname_ = classname; m_->fieldnames_ = fieldnames; m_->subarray_.clear(); m_->subarray_.resize(getnumelements()*getnumfields()); } void matlabarray::createstringarray() { std::string str(""); createstringarray(str); } void matlabarray::createstringarray(const std::string& str) { clear(); // make sure there is no data m_ = new mxarray; m_->ref_ = 1; m_->class_ = mlSTRING; m_->type_ = miUINT8; m_->flags_ = 0; setstring(str); } // sparse functions int matlabarray::getnnz() const { if (m_ == 0) { std::cerr << "internal error in getnnz()\n"; throw internal_error(); } if (m_->dims_.size() < 2) { return(0); } int n = m_->dims_[1]; if (m_->pcols_.size() < n) { return(0); } return(m_->pcols_.getandcastvalue<int>(n)); } // Raw access to data matfiledata matlabarray::getpreal() { if (m_ == 0) { std::cerr << "internal error in getpreal()\n"; throw internal_error(); } return( m_->preal_); } matfiledata matlabarray::getpimag() { if (m_ == 0) { std::cerr << "internal error in getpimag()\n"; throw internal_error(); } return( m_->pimag_); } matfiledata matlabarray::getprows() { if (m_ == 0) { std::cerr << "internal error in getprows()\n"; throw internal_error(); } return( m_->prows_); } matfiledata matlabarray::getpcols() { if (m_ == 0) { std::cerr << "internal error in getpcols()\n"; throw internal_error(); } return( m_->pcols_); } std::string matlabarray::getinfotext() const { return(getinfotext("")); } std::string matlabarray::getinfotext(const std::string& name) const { if (m_ == 0) return(std::string("[EMPTY MATRIX]")); std::ostringstream oss; if (name.size() == 0) { oss << m_->name_ << " "; if (m_->name_.length() < 40) oss << std::string(40-(m_->name_.length()),' '); } else { oss << name << " "; if (name.length() < 40) oss << std::string(40-(name.length()),' '); } oss << "[ "; for (int p=0;p<static_cast<int>(m_->dims_.size());p++) { oss << m_->dims_[p]; if (p<(static_cast<int>(m_->dims_.size())-1)) oss << "x "; } switch (m_->class_) { case mlDENSE: switch(m_->type_) { case miINT8: oss << " INT8"; break; case miUINT8: oss << " UINT8"; break; case miINT16: oss << " INT16"; break; case miUINT16: oss << " UINT16"; break; case miINT32: oss << " INT32"; break; case miUINT32: oss << " UINT32"; break; case miINT64: oss << " INT64"; break; case miUINT64: oss << " UINT64"; break; case miSINGLE: oss << " SINGLE"; break; case miDOUBLE: oss << " DOUBLE"; break; case miUTF8: oss << " UTF8"; break; case miUTF16: oss << " UTF16"; break; case miUTF32: oss << " UTF32"; break; default: oss << " UNKNOWN"; break; } oss << " ]"; break; case mlSPARSE: oss << " SPARSE ]"; break; case mlCELL: oss << " CELL ]"; break; case mlSTRUCT: oss << " STRUCT ]"; break; case mlSTRING: oss << " STRING ]"; break; case mlOBJECT: oss << " OBJECT ]"; break; default: oss << " UNKNOWN ]"; break; } return(oss.str()); } void matlabarray::setcomplex(bool val) { if (m_ == 0) { std::cerr << "internal error in setcomplex()\n"; throw internal_error(); } m_->flags_ &= 0xFE; if (val) m_->flags_ |= 0x01; } void matlabarray::setlogical(bool val) { if (m_ == 0) { std::cerr << "internal error in setlogical()\n"; throw internal_error(); } m_->flags_ &= 0xFD; if (val) m_->flags_ |= 0x02; } void matlabarray::setglobal(bool val) { if (m_ == 0) { std::cerr << "internal error in setglobal()\n"; throw internal_error(); } m_->flags_ &= 0xFB; if (val) m_->flags_ |= 0x04; } bool matlabarray::iscomplex() const { if (m_ == 0) return(false); return(m_->flags_ & 0x01) != 0; } bool matlabarray::islogical() const { if (m_ == 0) return(false); return(m_->flags_ & 0x02) != 0; } bool matlabarray::isglobal() const { if (m_ == 0) return(false); return(m_->flags_ & 0x04) != 0; } bool matlabarray::isnumeric() const { if (m_ == 0) return(false); return(((m_->class_ == mlSPARSE)||(m_->class_ == mlDENSE))); } bool matlabarray::isstruct() const { if (m_ == 0) return(false); return(((m_->class_ == mlSTRUCT)||(m_->class_ == mlOBJECT))); } bool matlabarray::iscell() const { if (m_ == 0) return(false); return((m_->class_ == mlCELL)); } bool matlabarray::isclass() const { if (m_ == 0) return(false); return((m_->class_ == mlOBJECT)); } bool matlabarray::isstring() const { if (m_ == 0) return(false); return((m_->class_ == mlSTRING)); } bool matlabarray::isdense() const { if (m_ == 0) return(false); return((m_->class_ == mlDENSE)); } bool matlabarray::issparse() const { if (m_ == 0) return(false); return((m_->class_ == mlSPARSE)); } bool matlabarray::isfield(const std::string& fieldname) const { return(getfieldnameindex(fieldname) != -1); } bool matlabarray::isfieldCI(const std::string& fieldname) const { return(getfieldnameindexCI(fieldname) != -1); } // Private functions // //int matlabarray::cmp_nocase(const std::string &s1,const std::string &s2) //{ // std::string::const_iterator p1 = s1.begin(); // std::string::const_iterator p2 = s2.begin(); // // while (p1!=s1.end() && p2 != s2.end()) // { // if (toupper(*p1) != toupper(*p2)) return (toupper(*p1) < toupper(*p2)) ? -1 : 1; // p1++; p2++; // } // // return((s2.size()==s1.size()) ? 0 : (s1.size() < s2.size()) ? -1 : 1); //} void matlabarray::permute(const std::vector<int>& permorder) { if (m_ == 0) { std::cerr << "internal error in permute()\n"; throw internal_error(); } if (m_->class_ != mlDENSE) { std::cerr << "internal error in permute()\n"; throw internal_error(); // Other types are not yet implemented } // In case we are in information mode, there may be no data stored in // the matrix. Hence if there is no data only swap the header if (m_->preal_.size() > 0) { std::vector<int> neworder; reorder_permute(neworder,permorder); // this construction creates a new reordered matfiledata object // and destroys the old one. m_->preal_ = m_->preal_.reorder(neworder); if (iscomplex()) m_->pimag_ = m_->pimag_.reorder(neworder); } int dsize = static_cast<int>(m_->dims_.size()); std::vector<int> dims(dsize); for (int p = 0; p< dsize;p++) dims[p] = m_->dims_[permorder[p]]; m_->dims_ = dims; } void matlabarray::transpose() { if (m_ == 0) { std::cerr << "internal error in transpose()\n"; throw internal_error(); } if (m_->dims_.size() != 2) { std::cerr << "internal error in transpose()\n"; throw internal_error(); } if (m_->class_ != mlDENSE) { std::cerr << "internal error in transpose()\n"; throw internal_error(); // Other types are not yet implemented } std::vector<int> permorder(2); permorder[0] = 1; permorder[1] = 0; if (m_->preal_.size() > 0) { std::vector<int> neworder; reorder_permute(neworder,permorder); // this construction creates a new reordered matfiledata object // and destroys the old one. m_->preal_ = m_->preal_.reorder(neworder); if (iscomplex()) m_->pimag_ =m_->pimag_.reorder(neworder); } int dsize = static_cast<int>(m_->dims_.size()); std::vector<int> dims(dsize); for (int p = 0 ; p < dsize ; p++) dims[p] = m_->dims_[permorder[p]]; m_->dims_ = dims; } void matlabarray::reorder_permute(std::vector<int> &newindices, const std::vector<int>& permorder) { // check whether we can permute this matrix if (m_ == 0) { std::cerr << "internal error in reorder_permute()\n"; throw internal_error(); } if (m_->dims_.size() != permorder.size()) { std::cerr << "internal error in reorder_permute()\n"; throw internal_error(); } newindices.resize(getnumelements()); int size = static_cast<int>(m_->dims_.size()); for (int p = 0; p < size; p++) { if ((permorder[p] < 0)||(permorder[p] >= size)) throw out_of_range(); } std::vector<int> dims(size); std::vector<int> ndims(size); std::vector<int> index(size); std::vector<int> cdims(size); std::vector<int> ncdims(size); int m = 1; for (int p = 0; p < size; p++) { cdims[p] = m; dims[p] = m_->dims_[p]; m *= dims[p]; } for (int p = 0; p < size; p++) { ncdims[p] = cdims[permorder[p]]; ndims[p] = dims[permorder[p]]; } size_t numel = newindices.size(); for (size_t p = 0; p < numel; p++) { newindices[p] = 0; for (int q = 0;q < size; q++) {newindices[p] += index[q]*ncdims[q];} index[0]++; if (index[0] == ndims[0]) { int q = 0; while ((q < size)&&(index[q] == ndims[q])) { index[q] = 0; q++; if (q == size) break; index[q]++; } } } } bool matlabarray::compare(const std::string& str) const { if (m_ == 0) return(false); if (str == m_->string_) return(true); return(false); } bool matlabarray::compareCI(const std::string& str) const { if (m_ == 0) return(false); return boost::iequals(str,m_->string_); }
[ "dwhite@sci.utah.edu" ]
dwhite@sci.utah.edu
1d17443d5233e6651a28eb958f56b480ba7d7a9e
d92a20be082f9a602b9bcef5d04ae4f9e99008ee
/src/163-div2-B.cpp
00e708b957c5547cd63a236d63bee91667ae182b
[]
no_license
kuno4n/Codeforces
5a6c0910dbf78fafe375aea372e6d86027c2c8a1
41972bc1cfefd1014aff4cc4f24db4e016d9b724
refs/heads/master
2016-09-06T12:21:42.763853
2015-01-07T08:38:55
2015-01-07T08:38:55
7,849,601
1
1
null
null
null
null
UTF-8
C++
false
false
1,086
cpp
#include <cstdio> #include <cstdlib> #include <stdlib.h> #include <cmath> #include <ctime> #include <iostream> #include <algorithm> #include <sstream> #include <cstring> #include <vector> #include <set> #include <map> #include <stack> #include <queue> #include <numeric> //#include "cout.h" using namespace std; #define SZ(x) ((int)x.size()) #define MSET(x,a) memset(x, a, (int)sizeof(x)) #define PB push_back #define VI vector < int > #define PII pair < int, int > #define LL long long #define FOR(i,a,b) for (int i = (a); i < (b); i++) #define REP(i,n) FOR(i,0,n) #define ALL(v) (v).begin(), (v).end() #define FIT(it,v) for (typeof((v).begin()) it = (v).begin(); it != (v).end(); it++) #define OUT(A) cout << #A << " = "<< (A) << endl int main() { int n, t; string s; cin >> n >> t >> s; string ss = s; REP(i, t){ REP(j, SZ(s)-1) if(s[j] == 'B' && s[j+1] == 'G'){ ss[j] = 'G'; ss[j+1] = 'B'; j++; } s = ss; } cout << s << endl; return 0; }
[ "kuno4n@gmail.com" ]
kuno4n@gmail.com
eb2ecbf675999b967ee5321792c845f6e7a18d72
164d80b72af086a12ec7a6bfbe689377c76ccf46
/build/android-native-build/Sources/src/kha/vr/SensorState.cpp
66a678f576a44ff556acb245f0fe0d16e0cbc54b
[]
no_license
matthewswallace/HelloKha
0224ab2191e05f41f4c69eaf2c5aae160fa0a216
6a0f9804743d01612be9dd228e46591a5f0effa5
refs/heads/master
2021-01-12T15:07:49.100731
2016-10-25T13:59:22
2016-10-25T13:59:22
71,712,114
1
0
null
null
null
null
UTF-8
C++
false
true
5,356
cpp
// Generated by Haxe 3.3.0 #include <hxcpp.h> #ifndef INCLUDED_kha_vr_PoseState #include <kha/vr/PoseState.h> #endif #ifndef INCLUDED_kha_vr_SensorState #include <kha/vr/SensorState.h> #endif namespace kha{ namespace vr{ void SensorState_obj::__construct(){ HX_STACK_FRAME("kha.vr.SensorState","new",0xdbc352a1,"kha.vr.SensorState.new","kha/vr/SensorState.hx",19,0x60092a8f) HX_STACK_THIS(this) } Dynamic SensorState_obj::__CreateEmpty() { return new SensorState_obj; } hx::ObjectPtr< SensorState_obj > SensorState_obj::__new() { hx::ObjectPtr< SensorState_obj > _hx_result = new SensorState_obj(); _hx_result->__construct(); return _hx_result; } Dynamic SensorState_obj::__Create(hx::DynamicArray inArgs) { hx::ObjectPtr< SensorState_obj > _hx_result = new SensorState_obj(); _hx_result->__construct(); return _hx_result; } SensorState_obj::SensorState_obj() { } void SensorState_obj::__Mark(HX_MARK_PARAMS) { HX_MARK_BEGIN_CLASS(SensorState); HX_MARK_MEMBER_NAME(Predicted,"Predicted"); HX_MARK_MEMBER_NAME(Recorded,"Recorded"); HX_MARK_MEMBER_NAME(Temperature,"Temperature"); HX_MARK_MEMBER_NAME(Status,"Status"); HX_MARK_END_CLASS(); } void SensorState_obj::__Visit(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(Predicted,"Predicted"); HX_VISIT_MEMBER_NAME(Recorded,"Recorded"); HX_VISIT_MEMBER_NAME(Temperature,"Temperature"); HX_VISIT_MEMBER_NAME(Status,"Status"); } hx::Val SensorState_obj::__Field(const ::String &inName,hx::PropertyAccess inCallProp) { switch(inName.length) { case 6: if (HX_FIELD_EQ(inName,"Status") ) { return hx::Val( Status); } break; case 8: if (HX_FIELD_EQ(inName,"Recorded") ) { return hx::Val( Recorded); } break; case 9: if (HX_FIELD_EQ(inName,"Predicted") ) { return hx::Val( Predicted); } break; case 11: if (HX_FIELD_EQ(inName,"Temperature") ) { return hx::Val( Temperature); } } return super::__Field(inName,inCallProp); } hx::Val SensorState_obj::__SetField(const ::String &inName,const hx::Val &inValue,hx::PropertyAccess inCallProp) { switch(inName.length) { case 6: if (HX_FIELD_EQ(inName,"Status") ) { Status=inValue.Cast< Int >(); return inValue; } break; case 8: if (HX_FIELD_EQ(inName,"Recorded") ) { Recorded=inValue.Cast< ::kha::vr::PoseState >(); return inValue; } break; case 9: if (HX_FIELD_EQ(inName,"Predicted") ) { Predicted=inValue.Cast< ::kha::vr::PoseState >(); return inValue; } break; case 11: if (HX_FIELD_EQ(inName,"Temperature") ) { Temperature=inValue.Cast< Float >(); return inValue; } } return super::__SetField(inName,inValue,inCallProp); } void SensorState_obj::__GetFields(Array< ::String> &outFields) { outFields->push(HX_HCSTRING("Predicted","\x98","\xf7","\x6a","\x7e")); outFields->push(HX_HCSTRING("Recorded","\x50","\x11","\x96","\x84")); outFields->push(HX_HCSTRING("Temperature","\x14","\x4c","\xc3","\x20")); outFields->push(HX_HCSTRING("Status","\x52","\x5b","\x90","\x3a")); super::__GetFields(outFields); }; #if HXCPP_SCRIPTABLE static hx::StorageInfo SensorState_obj_sMemberStorageInfo[] = { {hx::fsObject /*::kha::vr::PoseState*/ ,(int)offsetof(SensorState_obj,Predicted),HX_HCSTRING("Predicted","\x98","\xf7","\x6a","\x7e")}, {hx::fsObject /*::kha::vr::PoseState*/ ,(int)offsetof(SensorState_obj,Recorded),HX_HCSTRING("Recorded","\x50","\x11","\x96","\x84")}, {hx::fsFloat,(int)offsetof(SensorState_obj,Temperature),HX_HCSTRING("Temperature","\x14","\x4c","\xc3","\x20")}, {hx::fsInt,(int)offsetof(SensorState_obj,Status),HX_HCSTRING("Status","\x52","\x5b","\x90","\x3a")}, { hx::fsUnknown, 0, null()} }; static hx::StaticInfo *SensorState_obj_sStaticStorageInfo = 0; #endif static ::String SensorState_obj_sMemberFields[] = { HX_HCSTRING("Predicted","\x98","\xf7","\x6a","\x7e"), HX_HCSTRING("Recorded","\x50","\x11","\x96","\x84"), HX_HCSTRING("Temperature","\x14","\x4c","\xc3","\x20"), HX_HCSTRING("Status","\x52","\x5b","\x90","\x3a"), ::String(null()) }; static void SensorState_obj_sMarkStatics(HX_MARK_PARAMS) { HX_MARK_MEMBER_NAME(SensorState_obj::__mClass,"__mClass"); }; #ifdef HXCPP_VISIT_ALLOCS static void SensorState_obj_sVisitStatics(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(SensorState_obj::__mClass,"__mClass"); }; #endif hx::Class SensorState_obj::__mClass; void SensorState_obj::__register() { hx::Static(__mClass) = new hx::Class_obj(); __mClass->mName = HX_HCSTRING("kha.vr.SensorState","\x2f","\x6e","\xe3","\x6b"); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &hx::Class_obj::GetNoStaticField; __mClass->mSetStaticField = &hx::Class_obj::SetNoStaticField; __mClass->mMarkFunc = SensorState_obj_sMarkStatics; __mClass->mStatics = hx::Class_obj::dupFunctions(0 /* sStaticFields */); __mClass->mMembers = hx::Class_obj::dupFunctions(SensorState_obj_sMemberFields); __mClass->mCanCast = hx::TCanCast< SensorState_obj >; #ifdef HXCPP_VISIT_ALLOCS __mClass->mVisitFunc = SensorState_obj_sVisitStatics; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = SensorState_obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = SensorState_obj_sStaticStorageInfo; #endif hx::_hx_RegisterClass(__mClass->mName, __mClass); } } // end namespace kha } // end namespace vr
[ "matthew.wallace@riotgames.com" ]
matthew.wallace@riotgames.com
fcafe2815d4d9af8e015bc95f40539499e66fa08
a9b54c47a5feb0c83b6e87cf626ee613cde2eacd
/wg_modified_diamondback/tf/test/cache_unittest.cpp
e68545949eb556ee85a7b70b77ba76d64464ba3f
[]
no_license
rll/graveyard
fae7366511bd81891ac5b34e8831cf418497642f
7629941d1f3982645fc6bbd951ec071cc110987c
refs/heads/master
2020-05-17T17:19:06.637504
2012-01-10T06:13:04
2012-01-10T06:13:04
3,143,123
1
0
null
null
null
null
UTF-8
C++
false
false
12,787
cpp
/* * Copyright (c) 2008, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Willow Garage, 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. */ #include <gtest/gtest.h> #include <tf/tf.h> #include <sys/time.h> #include "LinearMath/btVector3.h" #include "LinearMath/btMatrix3x3.h" void seed_rand() { //Seed random number generator with current microseond count timeval temp_time_struct; gettimeofday(&temp_time_struct,NULL); srand(temp_time_struct.tv_usec); }; using namespace tf; TEST(TimeCache, Repeatability) { unsigned int runs = 100; seed_rand(); tf::TimeCache cache; std::vector<double> values(runs); StampedTransform t; t.setIdentity(); for ( uint64_t i = 1; i < runs ; i++ ) { values[i] = 10.0 * ((double) rand() - (double)RAND_MAX /2.0) /(double)RAND_MAX; std::stringstream ss; ss << values[i]; t.frame_id_ = ss.str(); t.stamp_ = ros::Time().fromNSec(i); TransformStorage stor(t, i, 0); cache.insertData(stor); } TransformStorage out; for ( uint64_t i = 1; i < runs ; i++ ) { cache.getData(ros::Time().fromNSec(i), out); EXPECT_EQ(out.frame_id_, i); EXPECT_EQ(out.stamp_, ros::Time().fromNSec(i)); } } TEST(TimeCache, RepeatabilityReverseInsertOrder) { unsigned int runs = 100; seed_rand(); tf::TimeCache cache; std::vector<double> values(runs); StampedTransform t; t.setIdentity(); for ( int i = runs -1; i >= 0 ; i-- ) { values[i] = 10.0 * ((double) rand() - (double)RAND_MAX /2.0) /(double)RAND_MAX; t.stamp_ = ros::Time().fromNSec(i); TransformStorage stor(t, i, 0); cache.insertData(stor); } TransformStorage out; for ( uint64_t i = 1; i < runs ; i++ ) { cache.getData(ros::Time().fromNSec(i), out); EXPECT_EQ(out.frame_id_, i); EXPECT_EQ(out.stamp_, ros::Time().fromNSec(i)); } } TEST(TimeCache, RepeatabilityRandomInsertOrder) { seed_rand(); tf::TimeCache cache; double my_vals[] = {13,2,5,4,9,7,3,11,15,14,12,1,6,10,0,8}; std::vector<double> values (my_vals, my_vals + sizeof(my_vals)/sizeof(double)); unsigned int runs = values.size(); StampedTransform t; t.setIdentity(); for ( uint64_t i = 0; i <runs ; i++ ) { values[i] = 10.0 * ((double) rand() - (double)RAND_MAX /2.0) /(double)RAND_MAX; t.stamp_ = ros::Time().fromNSec(i); TransformStorage stor(t, i, 0); cache.insertData(stor); } TransformStorage out; for ( uint64_t i = 1; i < runs ; i++ ) { cache.getData(ros::Time().fromNSec(i), out); EXPECT_EQ(out.frame_id_, i); EXPECT_EQ(out.stamp_, ros::Time().fromNSec(i)); } } TEST(TimeCache, ZeroAtFront) { uint64_t runs = 100; seed_rand(); tf::TimeCache cache; std::vector<double> values(runs); StampedTransform t; t.setIdentity(); for ( uint64_t i = 0; i <runs ; i++ ) { values[i] = 10.0 * ((double) rand() - (double)RAND_MAX /2.0) /(double)RAND_MAX; t.stamp_ = ros::Time().fromNSec(i); TransformStorage stor(t, i, 0); cache.insertData(stor); } t.stamp_ = ros::Time().fromNSec(runs); TransformStorage stor(t, runs, 0); cache.insertData(stor); for ( uint64_t i = 1; i < runs ; i++ ) { cache.getData(ros::Time().fromNSec(i), stor); EXPECT_EQ(stor.frame_id_, i); EXPECT_EQ(stor.stamp_, ros::Time().fromNSec(i)); } cache.getData(ros::Time(), stor); EXPECT_EQ(stor.frame_id_, runs); EXPECT_EQ(stor.stamp_, ros::Time().fromNSec(runs)); t.stamp_ = ros::Time().fromNSec(runs+1); TransformStorage stor2(t, runs+1, 0); cache.insertData(stor2); //Make sure we get a different value now that a new values is added at the front cache.getData(ros::Time(), stor); EXPECT_EQ(stor.frame_id_, runs+1); EXPECT_EQ(stor.stamp_, ros::Time().fromNSec(runs+1)); } TEST(TimeCache, CartesianInterpolation) { uint64_t runs = 100; double epsilon = 1e-6; seed_rand(); tf::TimeCache cache; std::vector<double> xvalues(2); std::vector<double> yvalues(2); std::vector<double> zvalues(2); uint64_t offset = 200; StampedTransform t; t.setIdentity(); for ( uint64_t i = 1; i < runs ; i++ ) { for (uint64_t step = 0; step < 2 ; step++) { xvalues[step] = 10.0 * ((double) rand() - (double)RAND_MAX /2.0) /(double)RAND_MAX; yvalues[step] = 10.0 * ((double) rand() - (double)RAND_MAX /2.0) /(double)RAND_MAX; zvalues[step] = 10.0 * ((double) rand() - (double)RAND_MAX /2.0) /(double)RAND_MAX; t.setOrigin(btVector3(xvalues[step], yvalues[step], zvalues[step])); t.stamp_ = ros::Time().fromNSec(step * 100 + offset); TransformStorage stor(t, 2, 0); cache.insertData(stor); } TransformStorage out; for (int pos = 0; pos < 100 ; pos++) { cache.getData(ros::Time().fromNSec(offset + pos), out); double x_out = out.translation_.x(); double y_out = out.translation_.y(); double z_out = out.translation_.z(); EXPECT_NEAR(xvalues[0] + (xvalues[1] - xvalues[0]) * (double)pos/100.0, x_out, epsilon); EXPECT_NEAR(yvalues[0] + (yvalues[1] - yvalues[0]) * (double)pos/100.0, y_out, epsilon); EXPECT_NEAR(zvalues[0] + (zvalues[1] - zvalues[0]) * (double)pos/100.0, z_out, epsilon); } cache.clearList(); } } /* TEST IS BROKEN, NEED TO PREVENT THIS ///\brief Make sure we dont' interpolate across reparented data TEST(TimeCache, ReparentingInterpolationProtection) { double epsilon = 1e-6; uint64_t offset = 555; tf::TimeCache cache; std::vector<double> xvalues(2); std::vector<double> yvalues(2); std::vector<double> zvalues(2); StampedTransform t; t.setIdentity(); for (uint64_t step = 0; step < 2 ; step++) { xvalues[step] = 10.0 * ((double) rand() - (double)RAND_MAX /2.0) /(double)RAND_MAX; yvalues[step] = 10.0 * ((double) rand() - (double)RAND_MAX /2.0) /(double)RAND_MAX; zvalues[step] = 10.0 * ((double) rand() - (double)RAND_MAX /2.0) /(double)RAND_MAX; t.setOrigin(btVector3(xvalues[step], yvalues[step], zvalues[step])); t.stamp_ = ros::Time().fromNSec(step * 100 + offset); TransformStorage stor(t, step + 4, 0); cache.insertData(stor); } TransformStorage out; for (int pos = 0; pos < 100 ; pos ++) { EXPECT_TRUE(cache.getData(ros::Time().fromNSec(offset + pos), out)); double x_out = out.translation_.x(); double y_out = out.translation_.y(); double z_out = out.translation_.z(); EXPECT_NEAR(xvalues[0], x_out, epsilon); EXPECT_NEAR(yvalues[0], y_out, epsilon); EXPECT_NEAR(zvalues[0], z_out, epsilon); } for (int pos = 100; pos < 120 ; pos ++) { EXPECT_TRUE(cache.getData(ros::Time().fromNSec(offset + pos), out)); double x_out = out.translation_.x(); double y_out = out.translation_.y(); double z_out = out.translation_.z(); EXPECT_NEAR(xvalues[1], x_out, epsilon); EXPECT_NEAR(yvalues[1], y_out, epsilon); EXPECT_NEAR(zvalues[1], z_out, epsilon); } } // EXTRAPOLATION DISABLED TEST(TimeCache, CartesianExtrapolation) { uint64_t runs = 100; double epsilon = 1e-5; seed_rand(); tf::TimeCache cache; std::vector<double> xvalues(2); std::vector<double> yvalues(2); std::vector<double> zvalues(2); uint64_t offset = 555; StampedTransform t; t.setIdentity(); for ( uint64_t i = 1; i < runs ; i++ ) { for (uint64_t step = 0; step < 2 ; step++) { xvalues[step] = 10.0 * ((double) rand() - (double)RAND_MAX /2.0) /(double)RAND_MAX; yvalues[step] = 10.0 * ((double) rand() - (double)RAND_MAX /2.0) /(double)RAND_MAX; zvalues[step] = 10.0 * ((double) rand() - (double)RAND_MAX /2.0) /(double)RAND_MAX; t.setOrigin(btVector3(xvalues[step], yvalues[step], zvalues[step])); t.stamp_ = ros::Time().fromNSec(step * 100 + offset); TransformStorage stor(t, 2, 0); cache.insertData(stor); } TransformStorage out; for (int pos = -200; pos < 300 ; pos ++) { cache.getData(ros::Time().fromNSec(offset + pos), out); double x_out = out.translation_.x(); double y_out = out.translation_.y(); double z_out = out.translation_.z(); EXPECT_NEAR(xvalues[0] + (xvalues[1] - xvalues[0]) * (double)pos/100.0, x_out, epsilon); EXPECT_NEAR(yvalues[0] + (yvalues[1] - yvalues[0]) * (double)pos/100.0, y_out, epsilon); EXPECT_NEAR(zvalues[0] + (zvalues[1] - zvalues[0]) * (double)pos/100.0, z_out, epsilon); } cache.clearList(); } } */ TEST(Bullet, Slerp) { uint64_t runs = 100; seed_rand(); btQuaternion q1, q2; q1.setEuler(0,0,0); for (uint64_t i = 0 ; i < runs ; i++) { q2.setEuler(1.0 * ((double) rand() - (double)RAND_MAX /2.0) /(double)RAND_MAX, 1.0 * ((double) rand() - (double)RAND_MAX /2.0) /(double)RAND_MAX, 1.0 * ((double) rand() - (double)RAND_MAX /2.0) /(double)RAND_MAX); btQuaternion q3 = slerp(q1,q2,0.5); EXPECT_NEAR(q3.angle(q1), q2.angle(q3), 1e-5); } } TEST(TimeCache, AngularInterpolation) { uint64_t runs = 100; double epsilon = 1e-6; seed_rand(); tf::TimeCache cache; std::vector<double> yawvalues(2); std::vector<double> pitchvalues(2); std::vector<double> rollvalues(2); uint64_t offset = 200; std::vector<btQuaternion> quats(2); StampedTransform t; t.setIdentity(); for ( uint64_t i = 1; i < runs ; i++ ) { for (uint64_t step = 0; step < 2 ; step++) { yawvalues[step] = 10.0 * ((double) rand() - (double)RAND_MAX /2.0) /(double)RAND_MAX / 100.0; pitchvalues[step] = 0;//10.0 * ((double) rand() - (double)RAND_MAX /2.0) /(double)RAND_MAX; rollvalues[step] = 0;//10.0 * ((double) rand() - (double)RAND_MAX /2.0) /(double)RAND_MAX; quats[step].setRPY(yawvalues[step], pitchvalues[step], rollvalues[step]); t.setRotation(quats[step]); t.stamp_ = ros::Time().fromNSec(offset + (step * 100)); //step = 0 or 1 TransformStorage stor(t, 3, 0); cache.insertData(stor); } TransformStorage out; for (int pos = 0; pos < 100 ; pos ++) { cache.getData(ros::Time().fromNSec(offset + pos), out); //get the transform for the position btQuaternion quat = out.rotation_; //get the quaternion out of the transform //Generate a ground truth quaternion directly calling slerp btQuaternion ground_truth = quats[0].slerp(quats[1], pos/100.0); //Make sure the transformed one and the direct call match EXPECT_NEAR(0, angle(ground_truth, quat), epsilon); } cache.clearList(); } } TEST(TimeCache, DuplicateEntries) { TimeCache cache; StampedTransform t; t.setIdentity(); t.stamp_ = ros::Time().fromNSec(1); TransformStorage stor(t, 3, 0); cache.insertData(stor); cache.insertData(stor); cache.getData(ros::Time().fromNSec(1), stor); EXPECT_TRUE(!std::isnan(stor.translation_.x())); EXPECT_TRUE(!std::isnan(stor.translation_.y())); EXPECT_TRUE(!std::isnan(stor.translation_.z())); EXPECT_TRUE(!std::isnan(stor.rotation_.x())); EXPECT_TRUE(!std::isnan(stor.rotation_.y())); EXPECT_TRUE(!std::isnan(stor.rotation_.z())); EXPECT_TRUE(!std::isnan(stor.rotation_.w())); } int main(int argc, char **argv){ testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
[ "ziang.xie@berkeley.edu" ]
ziang.xie@berkeley.edu
a056b30e9a797d8a8c69e0f4a12d1e2f3ffacc94
28933f490396a61dd9556387bf6599e307cfc267
/CD_CNC.ino
6fef5b84254a3db05557eff9e49ac879ab27c558
[]
no_license
rekomerio/cd-tray-plotter
65108f49e4790fa35014bac4d5f46bdc448cc18c
7039d6ad34153464007740a8aa0223f2f48b9d3a
refs/heads/master
2020-07-08T05:45:02.033831
2020-01-09T14:33:33
2020-01-09T14:33:33
203,582,872
0
0
null
null
null
null
UTF-8
C++
false
false
8,325
ino
#include <Stepper.h> #include <Servo.h> #include <SymbolMap.h> #define REVERSE_X 1 #define REVERSE_Y 0 #define STEPS_PER_REV 20 #define MAX_STEPS 250 #define PEN_UP_ANGLE 50 #define PEN_DOWN_ANGLE 80 #define SERVO_DELAY (PEN_DOWN_ANGLE - PEN_UP_ANGLE) * 4 #define SERVO_PIN 10 #define LETTER_SPACING 2 #define PIXEL_SIZE 6 #define SYMBOL_HEIGHT 7 #define SYMBOL_WIDTH 8 /* Fill types */ #define VERTICAL 0 #define HORIZONTAL 1 #define BOTH 2 #define MAX_SYMBOLS 28 Stepper X_MOTOR(STEPS_PER_REV, 6, 7, 8, 9); Stepper Y_MOTOR(STEPS_PER_REV, 2, 3, 4, 5); Servo servo; SymbolMap symbols; struct point { uint8_t x, y, z; /* Directly initialize axis rather than assign new value after initialization. Constructor member initialization on Google. */ point() : x(0), y(0), z(0) {} point(uint8_t _x, uint8_t _y) : x(_x), y(_y), z(0) {} point(uint8_t _x, uint8_t _y, uint8_t _z) : x(_x), y(_y), z(_z) {} point operator + (const point& p) { return point(this->x + p.x, this->y + p.y); } point operator - (const point& p) { return point(this->x - p.x, this->y - p.y); } bool operator == (const point& p) { return (this->x == p.x && this->y == p.y && this->z == p.z); } bool operator != (const point& p) { return (this->x != p.x || this->y != p.y || this->z != p.z); } }; struct point rectangle[] = { {0, MAX_STEPS, 0}, {MAX_STEPS, MAX_STEPS, 0}, {MAX_STEPS , 0, 0}, {0, 0, 0} }; struct point shape[] = { {0, MAX_STEPS / 2, 0}, {MAX_STEPS / 2, MAX_STEPS, 0}, {MAX_STEPS, MAX_STEPS / 2, 0}, {MAX_STEPS / 2, 0, 0} }; struct point triangle[] = { {0, 0, 0}, {MAX_STEPS, 0, 0}, {0, MAX_STEPS, 0}, }; struct point line[] = { {0, 0, 0}, {118, 213, 0} }; struct point location = {0, 0, 0}; void setup() { Serial.begin(9600); X_MOTOR.setSpeed(1000); Y_MOTOR.setSpeed(1000); servo.attach(SERVO_PIN); penUp(); releaseMotors(); } void loop() { if (Serial.available()) { struct point node; String str = Serial.readString(); uint32_t coords = strtoul((const char *) &str[1], NULL, 16); uint8_t i = 1; uint8_t radius; switch (str[0]) { case '#': // Letter while (str[i]) { drawSymbol(symbols.getSymbol(str[i]), PIXEL_SIZE, HORIZONTAL); i++; } releaseMotors(); break; case 'v': // Vector node.x = coords >> 16 & 0xFF; node.y = coords >> 8 & 0xFF; node.z = coords >> 0 & 0xFF; if (node.x < MAX_STEPS && node.y < MAX_STEPS) { drawVector(node); releaseMotors(); } break; case 'c': // Circle node.x = coords >> 16 & 0xFF; node.y = coords >> 8 & 0xFF; radius = coords >> 0 & 0xFF; drawCircle({node.x, node.y, 0}, radius); break; } } Serial.println("!"); delay(10); } void drawShape (struct point nodes[], uint8_t len) { moveTo(nodes[0]); for (uint8_t i = 0; i < len + 1; i++) { drawVector(nodes[i % len]); } moveTo({0, 0}); releaseMotors(); } void drawVector(struct point node) { uint8_t xDistance = abs(node.x - location.x); //Distance to travel on x-axis uint8_t yDistance = abs(node.y - location.y); //Distance to travel on y-axis char longerAxis = xDistance > yDistance ? 'x' : 'y'; //Which axis has longer distance to travel float scale = (longerAxis == 'x') ? (float)(xDistance) / (float)(yDistance) : (float)(yDistance) / (float)(xDistance); while (location != node) { //Loop until motors reach target node moveZ(node.z); //Move the pen up/down if (scale < MAX_STEPS) { //If scale is equal to max steps, there is no need to limit other axis's switch (longerAxis) { case 'x': //x-axis travels freely, y-axis is limited moveX(node.x); if (yDistance * scale >= xDistance) { moveY(node.y); } break; case 'y': //y-axis travels freely, x-axis is limited moveY(node.y); if (xDistance * scale >= yDistance) { moveX(node.x); } break; } } else { moveX(node.x); moveY(node.y); } xDistance = abs(node.x - location.x); //Recalculate the distance for next loop yDistance = abs(node.y - location.y); } } /* Iterates through a whole column, then increases row and goes again */ void drawSymbol(char arr[SYMBOL_HEIGHT], uint8_t pixelSize, uint8_t fillType) { static uint8_t offsetY = 0; //If space is running out on X axis, move one row down if (arr == NULL) return; if (location.x + LETTER_SPACING * pixelSize + SYMBOL_WIDTH * pixelSize >= MAX_STEPS) { moveTo({0, location.y + pixelSize * LETTER_SPACING}); offsetY = location.y; } uint8_t offsetX = location.x + pixelSize * LETTER_SPACING; struct point pixel; for (uint8_t x = 0; x < SYMBOL_WIDTH; x++) { for (uint8_t y = 0; y < SYMBOL_HEIGHT; y++) { if (arr[y] >> SYMBOL_WIDTH - 1 - x & 1) { pixel = {pixelSize * x + offsetX, pixelSize * y + offsetY}; switch (fillType) { case VERTICAL: verticalFill(pixel, pixelSize); break; case HORIZONTAL: horizontalFill(pixel, pixelSize); break; case BOTH: horizontalFill(pixel, pixelSize); verticalFill(pixel, pixelSize); break; default: horizontalFill(pixel, pixelSize); } } } } } void horizontalFill(struct point start, uint8_t pixelSize) { uint8_t i = start.y; if (location != start) { moveTo(start); } while (i <= start.y + pixelSize) { drawVector({ i % 2 == 0 ? start.x : start.x + pixelSize, i, 0}); i++; } } void verticalFill(struct point start, uint8_t pixelSize) { uint8_t i = start.x; if (location != start) { moveTo(start); } while (i <= start.x + pixelSize) { drawVector({ i, i % 2 == 0 ? start.y : start.y + pixelSize, 0}); i++; } } void drawCircle(struct point center, uint8_t radius) { for (uint16_t i = 0; i <= 360 + 10; i++) { uint8_t x = center.x + sin((float)(i) * PI / 180) * radius; uint8_t y = center.y + cos((float)(i) * PI / 180) * radius; if (!i) { moveTo({x, y}); penDown(); } drawVector({x, y, 0}); } } void moveX(uint8_t x) { if (location.x < x) { //Step one step forward on x-axis, if location on x-axis is less than target #if REVERSE_X X_MOTOR.step(-1); #else X_MOTOR.step(1); #endif location.x++; } else if (location.x > x) { //Step one step back on x-axis, if location on x-axis is higher than target #if REVERSE_X X_MOTOR.step(1); #else X_MOTOR.step(-1); #endif location.x--; } } void moveY(uint8_t y) { if (location.y < y) { //Step one step forward on y-axis, if location on y-axis is less than target #if REVERSE_Y Y_MOTOR.step(-1); #else Y_MOTOR.step(1); #endif location.y++; } else if (location.y > y) { //Step one step back on y-axis, if location on y-axis is higher than target #if REVERSE_Y Y_MOTOR.step(1); #else Y_MOTOR.step(-1); #endif location.y--; } } void moveZ(uint8_t z) { if (z && !location.z) { //Lift the pen up if Z is 1 and pen is down penUp(); } else if (!z && location.z) { //Release the pen down if Z is 0 and pen is up penDown(); } } /* Move the pen to target location while pen is held up */ void moveTo(struct point node) { penUp(); #if REVERSE_X X_MOTOR.step(location.x - node.x); #else X_MOTOR.step(node.x - location.x); #endif #if REVERSE_Y Y_MOTOR.step(location.y - node.y); #else Y_MOTOR.step(node.y - location.y); #endif location.x = node.x; location.y = node.y; } void penUp() { servo.write(PEN_UP_ANGLE); location.z = 1; delay(SERVO_DELAY); } void penDown() { servo.write(PEN_DOWN_ANGLE); location.z = 0; delay(SERVO_DELAY); } /* Drive stepper motor pins low, so they can be moved freely and so they don't consume power */ void releaseMotors() { for (uint8_t i = 2; i < 10; i++) { digitalWrite(i, LOW); } }
[ "K9260@student.jamk.fi" ]
K9260@student.jamk.fi
95fdb343918ffb210c64dd0f1bb656e32d10c823
0d3e1da98d51cd32803138fe76e04fdfa48f7a09
/2000/BOJ 2517.cpp
535bc5b67929dc94f196c5148b2f4ec29ac83b2b
[]
no_license
bsgreentea/PS
75648a505fa2fc7514cc810ea07e4728581443d1
25fdbe6cdc91731312efaee69c22f2b33e368430
refs/heads/master
2021-07-01T11:53:37.091403
2020-10-16T15:02:20
2020-10-16T15:02:20
163,829,035
0
0
null
null
null
null
UTF-8
C++
false
false
1,144
cpp
#include <cstdio> #include <vector> #include <algorithm> #include <utility> using namespace std; const int MAX = 500000; int n, tree[4 * MAX + 1], res[MAX + 1]; vector<pair<int, int>> vt; int update(int pos, int node, int start, int end) { if (pos < start || end < pos) return tree[node]; if (start == end) return tree[node] = 1; int mid = (start + end) / 2; return tree[node] = update(pos, node * 2, start, mid) + update(pos, node * 2 + 1, mid + 1, end); } int query(int left, int right, int node, int start, int end) { if (right < start || end < left) return 0; if (left <= start && end <= right) return tree[node]; int mid = (start + end) / 2; return query(left, right, node * 2, start, mid) + query(left, right, node * 2 + 1, mid + 1, end); } int main() { scanf("%d", &n); vt.resize(n); int a; for (int i = 0; i < n; i++) { scanf("%d", &a); vt[i] = { a,i + 1 }; } sort(vt.begin(), vt.end()); reverse(vt.begin(), vt.end()); for (int i = 0; i < n; i++) { res[vt[i].second] = query(1, vt[i].second, 1, 1, n) + 1; update(vt[i].second, 1, 1, n); } for (int i = 1; i <= n; i++) printf("%d\n", res[i]); }
[ "46317084+bsgreentea@users.noreply.github.com" ]
46317084+bsgreentea@users.noreply.github.com
374738f274ec39b4d58b94dfa8fd31b791a5f7b3
1f032ac06a2fc792859a57099e04d2b9bc43f387
/25/60/b4/e6/0ce9bb0c79968da5255a3a0e1b7556633c3e9d9954d6d84ebd267a469de39d6e793e99a9b9d2b850a180fc4fab84e9051256d2111ee7481c0aa53dff/sw.cpp
baf08066952f3bcfc106f5910dabff00940a320a
[]
no_license
SoftwareNetwork/specifications
9d6d97c136d2b03af45669bad2bcb00fda9d2e26
ba960f416e4728a43aa3e41af16a7bdd82006ec3
refs/heads/master
2023-08-16T13:17:25.996674
2023-08-15T10:45:47
2023-08-15T10:45:47
145,738,888
0
0
null
null
null
null
UTF-8
C++
false
false
250
cpp
void build(Solution &s) { auto &wr = s.addTarget<StaticLibraryTarget>("giovannidicanio.winreg", "master"); wr += Git("https://github.com/GiovanniDicanio/WinReg", "", "{b}"); wr.setRootDirectory("WinReg/WinReg"); wr += "WinReg.hpp"; }
[ "egor.pugin@gmail.com" ]
egor.pugin@gmail.com
f265290182e056c0a1ee84ef49922502b2cc5eac
78fd33998d6d0aa3714ba5bc88f062360e51de16
/test.cpp
be22c8c51cc42bb80b810628b05adfe20ca69f40
[]
no_license
vishwakarma/faculty_scheduling
ca1a9f74754fe57f55c53d5121dd7370955b163a
f51cad3a32b6ef84fa8fefa5dd160d1b00468231
refs/heads/master
2021-03-27T13:46:41.770686
2016-11-15T12:20:35
2016-11-15T12:20:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
140
cpp
#include <iostream> using namespace std; int main() { int j = 0; for(int i=0;i<2011637;i++){ j++; } cout << j << "\n"; return 0; }
[ "vishwakarma.iiita@@gmail.com" ]
vishwakarma.iiita@@gmail.com
0189131b46a254dc23df44ab64744fc1e7bf0011
e299ad494a144cc6cfebcd45b10ddcc8efab54a9
/llvm/include/llvm/Support/FileSystem.h
48ff224bcd348368e5e9e615bfa5c5306db36a71
[ "NCSA" ]
permissive
apple-oss-distributions/lldb
3dbd2fea5ce826b2bebec2fe88fadbca771efbdf
10de1840defe0dff10b42b9c56971dbc17c1f18c
refs/heads/main
2023-08-02T21:31:38.525968
2014-04-11T21:20:22
2021-10-06T05:26:12
413,590,587
4
1
null
null
null
null
UTF-8
C++
false
false
34,960
h
//===- llvm/Support/FileSystem.h - File System OS Concept -------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file declares the llvm::sys::fs namespace. It is designed after // TR2/boost filesystem (v3), but modified to remove exception handling and the // path class. // // All functions return an error_code and their actual work via the last out // argument. The out argument is defined if and only if errc::success is // returned. A function may return any error code in the generic or system // category. However, they shall be equivalent to any error conditions listed // in each functions respective documentation if the condition applies. [ note: // this does not guarantee that error_code will be in the set of explicitly // listed codes, but it does guarantee that if any of the explicitly listed // errors occur, the correct error_code will be used ]. All functions may // return errc::not_enough_memory if there is not enough memory to complete the // operation. // //===----------------------------------------------------------------------===// #ifndef LLVM_SUPPORT_FILESYSTEM_H #define LLVM_SUPPORT_FILESYSTEM_H #include "llvm/ADT/IntrusiveRefCntPtr.h" #include "llvm/ADT/OwningPtr.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/Twine.h" #include "llvm/Support/DataTypes.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/TimeValue.h" #include "llvm/Support/system_error.h" #include <ctime> #include <iterator> #include <stack> #include <string> #include <vector> #ifdef HAVE_SYS_STAT_H #include <sys/stat.h> #endif namespace llvm { namespace sys { namespace fs { /// file_type - An "enum class" enumeration for the file system's view of the /// type. struct file_type { enum _ { status_error, file_not_found, regular_file, directory_file, symlink_file, block_file, character_file, fifo_file, socket_file, type_unknown }; file_type(_ v) : v_(v) {} explicit file_type(int v) : v_(_(v)) {} operator int() const {return v_;} private: int v_; }; /// space_info - Self explanatory. struct space_info { uint64_t capacity; uint64_t free; uint64_t available; }; enum perms { no_perms = 0, owner_read = 0400, owner_write = 0200, owner_exe = 0100, owner_all = owner_read | owner_write | owner_exe, group_read = 040, group_write = 020, group_exe = 010, group_all = group_read | group_write | group_exe, others_read = 04, others_write = 02, others_exe = 01, others_all = others_read | others_write | others_exe, all_read = owner_read | group_read | others_read, all_write = owner_write | group_write | others_write, all_exe = owner_exe | group_exe | others_exe, all_all = owner_all | group_all | others_all, set_uid_on_exe = 04000, set_gid_on_exe = 02000, sticky_bit = 01000, perms_not_known = 0xFFFF }; // Helper functions so that you can use & and | to manipulate perms bits: inline perms operator|(perms l , perms r) { return static_cast<perms>( static_cast<unsigned short>(l) | static_cast<unsigned short>(r)); } inline perms operator&(perms l , perms r) { return static_cast<perms>( static_cast<unsigned short>(l) & static_cast<unsigned short>(r)); } inline perms &operator|=(perms &l, perms r) { l = l | r; return l; } inline perms &operator&=(perms &l, perms r) { l = l & r; return l; } inline perms operator~(perms x) { return static_cast<perms>(~static_cast<unsigned short>(x)); } class UniqueID { uint64_t Device; uint64_t File; public: UniqueID() {} UniqueID(uint64_t Device, uint64_t File) : Device(Device), File(File) {} bool operator==(const UniqueID &Other) const { return Device == Other.Device && File == Other.File; } bool operator!=(const UniqueID &Other) const { return !(*this == Other); } bool operator<(const UniqueID &Other) const { return Device < Other.Device || (Device == Other.Device && File < Other.File); } uint64_t getDevice() const { return Device; } uint64_t getFile() const { return File; } }; /// file_status - Represents the result of a call to stat and friends. It has /// a platform specific member to store the result. class file_status { #if defined(LLVM_ON_UNIX) dev_t fs_st_dev; ino_t fs_st_ino; time_t fs_st_mtime; uid_t fs_st_uid; gid_t fs_st_gid; off_t fs_st_size; #elif defined (LLVM_ON_WIN32) uint32_t LastWriteTimeHigh; uint32_t LastWriteTimeLow; uint32_t VolumeSerialNumber; uint32_t FileSizeHigh; uint32_t FileSizeLow; uint32_t FileIndexHigh; uint32_t FileIndexLow; #endif friend bool equivalent(file_status A, file_status B); file_type Type; perms Perms; public: file_status() : Type(file_type::status_error) {} file_status(file_type Type) : Type(Type) {} #if defined(LLVM_ON_UNIX) file_status(file_type Type, perms Perms, dev_t Dev, ino_t Ino, time_t MTime, uid_t UID, gid_t GID, off_t Size) : fs_st_dev(Dev), fs_st_ino(Ino), fs_st_mtime(MTime), fs_st_uid(UID), fs_st_gid(GID), fs_st_size(Size), Type(Type), Perms(Perms) {} #elif defined(LLVM_ON_WIN32) file_status(file_type Type, uint32_t LastWriteTimeHigh, uint32_t LastWriteTimeLow, uint32_t VolumeSerialNumber, uint32_t FileSizeHigh, uint32_t FileSizeLow, uint32_t FileIndexHigh, uint32_t FileIndexLow) : LastWriteTimeHigh(LastWriteTimeHigh), LastWriteTimeLow(LastWriteTimeLow), VolumeSerialNumber(VolumeSerialNumber), FileSizeHigh(FileSizeHigh), FileSizeLow(FileSizeLow), FileIndexHigh(FileIndexHigh), FileIndexLow(FileIndexLow), Type(Type), Perms(perms_not_known) {} #endif // getters file_type type() const { return Type; } perms permissions() const { return Perms; } TimeValue getLastModificationTime() const; UniqueID getUniqueID() const; #if defined(LLVM_ON_UNIX) uint32_t getUser() const { return fs_st_uid; } uint32_t getGroup() const { return fs_st_gid; } uint64_t getSize() const { return fs_st_size; } #elif defined (LLVM_ON_WIN32) uint32_t getUser() const { return 9999; // Not applicable to Windows, so... } uint32_t getGroup() const { return 9999; // Not applicable to Windows, so... } uint64_t getSize() const { return (uint64_t(FileSizeHigh) << 32) + FileSizeLow; } #endif // setters void type(file_type v) { Type = v; } void permissions(perms p) { Perms = p; } }; /// file_magic - An "enum class" enumeration of file types based on magic (the first /// N bytes of the file). struct file_magic { enum Impl { unknown = 0, ///< Unrecognized file bitcode, ///< Bitcode file archive, ///< ar style archive file elf_relocatable, ///< ELF Relocatable object file elf_executable, ///< ELF Executable image elf_shared_object, ///< ELF dynamically linked shared lib elf_core, ///< ELF core image macho_object, ///< Mach-O Object file macho_executable, ///< Mach-O Executable macho_fixed_virtual_memory_shared_lib, ///< Mach-O Shared Lib, FVM macho_core, ///< Mach-O Core File macho_preload_executable, ///< Mach-O Preloaded Executable macho_dynamically_linked_shared_lib, ///< Mach-O dynlinked shared lib macho_dynamic_linker, ///< The Mach-O dynamic linker macho_bundle, ///< Mach-O Bundle file macho_dynamically_linked_shared_lib_stub, ///< Mach-O Shared lib stub macho_dsym_companion, ///< Mach-O dSYM companion file macho_universal_binary, ///< Mach-O universal binary coff_object, ///< COFF object file pecoff_executable, ///< PECOFF executable file windows_resource ///< Windows compiled resource file (.rc) }; bool is_object() const { return V == unknown ? false : true; } file_magic() : V(unknown) {} file_magic(Impl V) : V(V) {} operator Impl() const { return V; } private: Impl V; }; /// @} /// @name Physical Operators /// @{ /// @brief Make \a path an absolute path. /// /// Makes \a path absolute using the current directory if it is not already. An /// empty \a path will result in the current directory. /// /// /absolute/path => /absolute/path /// relative/../path => <current-directory>/relative/../path /// /// @param path A path that is modified to be an absolute path. /// @returns errc::success if \a path has been made absolute, otherwise a /// platform specific error_code. error_code make_absolute(SmallVectorImpl<char> &path); /// @brief Create all the non-existent directories in path. /// /// @param path Directories to create. /// @param existed Set to true if \a path already existed, false otherwise. /// @returns errc::success if is_directory(path) and existed have been set, /// otherwise a platform specific error_code. error_code create_directories(const Twine &path, bool &existed); /// @brief Convenience function for clients that don't need to know if the /// directory existed or not. inline error_code create_directories(const Twine &Path) { bool Existed; return create_directories(Path, Existed); } /// @brief Create the directory in path. /// /// @param path Directory to create. /// @param existed Set to true if \a path already existed, false otherwise. /// @returns errc::success if is_directory(path) and existed have been set, /// otherwise a platform specific error_code. error_code create_directory(const Twine &path, bool &existed); /// @brief Convenience function for clients that don't need to know if the /// directory existed or not. inline error_code create_directory(const Twine &Path) { bool Existed; return create_directory(Path, Existed); } /// @brief Create a hard link from \a from to \a to. /// /// @param to The path to hard link to. /// @param from The path to hard link from. This is created. /// @returns errc::success if exists(to) && exists(from) && equivalent(to, from) /// , otherwise a platform specific error_code. error_code create_hard_link(const Twine &to, const Twine &from); /// @brief Create a symbolic link from \a from to \a to. /// /// @param to The path to symbolically link to. /// @param from The path to symbolically link from. This is created. /// @returns errc::success if exists(to) && exists(from) && is_symlink(from), /// otherwise a platform specific error_code. error_code create_symlink(const Twine &to, const Twine &from); /// @brief Get the current path. /// /// @param result Holds the current path on return. /// @returns errc::success if the current path has been stored in result, /// otherwise a platform specific error_code. error_code current_path(SmallVectorImpl<char> &result); /// @brief Remove path. Equivalent to POSIX remove(). /// /// @param path Input path. /// @param existed Set to true if \a path existed, false if it did not. /// undefined otherwise. /// @returns errc::success if path has been removed and existed has been /// successfully set, otherwise a platform specific error_code. error_code remove(const Twine &path, bool &existed); /// @brief Convenience function for clients that don't need to know if the file /// existed or not. inline error_code remove(const Twine &Path) { bool Existed; return remove(Path, Existed); } /// @brief Recursively remove all files below \a path, then \a path. Files are /// removed as if by POSIX remove(). /// /// @param path Input path. /// @param num_removed Number of files removed. /// @returns errc::success if path has been removed and num_removed has been /// successfully set, otherwise a platform specific error_code. error_code remove_all(const Twine &path, uint32_t &num_removed); /// @brief Convenience function for clients that don't need to know how many /// files were removed. inline error_code remove_all(const Twine &Path) { uint32_t Removed; return remove_all(Path, Removed); } /// @brief Rename \a from to \a to. Files are renamed as if by POSIX rename(). /// /// @param from The path to rename from. /// @param to The path to rename to. This is created. error_code rename(const Twine &from, const Twine &to); /// @brief Resize path to size. File is resized as if by POSIX truncate(). /// /// @param path Input path. /// @param size Size to resize to. /// @returns errc::success if \a path has been resized to \a size, otherwise a /// platform specific error_code. error_code resize_file(const Twine &path, uint64_t size); /// @} /// @name Physical Observers /// @{ /// @brief Does file exist? /// /// @param status A file_status previously returned from stat. /// @returns True if the file represented by status exists, false if it does /// not. bool exists(file_status status); /// @brief Does file exist? /// /// @param path Input path. /// @param result Set to true if the file represented by status exists, false if /// it does not. Undefined otherwise. /// @returns errc::success if result has been successfully set, otherwise a /// platform specific error_code. error_code exists(const Twine &path, bool &result); /// @brief Simpler version of exists for clients that don't need to /// differentiate between an error and false. inline bool exists(const Twine &path) { bool result; return !exists(path, result) && result; } /// @brief Can we execute this file? /// /// @param Path Input path. /// @returns True if we can execute it, false otherwise. bool can_execute(const Twine &Path); /// @brief Can we write this file? /// /// @param Path Input path. /// @returns True if we can write to it, false otherwise. bool can_write(const Twine &Path); /// @brief Do file_status's represent the same thing? /// /// @param A Input file_status. /// @param B Input file_status. /// /// assert(status_known(A) || status_known(B)); /// /// @returns True if A and B both represent the same file system entity, false /// otherwise. bool equivalent(file_status A, file_status B); /// @brief Do paths represent the same thing? /// /// assert(status_known(A) || status_known(B)); /// /// @param A Input path A. /// @param B Input path B. /// @param result Set to true if stat(A) and stat(B) have the same device and /// inode (or equivalent). /// @returns errc::success if result has been successfully set, otherwise a /// platform specific error_code. error_code equivalent(const Twine &A, const Twine &B, bool &result); /// @brief Simpler version of equivalent for clients that don't need to /// differentiate between an error and false. inline bool equivalent(const Twine &A, const Twine &B) { bool result; return !equivalent(A, B, result) && result; } /// @brief Does status represent a directory? /// /// @param status A file_status previously returned from status. /// @returns status.type() == file_type::directory_file. bool is_directory(file_status status); /// @brief Is path a directory? /// /// @param path Input path. /// @param result Set to true if \a path is a directory, false if it is not. /// Undefined otherwise. /// @returns errc::success if result has been successfully set, otherwise a /// platform specific error_code. error_code is_directory(const Twine &path, bool &result); /// @brief Simpler version of is_directory for clients that don't need to /// differentiate between an error and false. inline bool is_directory(const Twine &Path) { bool Result; return !is_directory(Path, Result) && Result; } /// @brief Does status represent a regular file? /// /// @param status A file_status previously returned from status. /// @returns status_known(status) && status.type() == file_type::regular_file. bool is_regular_file(file_status status); /// @brief Is path a regular file? /// /// @param path Input path. /// @param result Set to true if \a path is a regular file, false if it is not. /// Undefined otherwise. /// @returns errc::success if result has been successfully set, otherwise a /// platform specific error_code. error_code is_regular_file(const Twine &path, bool &result); /// @brief Simpler version of is_regular_file for clients that don't need to /// differentiate between an error and false. inline bool is_regular_file(const Twine &Path) { bool Result; if (is_regular_file(Path, Result)) return false; return Result; } /// @brief Does this status represent something that exists but is not a /// directory, regular file, or symlink? /// /// @param status A file_status previously returned from status. /// @returns exists(s) && !is_regular_file(s) && !is_directory(s) && /// !is_symlink(s) bool is_other(file_status status); /// @brief Is path something that exists but is not a directory, /// regular file, or symlink? /// /// @param path Input path. /// @param result Set to true if \a path exists, but is not a directory, regular /// file, or a symlink, false if it does not. Undefined otherwise. /// @returns errc::success if result has been successfully set, otherwise a /// platform specific error_code. error_code is_other(const Twine &path, bool &result); /// @brief Does status represent a symlink? /// /// @param status A file_status previously returned from stat. /// @returns status.type() == symlink_file. bool is_symlink(file_status status); /// @brief Is path a symlink? /// /// @param path Input path. /// @param result Set to true if \a path is a symlink, false if it is not. /// Undefined otherwise. /// @returns errc::success if result has been successfully set, otherwise a /// platform specific error_code. error_code is_symlink(const Twine &path, bool &result); /// @brief Get file status as if by POSIX stat(). /// /// @param path Input path. /// @param result Set to the file status. /// @returns errc::success if result has been successfully set, otherwise a /// platform specific error_code. error_code status(const Twine &path, file_status &result); /// @brief A version for when a file descriptor is already available. error_code status(int FD, file_status &Result); /// @brief Get file size. /// /// @param Path Input path. /// @param Result Set to the size of the file in \a Path. /// @returns errc::success if result has been successfully set, otherwise a /// platform specific error_code. inline error_code file_size(const Twine &Path, uint64_t &Result) { file_status Status; error_code EC = status(Path, Status); if (EC) return EC; Result = Status.getSize(); return error_code::success(); } error_code setLastModificationAndAccessTime(int FD, TimeValue Time); /// @brief Is status available? /// /// @param s Input file status. /// @returns True if status() != status_error. bool status_known(file_status s); /// @brief Is status available? /// /// @param path Input path. /// @param result Set to true if status() != status_error. /// @returns errc::success if result has been successfully set, otherwise a /// platform specific error_code. error_code status_known(const Twine &path, bool &result); /// @brief Create a uniquely named file. /// /// Generates a unique path suitable for a temporary file and then opens it as a /// file. The name is based on \a model with '%' replaced by a random char in /// [0-9a-f]. If \a model is not an absolute path, a suitable temporary /// directory will be prepended. /// /// Example: clang-%%-%%-%%-%%-%%.s => clang-a0-b1-c2-d3-e4.s /// /// This is an atomic operation. Either the file is created and opened, or the /// file system is left untouched. /// /// The intendend use is for files that are to be kept, possibly after /// renaming them. For example, when running 'clang -c foo.o', the file can /// be first created as foo-abc123.o and then renamed. /// /// @param Model Name to base unique path off of. /// @param ResultFD Set to the opened file's file descriptor. /// @param ResultPath Set to the opened file's absolute path. /// @returns errc::success if Result{FD,Path} have been successfully set, /// otherwise a platform specific error_code. error_code createUniqueFile(const Twine &Model, int &ResultFD, SmallVectorImpl<char> &ResultPath, unsigned Mode = all_read | all_write); /// @brief Simpler version for clients that don't want an open file. error_code createUniqueFile(const Twine &Model, SmallVectorImpl<char> &ResultPath); /// @brief Create a file in the system temporary directory. /// /// The filename is of the form prefix-random_chars.suffix. Since the directory /// is not know to the caller, Prefix and Suffix cannot have path separators. /// The files are created with mode 0600. /// /// This should be used for things like a temporary .s that is removed after /// running the assembler. error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix, int &ResultFD, SmallVectorImpl<char> &ResultPath); /// @brief Simpler version for clients that don't want an open file. error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix, SmallVectorImpl<char> &ResultPath); error_code createUniqueDirectory(const Twine &Prefix, SmallVectorImpl<char> &ResultPath); enum OpenFlags { F_None = 0, /// F_Excl - When opening a file, this flag makes raw_fd_ostream /// report an error if the file already exists. F_Excl = 1, /// F_Append - When opening a file, if it already exists append to the /// existing file instead of returning an error. This may not be specified /// with F_Excl. F_Append = 2, /// F_Binary - The file should be opened in binary mode on platforms that /// make this distinction. F_Binary = 4 }; inline OpenFlags operator|(OpenFlags A, OpenFlags B) { return OpenFlags(unsigned(A) | unsigned(B)); } inline OpenFlags &operator|=(OpenFlags &A, OpenFlags B) { A = A | B; return A; } error_code openFileForWrite(const Twine &Name, int &ResultFD, OpenFlags Flags, unsigned Mode = 0666); error_code openFileForRead(const Twine &Name, int &ResultFD); /// @brief Are \a path's first bytes \a magic? /// /// @param path Input path. /// @param magic Byte sequence to compare \a path's first len(magic) bytes to. /// @returns errc::success if result has been successfully set, otherwise a /// platform specific error_code. error_code has_magic(const Twine &path, const Twine &magic, bool &result); /// @brief Get \a path's first \a len bytes. /// /// @param path Input path. /// @param len Number of magic bytes to get. /// @param result Set to the first \a len bytes in the file pointed to by /// \a path. Or the entire file if file_size(path) < len, in which /// case result.size() returns the size of the file. /// @returns errc::success if result has been successfully set, /// errc::value_too_large if len is larger then the file pointed to by /// \a path, otherwise a platform specific error_code. error_code get_magic(const Twine &path, uint32_t len, SmallVectorImpl<char> &result); /// @brief Identify the type of a binary file based on how magical it is. file_magic identify_magic(StringRef magic); /// @brief Get and identify \a path's type based on its content. /// /// @param path Input path. /// @param result Set to the type of file, or file_magic::unknown. /// @returns errc::success if result has been successfully set, otherwise a /// platform specific error_code. error_code identify_magic(const Twine &path, file_magic &result); error_code getUniqueID(const Twine Path, UniqueID &Result); /// This class represents a memory mapped file. It is based on /// boost::iostreams::mapped_file. class mapped_file_region { mapped_file_region() LLVM_DELETED_FUNCTION; mapped_file_region(mapped_file_region&) LLVM_DELETED_FUNCTION; mapped_file_region &operator =(mapped_file_region&) LLVM_DELETED_FUNCTION; public: enum mapmode { readonly, ///< May only access map via const_data as read only. readwrite, ///< May access map via data and modify it. Written to path. priv ///< May modify via data, but changes are lost on destruction. }; private: /// Platform specific mapping state. mapmode Mode; uint64_t Size; void *Mapping; #ifdef LLVM_ON_WIN32 int FileDescriptor; void *FileHandle; void *FileMappingHandle; #endif error_code init(int FD, bool CloseFD, uint64_t Offset); public: typedef char char_type; #if LLVM_HAS_RVALUE_REFERENCES mapped_file_region(mapped_file_region&&); mapped_file_region &operator =(mapped_file_region&&); #endif /// Construct a mapped_file_region at \a path starting at \a offset of length /// \a length and with access \a mode. /// /// \param path Path to the file to map. If it does not exist it will be /// created. /// \param mode How to map the memory. /// \param length Number of bytes to map in starting at \a offset. If the file /// is shorter than this, it will be extended. If \a length is /// 0, the entire file will be mapped. /// \param offset Byte offset from the beginning of the file where the map /// should begin. Must be a multiple of /// mapped_file_region::alignment(). /// \param ec This is set to errc::success if the map was constructed /// successfully. Otherwise it is set to a platform dependent error. mapped_file_region(const Twine &path, mapmode mode, uint64_t length, uint64_t offset, error_code &ec); /// \param fd An open file descriptor to map. mapped_file_region takes /// ownership if closefd is true. It must have been opended in the correct /// mode. mapped_file_region(int fd, bool closefd, mapmode mode, uint64_t length, uint64_t offset, error_code &ec); ~mapped_file_region(); mapmode flags() const; uint64_t size() const; char *data() const; /// Get a const view of the data. Modifying this memory has undefined /// behavior. const char *const_data() const; /// \returns The minimum alignment offset must be. static int alignment(); }; /// @brief Memory maps the contents of a file /// /// @param path Path to file to map. /// @param file_offset Byte offset in file where mapping should begin. /// @param size Byte length of range of the file to map. /// @param map_writable If true, the file will be mapped in r/w such /// that changes to the mapped buffer will be flushed back /// to the file. If false, the file will be mapped read-only /// and the buffer will be read-only. /// @param result Set to the start address of the mapped buffer. /// @returns errc::success if result has been successfully set, otherwise a /// platform specific error_code. error_code map_file_pages(const Twine &path, off_t file_offset, size_t size, bool map_writable, void *&result); /// @brief Memory unmaps the contents of a file /// /// @param base Pointer to the start of the buffer. /// @param size Byte length of the range to unmmap. /// @returns errc::success if result has been successfully set, otherwise a /// platform specific error_code. error_code unmap_file_pages(void *base, size_t size); /// Return the path to the main executable, given the value of argv[0] from /// program startup and the address of main itself. In extremis, this function /// may fail and return an empty path. std::string getMainExecutable(const char *argv0, void *MainExecAddr); /// @} /// @name Iterators /// @{ /// directory_entry - A single entry in a directory. Caches the status either /// from the result of the iteration syscall, or the first time status is /// called. class directory_entry { std::string Path; mutable file_status Status; public: explicit directory_entry(const Twine &path, file_status st = file_status()) : Path(path.str()) , Status(st) {} directory_entry() {} void assign(const Twine &path, file_status st = file_status()) { Path = path.str(); Status = st; } void replace_filename(const Twine &filename, file_status st = file_status()); const std::string &path() const { return Path; } error_code status(file_status &result) const; bool operator==(const directory_entry& rhs) const { return Path == rhs.Path; } bool operator!=(const directory_entry& rhs) const { return !(*this == rhs); } bool operator< (const directory_entry& rhs) const; bool operator<=(const directory_entry& rhs) const; bool operator> (const directory_entry& rhs) const; bool operator>=(const directory_entry& rhs) const; }; namespace detail { struct DirIterState; error_code directory_iterator_construct(DirIterState&, StringRef); error_code directory_iterator_increment(DirIterState&); error_code directory_iterator_destruct(DirIterState&); /// DirIterState - Keeps state for the directory_iterator. It is reference /// counted in order to preserve InputIterator semantics on copy. struct DirIterState : public RefCountedBase<DirIterState> { DirIterState() : IterationHandle(0) {} ~DirIterState() { directory_iterator_destruct(*this); } intptr_t IterationHandle; directory_entry CurrentEntry; }; } /// directory_iterator - Iterates through the entries in path. There is no /// operator++ because we need an error_code. If it's really needed we can make /// it call report_fatal_error on error. class directory_iterator { IntrusiveRefCntPtr<detail::DirIterState> State; public: explicit directory_iterator(const Twine &path, error_code &ec) { State = new detail::DirIterState; SmallString<128> path_storage; ec = detail::directory_iterator_construct(*State, path.toStringRef(path_storage)); } explicit directory_iterator(const directory_entry &de, error_code &ec) { State = new detail::DirIterState; ec = detail::directory_iterator_construct(*State, de.path()); } /// Construct end iterator. directory_iterator() : State(0) {} // No operator++ because we need error_code. directory_iterator &increment(error_code &ec) { ec = directory_iterator_increment(*State); return *this; } const directory_entry &operator*() const { return State->CurrentEntry; } const directory_entry *operator->() const { return &State->CurrentEntry; } bool operator==(const directory_iterator &RHS) const { if (State == RHS.State) return true; if (RHS.State == 0) return State->CurrentEntry == directory_entry(); if (State == 0) return RHS.State->CurrentEntry == directory_entry(); return State->CurrentEntry == RHS.State->CurrentEntry; } bool operator!=(const directory_iterator &RHS) const { return !(*this == RHS); } // Other members as required by // C++ Std, 24.1.1 Input iterators [input.iterators] }; namespace detail { /// RecDirIterState - Keeps state for the recursive_directory_iterator. It is /// reference counted in order to preserve InputIterator semantics on copy. struct RecDirIterState : public RefCountedBase<RecDirIterState> { RecDirIterState() : Level(0) , HasNoPushRequest(false) {} std::stack<directory_iterator, std::vector<directory_iterator> > Stack; uint16_t Level; bool HasNoPushRequest; }; } /// recursive_directory_iterator - Same as directory_iterator except for it /// recurses down into child directories. class recursive_directory_iterator { IntrusiveRefCntPtr<detail::RecDirIterState> State; public: recursive_directory_iterator() {} explicit recursive_directory_iterator(const Twine &path, error_code &ec) : State(new detail::RecDirIterState) { State->Stack.push(directory_iterator(path, ec)); if (State->Stack.top() == directory_iterator()) State.reset(); } // No operator++ because we need error_code. recursive_directory_iterator &increment(error_code &ec) { const directory_iterator end_itr; if (State->HasNoPushRequest) State->HasNoPushRequest = false; else { file_status st; if ((ec = State->Stack.top()->status(st))) return *this; if (is_directory(st)) { State->Stack.push(directory_iterator(*State->Stack.top(), ec)); if (ec) return *this; if (State->Stack.top() != end_itr) { ++State->Level; return *this; } State->Stack.pop(); } } while (!State->Stack.empty() && State->Stack.top().increment(ec) == end_itr) { State->Stack.pop(); --State->Level; } // Check if we are done. If so, create an end iterator. if (State->Stack.empty()) State.reset(); return *this; } const directory_entry &operator*() const { return *State->Stack.top(); } const directory_entry *operator->() const { return &*State->Stack.top(); } // observers /// Gets the current level. Starting path is at level 0. int level() const { return State->Level; } /// Returns true if no_push has been called for this directory_entry. bool no_push_request() const { return State->HasNoPushRequest; } // modifiers /// Goes up one level if Level > 0. void pop() { assert(State && "Cannot pop an end iterator!"); assert(State->Level > 0 && "Cannot pop an iterator with level < 1"); const directory_iterator end_itr; error_code ec; do { if (ec) report_fatal_error("Error incrementing directory iterator."); State->Stack.pop(); --State->Level; } while (!State->Stack.empty() && State->Stack.top().increment(ec) == end_itr); // Check if we are done. If so, create an end iterator. if (State->Stack.empty()) State.reset(); } /// Does not go down into the current directory_entry. void no_push() { State->HasNoPushRequest = true; } bool operator==(const recursive_directory_iterator &RHS) const { return State == RHS.State; } bool operator!=(const recursive_directory_iterator &RHS) const { return !(*this == RHS); } // Other members as required by // C++ Std, 24.1.1 Input iterators [input.iterators] }; /// @} } // end namespace fs } // end namespace sys } // end namespace llvm #endif
[ "91980991+AppleOSSDistributions@users.noreply.github.com" ]
91980991+AppleOSSDistributions@users.noreply.github.com
f40fb82650cef358c1bd279c3a9c26e79462b5a1
f84da9a7da712409ebb0e8caf89b41b68a1ffb7c
/Codeforces/contest_id_659/Bicycle Race.cpp
f56959ca1393f510e3f1b58522781c4b2bc9e43a
[]
no_license
mahbubcseju/Programming-Problem-Solutions
7fe674d68ab340b54be64adfa2e2fb33cc64705c
e9de8553f7d0c2c439f62b67e1bf9d6e07d47400
refs/heads/master
2021-08-03T14:37:54.041903
2021-07-18T16:01:12
2021-07-18T16:01:12
199,957,649
0
0
null
null
null
null
UTF-8
C++
false
false
3,291
cpp
/******************************** *MAHBUBCSEJU * *CSE 22 * *JAHANGIRNAGAR UNIVERSITY * *TIMUS:164273FU * *UVA>>LIGHTOJ>>HUST:mahbubcseju * ********************************/ #include<cfloat> #include<climits> #include<fstream> #include<cstdio> #include<cstdlib> #include<cmath> #include<sstream> #include<iostream> #include<algorithm> #include<map> #include<cstring> #include<string> #include<vector> #include<queue> #include<stack> #include<set> #include<string.h> #define ll long long int #define ull unsigned long long int #define I(a) scanf("%d",&a) #define I2(a,b) scanf("%d%d",&a,&b) #define I3(a,b,c) scanf("%d%d%d",&a,&b,&c) #define L(a) scanf("%lld",&a) #define L2(a,b) scanf("%lld%lld",&a,&b) #define L3(a,b,c) scanf("%lld%lld%lld",&a,&b,&c) #define PI(a) printf("%d\n",a) #define PL(a) printf("%lld\n",a) #define PT(t) printf("Case %d: ",t) #define IT(x) for(typeof (x.begin()) it = x.begin(); it != x.end (); it++) #define ITP(x) for(typeof (x.begin()) it = x.begin(); it != x.end (); it++) { cout << *it << " "; } cout << endl; #define PB push_back #define xx first #define yy second #define SC scanf #define PC printf #define NL printf("\n") #define SET(a) memset(a,0,sizeof a) #define SETR(a) memset(a,-1,sizeof a) #define SZ(a) ((int)a.size()) //#define pi 2.0*acos(0.0) #define R(a) freopen(a, "r", stdin); #define W(a) freopen(a, "w", stdout); #define CB(x) __builtin_popcount(x) #define STN(a) stringtonumber<ll>(a) #define lol printf("BUG\n") #define mk make_pair using namespace std; template <class T> inline T BM(T p, T e, T M) { ll ret = 1; for (; e > 0; e >>= 1) { if (e & 1) ret = (ret * p) % M; p = (p * p) % M; } return (T)ret; } template <class T> inline T gcd(T a, T b) { if (b == 0)return a; return gcd(b, a % b); } template <class T> inline T MDINV(T a, T M) { return BM(a, M - 2, M); } template <class T> inline T PW(T p, T e) { ll ret = 1; for (; e > 0; e >>= 1) { if (e & 1) ret = (ret * p); p = (p * p); } return (T)ret; } template <class T>string NTS ( T Number ) { stringstream ss; ss << Number; return ss.str(); } template <class T>T stringtonumber ( const string &Text ) { istringstream ss(Text); T result; return ss >> result ? result : 0; } template <class T>bool ISLEFT ( T a, T b, T c) { if (((a.xx - b.xx) * (b.yy - c.yy) - (b.xx - c.xx) * (a.yy - b.yy)) < 0.0)return 1; //Uporer dike //A,b,c, x okkher ordera sorted else return 0; } #define mx 100000 #define md 1000000007ll #define maxp 1000004 typedef pair<int, int>P; typedef vector<int >V; ////////define value///// int check(P x,P y) { if(x.yy>y.yy)return 3; else if(x.yy<y.yy)return 1; else if(x.xx>y.xx)return 4; else return 2; } int main() { int n, m; I(n); P a[n+20]; n++; for(int i=1;i<=n;i++)I2(a[i].xx,a[i].yy); a[n+1]=a[1]; a[n+2]=a[2]; int op=1; int ans=0; for(int i=1;i<n;i++) { int x=check(a[i],a[i+1]); int y=check(a[i+1],a[i+2]); // cout<<x<<" "<<y<<endl; if(x==1&&y==4)ans++; if(x==2&&y==1)ans++; if(x==3&&y==2)ans++; if(x==4&&y==3)ans++; } PI(ans); return 0; }
[ "mahbubur.rahman@bjitgroup.com" ]
mahbubur.rahman@bjitgroup.com
4aaac3876112bf4e22c03d42ed992ab8284a6a35
901d05e34881b9c201122ec76837af6a1bd28518
/2012Code/WorkshopRobot.cpp
1696bd9c81215a805393423cf667397a07fdcbe8
[]
no_license
Team2550/cRIO-Code
f433b4144eff60577cd93b14ef0e3cf725a0085a
edd8599548858d409190061e8d24c42e1f6dad62
refs/heads/master
2020-04-08T14:26:15.209403
2014-05-27T16:32:45
2014-05-27T16:32:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,172
cpp
#include "WorkshopRobot.h" WorkshopRobot::WorkshopRobot() { //GetWatchdog().SetExpiration(0.1); GetWatchdog().SetEnabled(true); driveSys = new DriveSystem(); //launcher = new Launcher(); nathansArm = new Pickuper(); ramparm = new Arm(); //light = new Lights(); //myaccell7 = new Accell(); //DriverStationUpdater2 = new DriverstationUpdater(); } WorkshopRobot::~WorkshopRobot() { //delete DriverStationUpdater2; delete driveSys; delete ramparm; //delete launcher; delete nathansArm; //delete light; } void WorkshopRobot::Autonomous(void) { GetWatchdog().SetEnabled(false); ramparm->RunAutoArm(); } void WorkshopRobot::OperatorControl(void) { printf("2250 start\n"); GetWatchdog().SetEnabled(true); printf("Watchdog Enabled!\n"); while (IsOperatorControl()) { GetWatchdog().Feed(); //printf("Feed!\n"); driveSys->RunDrive(); //printf("RunDrive Done\n"); //driveSys->DriveMech(); nathansArm->RunPickuper(); //ramparm->RunArm(); //light->FlashLights(); //launcher->RunLauncher(); //DriverStationUpdater2->RunDriverstationUpdater(); Wait(0.005); // wait for a motor update time } } START_ROBOT_CLASS(WorkshopRobot);
[ "none" ]
none
33eb3892dac2678697d2538ba4b4582b819923de
28d10fd75717247883fc580b5347762e30294d4e
/sw/dragon_buttons.cpp
0235069be9b13e02026521e6ef3a69c090d330ea
[]
no_license
acornacorn/dragon2014
55fb9e353ed40b38ad9d5953bbfca3b389b1c3d9
31a725719eb187a42227260cd5ce1acde8fbb71d
refs/heads/master
2020-05-07T10:17:06.460902
2014-11-01T20:40:13
2014-11-01T20:40:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,021
cpp
#include <dragon_buttons.h> #include <dragon_pins.h> #include <dragon.h> #include <ac_printf.h> #include <Arduino.h> #include <Bounce.h> static const bool DEBUG_KEYS = true; static const bool DEBUG_BUTTONS = true; static const int DEBOUNCE_TIME_MS = 20; static Bounce* g_buttons[BUTTON_CNT]; bool g_buttons_changed[BUTTON_CNT]; bool g_buttons_value[BUTTON_CNT]; bool g_buttons_press[BUTTON_CNT]; AcCounter g_help_cnt; bool g_show_help = false; #define INIT_BUTTON(index) \ do \ { \ static Bounce but##index ( dpin_button##index, DEBOUNCE_TIME_MS ); \ g_buttons[index] = &but##index; \ g_buttons_changed[index] = false; \ g_buttons_value[index] = false; \ g_buttons_press[index] = false; \ pinMode(dpin_button##index, INPUT_PULLUP); \ } while(0) static void initButtons() { INIT_BUTTON(0); INIT_BUTTON(1); INIT_BUTTON(2); INIT_BUTTON(3); INIT_BUTTON(4); INIT_BUTTON(5); INIT_BUTTON(6); INIT_BUTTON(7); g_show_help = false; g_help_cnt.init(10, 2); } static void updateButtons() { bool none = true; for (int i = 0 ; i < BUTTON_CNT ; ++i) { g_buttons_changed[i] = g_buttons[i]->update(); g_buttons_value[i] = !g_buttons[i]->read(); g_buttons_press[i] = g_buttons_changed[i] && g_buttons_value[i]; if (g_buttons_changed[i] || g_buttons_value[i]) { none = false; } if (DEBUG_BUTTONS && g_buttons_changed[i]) { acPrintf("Button %d: %s\n", i, g_buttons_value[i] ? "Pressed" : "Released"); } } // wait for buttons to settle after startup. Ignore presses before that. static AcTimer startup; static int first = 1; if (first) { if (none) { first = 0; acPrintf("Buttons OK\n"); } else if (first == 1) { startup.init(1000); first = 2; } else if (startup.check()) { first = 0; acPrintf("Buttons TIMED OUT\n"); } for (int i = 0 ; i < BUTTON_CNT ; ++i) { g_buttons_changed[i] = false; g_buttons_value[i] = false; } return; } // look left BUT_LOOK_LEFT // look right BUT_LOOK_RIGHT // look all over BUT_LOOK_LEFT + BUT_LOOK_RIGHT // // emption+ BUT_EMO_INC // emotion- BUT_EMO_DEC // // right blink BUT_RIGHT_BLINK // left blink BUT_LEFT_BLINK // toggle autoblink BUT_LEFT_BLINK + BUT_RIGHT_BLINK // // toggle debug mode BUT_DEBUG_TOG static bool both_look = false; static bool both_blink = false; // toggle DEBUG modes if (g_buttons_press[BUT_DEBUG_TOG]) { if (g_dragon.getMode() == Dragon::MODE_BUT_SERVO_LIMITS) g_dragon.setMode(Dragon::MODE_HAPPY); else g_dragon.setMode(Dragon::MODE_BUT_SERVO_LIMITS); } // MODE_BUT_SERVO_LIMITS mode if (g_dragon.getMode() == Dragon::MODE_BUT_SERVO_LIMITS) { both_look = false; both_blink = false; if (g_buttons_press[BUT_LEFT_BLINK]) g_dragon.debugToggleServo(Dragon::MODE_KEY_LEYE); if (g_buttons_press[BUT_RIGHT_BLINK]) g_dragon.debugToggleServo(Dragon::MODE_KEY_REYE); if (g_buttons_press[BUT_LOOK_LEFT]) g_dragon.debugToggleServo(Dragon::MODE_KEY_LOOK); if (g_buttons_press[BUT_LOOK_RIGHT]) g_dragon.debugToggleServo(Dragon::MODE_KEY_LIPS); return; } // DETECT BUTTON PAIRS if (g_buttons_value[BUT_LOOK_LEFT] && g_buttons_value[BUT_LOOK_RIGHT]) { both_look = true; } if (g_buttons_value[BUT_RIGHT_BLINK] && g_buttons_value[BUT_LEFT_BLINK]) { // TOGGLE AUTO BLINK if (!both_blink) { g_dragon.enableBlink(!g_dragon.getEnableBlink()); } both_blink = true; } if (g_buttons_press[BUT_EMO_INC]) { g_dragon.incEmotion(1); } if (g_buttons_press[BUT_EMO_DEC]) { g_dragon.incEmotion(-1); } // NOTE: Blinking is handled in Dragon::updateBlink() // LOOK LEFT if (g_buttons_changed[BUT_LOOK_LEFT]) { if (both_look) { g_dragon.look(sv_look_mid, true); // TODO: enable auto looking around mode } else if (g_buttons_value[BUT_LOOK_LEFT]) { g_dragon.look(sv_look_left, false); } else { g_dragon.look(sv_look_mid, true); } } // LOOK RIGHT if (g_buttons_changed[BUT_LOOK_RIGHT]) { if (both_look) { g_dragon.look(sv_look_mid, true); // TODO: enable auto looking around mode } else if (g_buttons_value[BUT_LOOK_RIGHT]) { g_dragon.look(sv_look_right, false); } else { g_dragon.look(sv_look_mid, true); } } // DETECT BUTTON PAIRS if (!g_buttons_value[BUT_LOOK_LEFT] && !g_buttons_value[BUT_LOOK_RIGHT]) { both_look = false; } if (!g_buttons_value[BUT_RIGHT_BLINK] && !g_buttons_value[BUT_LEFT_BLINK]) { both_blink = false; } } static const char *help[] = { "", " __HELP__", " l - leye servo", " r - reye servo", " o - look servo", " i - lips servo", " R - red", " G - green", " B - blue", " , - decrement", " . - increment", " - - prev mode", " = - next mode", " p - happy", " a - angry", 0, }; static void startHelp() { g_show_help = true; g_help_cnt.init(11, 1000); } static void updateHelp() { if (g_show_help) { uint32_t val; if (g_help_cnt.check(&val)) { if (help[val] == 0) { g_show_help = false; } else { acPrintf("%s\n", help[val]); } } } } static void parseKey(int c) { int inc = 0; switch(c) { case 'H': case 'h': case '/': case '?': startHelp(); break; case 'l': g_dragon.setMode(Dragon::MODE_KEY_LEYE); break; case 'r': g_dragon.setMode(Dragon::MODE_KEY_REYE); break; case 'o': g_dragon.setMode(Dragon::MODE_KEY_LOOK); break; case 'i': g_dragon.setMode(Dragon::MODE_KEY_LIPS); break; case 'R': g_dragon.setMode(Dragon::MODE_KEY_R); break; case 'G': g_dragon.setMode(Dragon::MODE_KEY_G); break; case 'B': g_dragon.setMode(Dragon::MODE_KEY_B); break; case 'a': g_dragon.setMode(Dragon::MODE_ANGRY1); break; case 'p': g_dragon.setMode(Dragon::MODE_HAPPY); break; case '-': case '_': g_dragon.setMode((Dragon::Mode)(g_dragon.getMode() - 1)); break; case '+': case '=': g_dragon.setMode((Dragon::Mode)(g_dragon.getMode() + 1)); break; case ',': case '<': inc = -1; break; case '.': case '>': inc = +1; break; default: acPrintf("Unknown key: 0x%02x = '%c'\n", c, c >= ' ' && c < 0x7f ? c : '?'); break; } if (inc) g_dragon.debugIncrement(inc); } static void checkKey() { int c = Serial.peek(); if (c != -1) { c = Serial.read(); if (DEBUG_KEYS) acPrintf("Got key: %02x = %c\n", c, c >= ' ' && c < 0x7f ? c : '?'); parseKey(c); } } void dragonButtonInit() { initButtons(); } void dragonButtonUpdate() { checkKey(); updateButtons(); updateHelp(); }
[ "acorn@mad.scientist.com" ]
acorn@mad.scientist.com
86ea12f1138d983b6e80abf350e984207b50f785
925e5f757754dfe9512a9da5a6675930a4b300e9
/sdkcreationmw/sdkexamples/cppexamples/S60Ex/SIPExample/gameUI_series60/Src/SIPExApp.cpp
60984cabf7371bc90f8466deef980cc75644a30a
[]
no_license
fedor4ever/packaging
d86342573ee2d738531904150748bbeee6c44f5d
cf25a1b5292e6c94c9bb6434f0f6ab1138c8329b
refs/heads/master
2021-01-15T18:09:15.875194
2015-04-12T12:03:13
2015-04-12T12:03:13
33,689,077
0
1
null
null
null
null
UTF-8
C++
false
false
2,891
cpp
/* * Copyright (c) 2004-2006 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: * */ // INCLUDE FILES #include "SIPExApp.h" #include "SIPExDoc.h" #ifdef EKA2 #include <eikstart.h> #endif // ============================ MEMBER FUNCTIONS =============================== // ----------------------------------------------------------------------------- // CSIPExApp::CreateDocumentL // Creates a document and returns a pointer to it // ----------------------------------------------------------------------------- // CApaDocument* CSIPExApp::CreateDocumentL() { CApaDocument* document = CSIPExDoc::NewL( *this ); return document; } // ----------------------------------------------------------------------------- // CSIPExApp::AppDllUid // Returns the UID for the SIPEx application // ----------------------------------------------------------------------------- // TUid CSIPExApp::AppDllUid() const { // Return the UID for the SIP Example game application return KUidSIPExApp; } // ========================== OTHER EXPORTED FUNCTIONS ========================= // ----------------------------------------------------------------------------- // NewApplication() implements the creation of the application class // Creates an application, and return a pointer to it // Returns: CApaApplication*: Pointer to the application class instance // ----------------------------------------------------------------------------- // EXPORT_C CApaApplication* NewApplication() { CApaApplication* app = new CSIPExApp; return app; } #ifdef EKA2 // ----------------------------------------------------------------------------- // E32Main() is the entry point to the application DLL in application // framework V2 // Returns: TInt: Error if starting the app trough framework wasn't succesful // ----------------------------------------------------------------------------- // GLDEF_C TInt E32Main() { return EikStart::RunApplication( NewApplication ); } #else // ----------------------------------------------------------------------------- // E32Dll() is the entry point to the application DLL // DLL entry point in EKA1 // Returns: TInt: Always KErrNone // ----------------------------------------------------------------------------- // GLDEF_C TInt E32Dll( TDllReason /*aReason*/ ) { return KErrNone; } #endif // EKA2 // End of file
[ "devnull@localhost" ]
devnull@localhost
207a3ce18876a07613e6d6cdc1436d8ac9b458ff
3b9b4049a8e7d38b49e07bb752780b2f1d792851
/src/chrome/browser/task_management/providers/child_process_task_unittest.cc
4ffbd555b8e6eecb0ae2bdb60e1dad78b8f42233
[ "BSD-3-Clause", "Apache-2.0" ]
permissive
webosce/chromium53
f8e745e91363586aee9620c609aacf15b3261540
9171447efcf0bb393d41d1dc877c7c13c46d8e38
refs/heads/webosce
2020-03-26T23:08:14.416858
2018-08-23T08:35:17
2018-09-20T14:25:18
145,513,343
0
2
Apache-2.0
2019-08-21T22:44:55
2018-08-21T05:52:31
null
UTF-8
C++
false
false
6,576
cc
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <stdint.h> #include "base/macros.h" #include "base/run_loop.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/task_management/providers/child_process_task.h" #include "chrome/browser/task_management/providers/child_process_task_provider.h" #include "chrome/browser/task_management/task_manager_observer.h" #include "chrome/grit/generated_resources.h" #include "components/nacl/common/nacl_process_type.h" #include "content/public/browser/child_process_data.h" #include "content/public/common/process_type.h" #include "content/public/test/test_browser_thread_bundle.h" #include "content/public/test/test_utils.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/base/l10n/l10n_util.h" using content::ChildProcessData; namespace task_management { namespace { // Will be used to test the translation from |content::ProcessType| to // |task_management::Task::Type|. struct ProcessTypeTaskTypePair { int process_type_; Task::Type expected_task_type_; } process_task_types_pairs[] = { { content::PROCESS_TYPE_PLUGIN, Task::PLUGIN }, { content::PROCESS_TYPE_PPAPI_PLUGIN, Task::PLUGIN }, { content::PROCESS_TYPE_PPAPI_BROKER, Task::PLUGIN }, { content::PROCESS_TYPE_UTILITY, Task::UTILITY }, { content::PROCESS_TYPE_ZYGOTE, Task::ZYGOTE }, { content::PROCESS_TYPE_SANDBOX_HELPER, Task::SANDBOX_HELPER }, { content::PROCESS_TYPE_GPU, Task::GPU }, { PROCESS_TYPE_NACL_LOADER, Task::NACL }, { PROCESS_TYPE_NACL_BROKER, Task::NACL }, }; } // namespace // Defines a test for the child process task provider and the child process // tasks themselves. class ChildProcessTaskTest : public testing::Test, public TaskProviderObserver { public: ChildProcessTaskTest() {} ~ChildProcessTaskTest() override {} // task_management::TaskProviderObserver: void TaskAdded(Task* task) override { DCHECK(task); if (provided_tasks_.find(task->process_handle()) != provided_tasks_.end()) FAIL() << "ChildProcessTaskProvider must never provide duplicate tasks"; provided_tasks_[task->process_handle()] = task; } void TaskRemoved(Task* task) override { DCHECK(task); provided_tasks_.erase(task->process_handle()); } bool AreProviderContainersEmpty( const ChildProcessTaskProvider& provider) const { return provider.tasks_by_handle_.empty() && provider.tasks_by_pid_.empty(); } protected: std::map<base::ProcessHandle, Task*> provided_tasks_; private: content::TestBrowserThreadBundle thread_bundle_; DISALLOW_COPY_AND_ASSIGN(ChildProcessTaskTest); }; // Perfoms a basic test. TEST_F(ChildProcessTaskTest, BasicTest) { ChildProcessTaskProvider provider; EXPECT_TRUE(provided_tasks_.empty()); provider.SetObserver(this); content::RunAllPendingInMessageLoop(); ASSERT_TRUE(provided_tasks_.empty()) << "unit tests don't have any browser child processes"; provider.ClearObserver(); EXPECT_TRUE(provided_tasks_.empty()); EXPECT_TRUE(AreProviderContainersEmpty(provider)); } // Tests everything related to child process task providing. TEST_F(ChildProcessTaskTest, TestAll) { ChildProcessTaskProvider provider; EXPECT_TRUE(provided_tasks_.empty()); provider.SetObserver(this); content::RunAllPendingInMessageLoop(); ASSERT_TRUE(provided_tasks_.empty()); // The following process which has handle = base::kNullProcessHandle, won't be // added. ChildProcessData data1(0); ASSERT_EQ(base::kNullProcessHandle, data1.handle); provider.BrowserChildProcessLaunchedAndConnected(data1); EXPECT_TRUE(provided_tasks_.empty()); const int unique_id = 245; const base::string16 name(base::UTF8ToUTF16("Test Task")); const base::string16 expected_name(l10n_util::GetStringFUTF16( IDS_TASK_MANAGER_PLUGIN_PREFIX, name)); ChildProcessData data2(content::PROCESS_TYPE_PLUGIN); data2.handle = base::GetCurrentProcessHandle(); data2.name = name; data2.id = unique_id; provider.BrowserChildProcessLaunchedAndConnected(data2); ASSERT_EQ(1U, provided_tasks_.size()); Task* task = provided_tasks_.begin()->second; EXPECT_EQ(base::GetCurrentProcessHandle(), task->process_handle()); EXPECT_EQ(base::GetCurrentProcId(), task->process_id()); EXPECT_EQ(expected_name, task->title()); EXPECT_EQ(Task::PLUGIN, task->GetType()); EXPECT_EQ(unique_id, task->GetChildProcessUniqueID()); EXPECT_EQ(base::string16(), task->GetProfileName()); EXPECT_FALSE(task->ReportsSqliteMemory()); EXPECT_FALSE(task->ReportsV8Memory()); EXPECT_FALSE(task->ReportsWebCacheStats()); EXPECT_FALSE(task->ReportsNetworkUsage()); // Make sure that the conversion from PID to Handle inside // |GetTaskOfUrlRequest()| is working properly. Task* found_task = provider.GetTaskOfUrlRequest(base::GetCurrentProcId(), 0, 0); ASSERT_EQ(task, found_task); const int64_t bytes_read = 1024; found_task->OnNetworkBytesRead(bytes_read); found_task->Refresh(base::TimeDelta::FromSeconds(1), REFRESH_TYPE_NETWORK_USAGE); EXPECT_TRUE(task->ReportsNetworkUsage()); EXPECT_EQ(bytes_read, task->network_usage()); // Clearing the observer won't notify us of any tasks removals even though // tasks will be actually deleted. provider.ClearObserver(); EXPECT_FALSE(provided_tasks_.empty()); EXPECT_TRUE(AreProviderContainersEmpty(provider)); } // Tests the translation of |content::ProcessType| to // |task_management::Task::Type|. TEST_F(ChildProcessTaskTest, ProcessTypeToTaskType) { ChildProcessTaskProvider provider; EXPECT_TRUE(provided_tasks_.empty()); provider.SetObserver(this); content::RunAllPendingInMessageLoop(); ASSERT_TRUE(provided_tasks_.empty()); for (const auto& types_pair : process_task_types_pairs) { // Add the task. ChildProcessData data(types_pair.process_type_); data.handle = base::GetCurrentProcessHandle(); provider.BrowserChildProcessLaunchedAndConnected(data); ASSERT_EQ(1U, provided_tasks_.size()); Task* task = provided_tasks_.begin()->second; EXPECT_EQ(base::GetCurrentProcessHandle(), task->process_handle()); EXPECT_EQ(types_pair.expected_task_type_, task->GetType()); // Remove the task. provider.BrowserChildProcessHostDisconnected(data); EXPECT_TRUE(provided_tasks_.empty()); } provider.ClearObserver(); EXPECT_TRUE(AreProviderContainersEmpty(provider)); } } // namespace task_management
[ "changhyeok.bae@lge.com" ]
changhyeok.bae@lge.com
ddb1bab2e0b4785c259e4eb5bba40956f0f1401d
c2b8747ab182b7ebb2b971d87cfa0a13177f7900
/MeanShiftSegm/edge/BgEdgeList.cpp
6350a3927b4f016cce941a242d2d30ce7745f1ed
[]
no_license
wilmer05/cv-l3
cf3a8494aa52f538594f6022f7a903d0573857da
d56d5e2add42be54b07905c406637d38c8383a61
refs/heads/master
2021-01-21T09:52:46.106578
2017-05-21T13:36:38
2017-05-21T13:36:38
91,670,199
0
0
null
null
null
null
UTF-8
C++
false
false
4,786
cpp
///////////////////////////////////////////////////////////////////////////// // Name: BgEdgeList.cpp // Purpose: BgEdgeList class functions // Author: Bogdan Georgescu // Modified by: // Created: 06/22/2000 // Copyright: (c) Bogdan Georgescu // Version: v0.1 ///////////////////////////////////////////////////////////////////////////// #include <stdio.h> #include <stdlib.h> #include <math.h> #include "BgDefaults.h" #include "BgImage.h" #include "BgEdge.h" #include "BgEdgeList.h" BgEdgeList::BgEdgeList() { nEdges_ = 0; edgelist_ = 0; crtedge_ = 0; } BgEdgeList::~BgEdgeList() { if (nEdges_>0) { BgEdge* edge; for (int i=0; i<nEdges_; i++) { edge = edgelist_->next_; delete edgelist_; edgelist_=edge; } } } void BgEdgeList::AddEdge(float* edge, int nPoints) { BgEdge* tedge; tedge = new BgEdge(); tedge->SetPoints(edge, nPoints); if (nEdges_==0) { nEdges_ = 1; edgelist_ = tedge; crtedge_ = tedge; } else { nEdges_++; crtedge_->next_ = tedge; crtedge_ = tedge; } } void BgEdgeList::AddEdge(int* edge, int nPoints) { BgEdge* tedge; tedge = new BgEdge(); tedge->SetPoints(edge, nPoints); if (nEdges_==0) { nEdges_ = 1; edgelist_ = tedge; crtedge_ = tedge; } else { nEdges_++; crtedge_->next_ = tedge; crtedge_ = tedge; } } void BgEdgeList::SetGradient(float* grx, float* gry, float* mark, int ncol) { BgEdge* it; int i; it=edgelist_; for (i=0; i<nEdges_; i++) { it->SetGradient(grx, gry, mark, ncol); it = it->next_; } } void BgEdgeList::RemoveShortEdges(int minp) { if (nEdges_==0) return; int nEdges=nEdges_; BgEdge* it1; BgEdge* it2; it1 = edgelist_; it2 = it1->next_; for (int i=1; i<nEdges_; i++) { if (it2->nPoints_ < minp) { it1->next_ = it2->next_; delete it2; it2 = it1->next_; nEdges--; } else { it1 = it2; it2 = it1->next_; } } if (edgelist_->nPoints_ < minp) { it1 = edgelist_; edgelist_ = edgelist_->next_; delete it1; nEdges--; } nEdges_=nEdges; } void BgEdgeList::SetBinImage(BgImage* image) { int i, j; int ix, iy; int x, y; x = image->x_; y = image->y_; unsigned char* im=image->im_; for (i=0; i<x; i++) { for (j=0;j<y;j++) { *(im++) = 0; } } im = image->im_; int* ite; crtedge_=edgelist_; for (i=0; i<nEdges_; i++) { ite = crtedge_->edge_; for (j=0; j<crtedge_->nPoints_; j++) { ix = *(ite++); iy = *(ite++); *(im+iy*x+ix) = 255; } crtedge_=crtedge_->next_; } } bool BgEdgeList::SaveEdgeList(char* edgeFile) { int length; int i,j; BgEdge *crtedge; FILE* fp; fp=fopen(edgeFile,"wb"); crtedge = edgelist_; for (i=0; i<nEdges_; i++) { length = crtedge->nPoints_; for (j=0; j<length; j++) { fprintf(fp, "%d %d %d\n", *((crtedge->edge_)+2*j), *((crtedge->edge_)+2*j+1), i); } crtedge = crtedge->next_; } fclose(fp); return true; } void BgEdgeList::GetAllEdgePoints(int* x, int* y, int* n) { int length; int i,j; BgEdge *crtedge; int *edgep; crtedge = edgelist_; *n = 0; for (i=0; i<nEdges_; i++) { length = crtedge->nPoints_; edgep = crtedge->edge_; for (j=0; j<length; j++) { x[*n] = edgep[2*j]; y[*n] = edgep[2*j+1]; (*n)++; } crtedge = crtedge->next_; } } void BgEdgeList::SetNoMark(void) { int length; int i,j; BgEdge* crtedge; unsigned char* mark; crtedge = edgelist_; for (i=0; i<nEdges_; i++) { length = crtedge->nPoints_; mark = crtedge->mark_ = new unsigned char[length]; crtedge->isMarkSet_ = true; for (j=0; j<length; j++) { *(mark+j) = 0; } crtedge = crtedge->next_; } }
[ "wbandres@mahisoft.com" ]
wbandres@mahisoft.com
931b8081a98172844f12f7525dc3fababe741d29
2aa9880c5ed5084112932a7bf03addbaeca84a32
/cxx_utilities/include/cxx_math/cxx_aabb.h
0d649d97cba5a00fceb97e72a8f8823fa2d5ce0d
[]
no_license
goteet/a-piece-of-shit
6da49e4f975495c7f049b0a9414d03b5259a7f03
2cae116ddba6b77a869966b7f005aae15f496b84
refs/heads/master
2022-10-03T20:34:31.450373
2020-05-26T07:13:07
2020-05-26T08:30:01
259,877,411
3
0
null
null
null
null
UTF-8
C++
false
false
10,453
h
#pragma once #include "cxx_mathcommon.h" #include "cxx_vector.h" #include "cxx_point.h" #include "cxx_matrix.h" namespace cxx { template<typename E, dimension Dimension> struct aabb_t; template<typename E> using aabb2d = aabb_t<E, dimension::_2>; template<typename E> using aabb3d = aabb_t<E, dimension::_3>; using aabb2d_i = aabb2d<int>; using aabb3d_i = aabb3d<int>; using aabb2d_f = aabb2d<float>; using aabb3d_f = aabb3d<float>; using aabb2d_d = aabb2d<double>; using aabb3d_d = aabb3d<double>; using rect = aabb2d_i; using cube = aabb3d_i; template<typename E, dimension D> struct aabb_t { using vector = vector_t<E, D>; using point = point_t<E, D>; constexpr aabb_t() = default; constexpr aabb_t(const point_t<E, D>& _min, const point_t<E, D>& _max); //properties constexpr const point& min_value() const { return m_min_value; } constexpr const point& max_value() const { return m_max_value; } constexpr const point center() const { return (m_min_value + m_max_value) / constants<E>::two; } constexpr const vector extend() const { return (m_max_value - m_min_value) / constants<E>::two; } constexpr bool is_valid() const { return valid; } inline bool is_empty() const { if (is_valid()) { for (size_t i = 0, n = D; i < n; i++) { if (is_equal(m_min_value[i], m_max_value[i])) { return true; } } } return false; } //functions constexpr void set(const point& _min, const point& _max) { m_min_value = min_v(_min, _max); m_max_value = max_v(_min, _max); valid = true; } constexpr void expand(const vector& point) { if (is_valid()) { m_min_value = min_v(m_min_value, point); m_max_value = max_v(m_max_value, point); } else { m_min_value = point; m_max_value = point; valid = true; } } constexpr void expand(const aabb_t& other) { if (other.is_valid()) { if (is_valid()) { m_min_value = min_v(m_min_value, other.m_min_value); m_max_value = max_v(m_max_value, other.m_max_value); } else { *this = other; } } } constexpr void move_to(const point& newCenter) { if (is_valid()) { vector offset = newCenter - center(); m_min_value += offset; m_max_value += offset; } else { m_min_value = newCenter; m_max_value = newCenter; valid = true; } } constexpr void set_extend(const vector& e) { if (is_valid()) { vector c = center(); m_min_value = c - e; m_max_value = c + e; } else { m_min_value = -e; m_max_value = e; valid = true; } } constexpr void clear() { m_min_value = m_max_value = point::zero(); valid = false; } inline bool contains(const aabb_t& other) const { if (!is_valid() || !other.is_valid()) { return false; } else { if (is_empty()) { return other.is_empty(); } else { for (int i = 0; i < D; i++) { if (m_min_value[i] > other.m_min_value[i] || m_max_value[i] < other.m_max_value[i]) { return false; } } return true; } } } inline bool contains(const point& point) const { if (is_valid()) { for (int i = 0; i < D; i++) { if (m_min_value[i] > point[i] || m_max_value[i] < point[i]) { return false; } } return true; } else { return false; } } intersection hit_test(const aabb_t& other) const { if (*this == other) { return intersection::same; } if (is_valid() && other.is_valid()) { int minless = 0; int maxless = 0; for (int i = 0; i < D; i++) { if (m_min_value[i] < other.m_min_value[i]) minless++; if (m_max_value[i] < other.m_max_value[i]) maxless++; if (m_min_value[i] > other.m_max_value[i] || m_max_value[i] < other.m_min_value[i]) { return intersection::none; } } if (minless == D && maxless == 0) { return intersection::contain; } else if (minless == 0 && maxless == D) { return intersection::inside; } else { return intersection::hit; } } else { return intersection::none; } } //move to = set center. template<dimension T = D> constexpr std::enable_if_t<dimension::_2 == T> move_to(scaler_t<E> x, scaler_t<E> y) { move_to(vector(x, y)); } template<dimension T = D> constexpr std::enable_if_t<dimension::_3 == T> move_to(scaler_t<E> x, scaler_t<E> y, scaler_t<E> z) { move_to(vector(x, y, z)); } template<dimension T = D> constexpr std::enable_if_t<dimension::_2 == T> expand_to(scaler_t<E> x, scaler_t<E> y) { set_extend(vector(x, y)); } template<dimension T = D> constexpr std::enable_if_t<dimension::_3 == T> expand_to(scaler_t<E> x, scaler_t<E> y, scaler_t<E> z) { set_extend(vector(x, y, z)); } private: bool valid = false; point m_min_value; point m_max_value; private: template<typename T, dimension DD> friend constexpr aabb_t<T, DD> operator*(const aabb_t<T, DD>& bounding, scaler_t<T> scaler); template<typename T, dimension DD> friend constexpr bool enlarge(aabb_t<T, DD>& bounding, const vector_t<T, DD>& scaler); template<typename T, dimension DD> friend constexpr bool move(aabb_t<T, DD>& bounding, const vector_t<T, DD>& offset); template<typename T, dimension DD> friend inline bool is_intersect(const aabb_t<T, DD>& lhs, const aabb_t<T, DD>& rhs); }; //functions template<typename E, dimension D> constexpr bool operator==(const aabb_t<E, D>& lhs, const aabb_t<E, D>& rhs) { return (&lhs == &rhs) || (!lhs.is_valid() && !rhs.is_valid()) || (lhs.is_valid() && rhs.is_valid() && lhs.min_value() == rhs.min_value() && lhs.max_value() == rhs.max_value()); } template<typename E, dimension D> constexpr bool operator!=(const aabb_t<E, D>& lhs, const aabb_t<E, D>& rhs) { return !(lhs == rhs); } template<typename E, dimension D> constexpr bool move(aabb_t<E, D>& bounding, const vector_t<E, D>& offset) { if (bounding.is_valid()) { bounding.m_min_value += offset; bounding.m_max_value += offset; return true; } else { return false; } } template<typename E, dimension D> constexpr aabb_t<E, D> operator*(const aabb_t<E, D>& bounding, scaler_t<E> scaler) { if (bounding.is_valid()) { aabb_t<E, D> newBound; vector_t<E, D> e = bounding.extend() * scaler; vector_t<E, D> c = bounding.center(); newBound.m_min_value = c - e; newBound.m_max_value = c + e; return newBound; } else { return bounding; } } template<typename E, dimension D> constexpr aabb_t<E, D> operator*(scaler_t<E> scaler, const aabb_t<E, D>& bounding) { return bounding * scaler; } template<typename E, dimension D> constexpr aabb_t<E, D>& operator*=(aabb_t<E, D>& bounding, scaler_t<E> scaler) { if (bounding.is_valid()) { vector_t<E, D> e = bounding.extend() * scaler; vector_t<E, D> c = bounding.center(); bounding.m_min_value = c - e; bounding.m_max_value = c + e; } return bounding; } template<typename E, dimension D> constexpr bool enlarge(aabb_t<E, D>& bounding, const vector_t<E, D>& scaler) { if (bounding.is_valid()) { vector_t<E, D> e = bounding.extend() + scaler; vector_t<E, D> c = bounding.center(); bounding.m_min_value = c - e; bounding.m_max_value = c + e; return true; } else { return false; } } template<typename E, dimension D> constexpr bool enlarge(aabb_t<E, D>& bounding, scaler_t<E> scaler) { return enlarge(bounding, vector(scaler)); } template<typename E, dimension D> inline bool is_intersect(const aabb_t<E, D>& lhs, const aabb_t<E, D>& rhs) { if (&lhs == &rhs) { return false; } if (lhs.is_valid() && rhs.is_valid()) { for (size_t i = 0; i < D; i++) { if (lhs.m_min_value[i] > rhs.m_max_value[i] || lhs.m_max_value[i] < rhs.m_min_value[i]) { return false; } } return true; } else { return false; } } template<typename E, dimension D> inline bool is_single_point(const aabb_t<E, D>& bounding) { return bounding.is_valid() && bounding.min_value() == bounding.max_value(); } // implements template<typename E, dimension D> constexpr aabb_t<E, D>::aabb_t(const point_t<E, D>& _min, const point_t<E, D>& _max) : valid(true) , m_min_value(min_v(_min, _max)) , m_max_value(max_v(_min, _max)) { } // 2d ui staff operations template<typename E> constexpr bool move(aabb_t<E, dimension::_2>& bounding, scaler_t<E> x, scaler_t<E> y) { return move(bounding, vector_t<E, dimension::_2>(x, y)); } template<typename E> constexpr bool move(aabb_t<E, dimension::_3>& bounding, scaler_t<E> x, scaler_t<E> y, scaler_t<E> z) { return move(bounding, vector_t<E, dimension::_3>(x, y, z)); } template<typename E> constexpr bool enlarge(aabb_t<E, dimension::_2>& bounding, scaler_t<E> x, scaler_t<E> y) { return enlarge(bounding, vector_t<E, dimension::_2>(x, y)); } template<typename E> constexpr bool enlarge(aabb_t<E, dimension::_3>& bounding, scaler_t<E> x, scaler_t<E> y, scaler_t<E> z) { return enlarge(bounding, vector_t<E, dimension::_3>(x, y, z)); } // Transforms template<typename E> constexpr aabb2d<E> transform(const matrix_t<E, dimension::_2, dimension::_3>& matrix, const aabb2d<E>& box) { return aabb2d<E>( transform(matrix, box.min_value()), transform(matrix, box.max_value()) ); } template<typename E> constexpr aabb2d<E> transform(const matrix_t<E, dimension::_3, dimension::_3>& matrix, const aabb2d<E>& box) { return aabb2d<E>( transform(matrix, box.min_value()), transform(matrix, box.max_value()) ); } template<typename E> constexpr aabb3d<E> transform(const matrix_t<E, dimension::_4, dimension::_4>& matrix, const aabb3d<E>& box) { return aabb3d<E>( transform(matrix, box.min_value()), transform(matrix, box.max_value()) ); } }
[ "goteet@126.com" ]
goteet@126.com
8f08ff0068089106bccbc4bbc305f1eb1365cf1e
03e1a82d1e83dd76aa10d926abf819640653411b
/网络流/劈配/bzoj5251.cpp
c53e9d16df2a6fd107886befeee82e2798d691ea
[]
no_license
gbakkk5951/OI
879d95c0b96df543d03d01b864bd47af2ba9c0c8
a3fe8894e604e9aac08c2db6e36c1b77f3882c43
refs/heads/master
2018-09-20T10:09:23.170608
2018-07-09T11:52:21
2018-07-09T11:52:21
115,510,457
2
0
null
null
null
null
GB18030
C++
false
false
3,610
cpp
#pragma optimize(2) using namespace std; int main() {} #include <cstdio> #include <cctype> #include <cstring> #include <cstdlib> #include <algorithm> namespace OI { const int DST = 0, NXT = 1, FLOW = 2; const int FMXN = 418, MXM = 5005, MXN = 205; int lstvis[FMXN]; int dst; int size; struct Flow { int head[FMXN]; int vis[FMXN]; int edge[MXM][3]; int eidx; void init() { eidx = 1; memset(head, 0, size * sizeof(int)); memset(lstvis, 0, size * sizeof(int)); } void dir_add(int a, int b, int c) { eidx++; edge[eidx][DST] = b; edge[eidx][FLOW] = c; edge[eidx][NXT] = head[a]; head[a] = eidx; } void add(int a, int b, int c) { dir_add(a, b, c); dir_add(b, a, 0); } void run(int nd) { memset(vis, 0, size * sizeof(int)); dfs(nd); } int dfs(int nd) { if (nd == dst) return 1; vis[nd] = 1; for (int e = head[nd]; e; e = edge[e][NXT]) { if (edge[e][FLOW]) { int t = edge[e][DST]; if (!vis[t] && dfs(t)) { --edge[e][FLOW]; ++edge[e ^ 1][FLOW]; return 1; } } } return 0; } void getvis(int nd, int id) { lstvis[nd] = id; for (int e = head[nd]; e; e = edge[e][NXT]) { if (edge[e ^ 1][FLOW]) { int t = edge[e][DST]; if (lstvis[t] < id) { getvis(t, id); } } } } }flow; struct _Main { int n, m; int arr[MXN];//rk为i学生的编号 int zy[MXN][MXN][11]; int need[MXN];//档次需求 int mne[MXN];//名额 int mid[MXN], nid[MXN]; int ans1[MXN], ans2[MXN]; int idx; int node() { return idx++; } _Main() { int a; int Tn, C; read(Tn); read(C); for (int T = 1; T <= Tn; T++) { for (int i = 1; i <= n; i++) { memset(zy[i], 0, (m + 1) * 11 * sizeof(int)); } idx = 0; read(n); read(m); for (int i = 1; i <= m; i++) { read(mne[i]); } for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { read(a); if (a != 0) { zy[i][a][++zy[i][a][0]] = j; } } } for (int i = 1; i <= n; i++) { read(need[i]); } dst = node(); for (int i = 1; i <= n; i++) { nid[i] = node(); } for (int i = 1; i <= m; i++) { mid[i] = node(); } size = idx; flow.init(); for (int i = 1; i <= m; i++) { flow.add(mid[i], dst, mne[i]); } for (int I = 1; I <= n; I++) { flow.getvis(dst, I); int nd = I, mx = 0; int a1 = 0, cnt = 0; for (int i = 1; i <= m; i++) { for (int j = 1; j <= zy[nd][i][0]; j++) { cnt++; if (lstvis[mid[zy[nd][i][j]]] == I) { a1 = ans1[nd] = i; goto JMP; } } } JMP: if (a1) { if (a1 <= need[nd]) { ans2[nd] = 0; } else { for (int i = 1; i <= need[nd]; i++) { for (int j = 1; j <= zy[nd][i][0]; j++) { mx = max(mx, lstvis[mid[zy[nd][i][j]]]); } } ans2[nd] = I - mx; } for (int j = 1; j <= zy[nd][a1][0]; j++) { int t = mid[zy[nd][a1][j]]; if (lstvis[t] == I) flow.add(nid[nd], t, 1);//小剪枝 } flow.run(nid[nd]); } else { if (cnt != 0) for (int i = 1; i <= need[nd]; i++) { for (int j = 1; j <= zy[nd][i][0]; j++) { mx = max(mx, lstvis[mid[zy[nd][i][j]]]); } } ans2[nd] = I - mx; ans1[nd] = m + 1; } } for (int i = 1; i <= n; i++) { printf("%d ", ans1[i]); } printf("\n"); for (int i = 1; i <= n; i++) { printf("%d ", ans2[i]); } printf("\n"); } } template <typename Type> void read(Type &a) { char t; while (!isdigit(t = getchar())); a = t - '0'; while ( isdigit(t = getchar())) { a *= 10; a += t - '0'; } } }bzoj5251; }
[ "526406038@qq.com" ]
526406038@qq.com
6245a954180030d6702e3776cff9b312c28dae1f
7ada3d5c958cfdaeefa3d67d0815bb027006f65f
/Engine/Engine/src/Render/Platform/RenderPass/RenderPassParticle.cpp
5e76e06bdcf3295bb5a6b42d7a90def942751839
[]
no_license
JSpink95/cypher
55778e2db3a842b502027a8d429393837eed0bfb
d6567e685a03a033b3ab447a84ea1b999a76b3ad
refs/heads/master
2020-11-27T11:55:41.064332
2020-02-20T17:17:37
2020-02-20T17:17:37
229,427,654
0
0
null
null
null
null
UTF-8
C++
false
false
3,748
cpp
////////////////////////////////////////////////////////////////////////// // File : RenderPassParticle.cpp // Created By : Jack Spink // Created On : [27/01/2020] ////////////////////////////////////////////////////////////////////////// #include "Render/Platform/RenderPass/RenderPassParticle.h" ////////////////////////////////////////////////////////////////////////// #include "Core/Object.h" ////////////////////////////////////////////////////////////////////////// #include "Render/Platform/Renderer.h" #include "Render/Platform/ApiManager.h" #include "Render/Platform/Framebuffer.h" ////////////////////////////////////////////////////////////////////////// #include "Render/Platform/RenderPass/RenderPassUnlit.h" ////////////////////////////////////////////////////////////////////////// #ifdef _OPENGL #include "glfw.h" #endif ////////////////////////////////////////////////////////////////////////// RenderPassParticle::RenderPassParticle() { } ////////////////////////////////////////////////////////////////////////// Ref<FramebufferAttachment> RenderPassParticle::GetAttachment(GBuffer::Color attachment) { return framebuffer->GetColorBuffer(attachment); } ////////////////////////////////////////////////////////////////////////// void RenderPassParticle::OnRenderCreate() { Super::OnRenderCreate(); FramebufferData fb; fb.resolution = RenderPassManager::GetFramebufferSize(); fb.colorBuffers.at(GBuffer::CB_Albedo) = { true, true }; fb.colorBuffers.at(GBuffer::CB_DepthStencil) = { true, true }; framebuffer = GetApiManager()->CreateFramebuffer(fb); } ////////////////////////////////////////////////////////////////////////// void RenderPassParticle::OnBegin() { Super::OnBegin(); Renderer::BeginScene(framebuffer); // #todo - add abstracted render commands for this kind of stuff GlCall(glClearColor(0.0f, 0.0f, 0.0f, 0.0f)); GlCall(glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)); GlCall(glEnable(GL_BLEND)); GlCall(glDepthMask(GL_FALSE)); GlCall(glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)); if (Ref<RenderPassBase> unlitPass = RenderPassManager::GetPass(RenderPassUnlit::Id)) { // copy across the depth from the unlit pass. // this way, particles have access to the same depth buffer that all previously rendered objects have written to (lit + unlit). Ref<FramebufferAttachment> depthAttachment = unlitPass->GetAttachment(GBuffer::CB_DepthStencil); framebuffer->GetColorBuffer(GBuffer::CB_DepthStencil)->CopyAttachmentData(depthAttachment); } } ////////////////////////////////////////////////////////////////////////// void RenderPassParticle::OnPerform() { Super::OnPerform(); for (RenderFunction* function : renderFunctions) { if (function && function->enabled) { function->ExecuteRender(RenderPassType::Particle, nullptr); } } } ////////////////////////////////////////////////////////////////////////// void RenderPassParticle::OnFinish() { Super::OnFinish(); GlCall(glDisable(GL_BLEND)); GlCall(glDepthMask(GL_TRUE)); Renderer::EndScene(); } ////////////////////////////////////////////////////////////////////////// void RenderPassParticle::AddRenderFunction(RenderFunction* function) { renderFunctions.push_back(function); } ////////////////////////////////////////////////////////////////////////// void RenderPassParticle::RemoveRenderFunction(RenderFunction* function) { renderFunctions.erase(std::remove(renderFunctions.begin(), renderFunctions.end(), function), renderFunctions.end()); } //////////////////////////////////////////////////////////////////////////
[ "jackspink95@gmail.com" ]
jackspink95@gmail.com
5286e2233042edfd64eb5bcc38fdb91471cbc7e0
dd80a584130ef1a0333429ba76c1cee0eb40df73
/external/chromium_org/ppapi/shared_impl/file_type_conversion.cc
1a4bb16c7be7ffe1d02a540cd3c0191ca6390a23
[ "BSD-3-Clause", "LicenseRef-scancode-khronos", "MIT" ]
permissive
karunmatharu/Android-4.4-Pay-by-Data
466f4e169ede13c5835424c78e8c30ce58f885c1
fcb778e92d4aad525ef7a995660580f948d40bc9
refs/heads/master
2021-03-24T13:33:01.721868
2017-02-18T17:48:49
2017-02-18T17:48:49
81,847,777
0
2
MIT
2020-03-09T00:02:12
2017-02-13T16:47:00
null
UTF-8
C++
false
false
3,285
cc
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ppapi/shared_impl/file_type_conversion.h" #include "base/logging.h" #include "ppapi/c/pp_errors.h" #include "ppapi/c/ppb_file_io.h" #include "ppapi/shared_impl/time_conversion.h" namespace ppapi { int PlatformFileErrorToPepperError(base::PlatformFileError error_code) { switch (error_code) { case base::PLATFORM_FILE_OK: return PP_OK; case base::PLATFORM_FILE_ERROR_EXISTS: return PP_ERROR_FILEEXISTS; case base::PLATFORM_FILE_ERROR_NOT_FOUND: return PP_ERROR_FILENOTFOUND; case base::PLATFORM_FILE_ERROR_ACCESS_DENIED: case base::PLATFORM_FILE_ERROR_SECURITY: return PP_ERROR_NOACCESS; case base::PLATFORM_FILE_ERROR_NO_MEMORY: return PP_ERROR_NOMEMORY; case base::PLATFORM_FILE_ERROR_NO_SPACE: return PP_ERROR_NOSPACE; case base::PLATFORM_FILE_ERROR_NOT_A_DIRECTORY: return PP_ERROR_FAILED; case base::PLATFORM_FILE_ERROR_NOT_A_FILE: return PP_ERROR_NOTAFILE; default: return PP_ERROR_FAILED; } } bool PepperFileOpenFlagsToPlatformFileFlags(int32_t pp_open_flags, int* flags_out) { bool pp_read = !!(pp_open_flags & PP_FILEOPENFLAG_READ); bool pp_write = !!(pp_open_flags & PP_FILEOPENFLAG_WRITE); bool pp_create = !!(pp_open_flags & PP_FILEOPENFLAG_CREATE); bool pp_truncate = !!(pp_open_flags & PP_FILEOPENFLAG_TRUNCATE); bool pp_exclusive = !!(pp_open_flags & PP_FILEOPENFLAG_EXCLUSIVE); bool pp_append = !!(pp_open_flags & PP_FILEOPENFLAG_APPEND); // Pepper allows Touch on any open file, so always set this Windows-only flag. int flags = base::PLATFORM_FILE_WRITE_ATTRIBUTES; if (pp_read) flags |= base::PLATFORM_FILE_READ; if (pp_write) { flags |= base::PLATFORM_FILE_WRITE; } if (pp_append) { if (pp_write) return false; flags |= base::PLATFORM_FILE_APPEND; } if (pp_truncate && !pp_write) return false; if (pp_create) { if (pp_exclusive) { flags |= base::PLATFORM_FILE_CREATE; } else if (pp_truncate) { flags |= base::PLATFORM_FILE_CREATE_ALWAYS; } else { flags |= base::PLATFORM_FILE_OPEN_ALWAYS; } } else if (pp_truncate) { flags |= base::PLATFORM_FILE_OPEN_TRUNCATED; } else { flags |= base::PLATFORM_FILE_OPEN; } if (flags_out) *flags_out = flags; return true; } void PlatformFileInfoToPepperFileInfo(const base::PlatformFileInfo& info, PP_FileSystemType fs_type, PP_FileInfo* info_out) { DCHECK(info_out); info_out->size = info.size; info_out->creation_time = TimeToPPTime(info.creation_time); info_out->last_access_time = TimeToPPTime(info.last_accessed); info_out->last_modified_time = TimeToPPTime(info.last_modified); info_out->system_type = fs_type; if (info.is_directory) { info_out->type = PP_FILETYPE_DIRECTORY; } else if (info.is_symbolic_link) { DCHECK_EQ(PP_FILESYSTEMTYPE_EXTERNAL, fs_type); info_out->type = PP_FILETYPE_OTHER; } else { info_out->type = PP_FILETYPE_REGULAR; } } } // namespace ppapi
[ "karun.matharu@gmail.com" ]
karun.matharu@gmail.com
c65040764d97636ebe04d308f4879c547e14091f
a51d33fbcc5b56f26f36526ff8ede4907041fd14
/YBH_OgreServer/Parser.h
163089602bf0c384115d05a00afb08a98db2438f
[]
no_license
gunsct/YBH_OgreServer
5d798aec527788a0056bd5764ce46cebeb35039d
f36a10f396d703b1459d38970cbbe34724d4a53d
refs/heads/master
2021-01-10T10:57:39.224042
2015-12-11T05:41:48
2015-12-11T05:41:48
46,725,962
0
0
null
null
null
null
UHC
C++
false
false
773
h
//패킷 분석하는부분 클라이언트쪽에서 짜야할거같다 //아마 나는 패킷을 클라넘버,최초 생성여부,좌표 로 구성하고 이걸 특수문자나 띄어쓰기 단위로 따로 따로 분석해서 자료형에 맞춰 하지않을까 한다 //패킷 맨처음에 넘버랑 생성부분 세자리만 체크하면 됨 서버는 이거 3개만 필요 클라나 복잡하게 짜야지.. #include"Socket_client.h" #include <stdio.h> #include <conio.h> #include <string.h> class Parser{ private: char rebuf[512];//넘버2자리 구분문자 1자리 생성1자리 int restart; //int cli_num; 전역변수 쓸거임 int regist; public: Parser(); ~Parser(); int parsing_msg(char* buf); const char* re_packet_msg(char* buf, int cli_num); };
[ "gunsct@gmail.com" ]
gunsct@gmail.com
0e88e177ebe51ef8f7f429d1a31de8c0947e6a94
012cea2586d96cf67c8f4529103fc719a63a360f
/temp/SumMulListener.h
19165d8cd60860507cec3b6fe678641611cacd1e
[]
no_license
yaroslavsadin/coursera-cpp-yandex
ae7a4eebddb3e061a86f9a40e3eb2c02659b4bd4
dd5d0b92915cf7073ac37c7ca207cb46af87fc3f
refs/heads/master
2022-10-22T18:15:18.090912
2020-06-09T22:24:56
2020-06-09T22:24:56
170,770,232
0
0
null
null
null
null
UTF-8
C++
false
false
789
h
// Generated from SumMul.g4 by ANTLR 4.7.2 #pragma once #include "antlr4-runtime.h" #include "SumMulParser.h" /** * This interface defines an abstract listener for a parse tree produced by SumMulParser. */ class SumMulListener : public antlr4::tree::ParseTreeListener { public: virtual void enterMain(SumMulParser::MainContext *ctx) = 0; virtual void exitMain(SumMulParser::MainContext *ctx) = 0; virtual void enterMul(SumMulParser::MulContext *ctx) = 0; virtual void exitMul(SumMulParser::MulContext *ctx) = 0; virtual void enterNumber(SumMulParser::NumberContext *ctx) = 0; virtual void exitNumber(SumMulParser::NumberContext *ctx) = 0; virtual void enterAdd(SumMulParser::AddContext *ctx) = 0; virtual void exitAdd(SumMulParser::AddContext *ctx) = 0; };
[ "ysadin@synopsys.com" ]
ysadin@synopsys.com
12e87d7d13d1bac7ee7a66315afd2d4feae1f73b
db6a98ff4743abf10fa798ed05d714a9be1c81d6
/Source.cpp
d56717989716c2572bccbe83ae4603023e0bf5b8
[]
no_license
Jahnava/max-value-of-two-values
43fe38012c706055b4e7fa58312ea7bc47138b35
75b7ccdd8940765deb5b29319e1ea1f871b37f82
refs/heads/master
2022-12-09T11:18:13.705377
2020-09-18T14:30:41
2020-09-18T14:30:41
296,635,396
0
0
null
null
null
null
UTF-8
C++
false
false
1,503
cpp
//find the max value from two values entered when prompted #include<iostream> #include<string> #include<iomanip> int main() { //using stuff from the standard library using std::cin; using std::cout; using std::endl; //using std::fixed //variables int value1; //value entered by the user int value2; //value entered by the user int value3; //value entered by user int max; //determined value //prompt the user for input cout << "Enter the first value: "; cin >> value1; cout << "Enter the second value: "; cin >> value2; cout << "Enter the third value: "; cin >> value3; //find the maximum value if (value1 > value2 && value1 > value3 ) //value one has to be greater than value 2 and (amperand symbol) greater than value 3 //100 90 80 three values. is 100 greater than 90 and is 100 greater than 80, so this would be true and max would be value 1. { max = value1; } else if (value2 > value1 && value2 > value3) //if value two is greater than value one & value 2 is greater than value 3 // ex. 90 100 80 is 100 greater than 90,yes. is 100 greater than 80, true, so this would work { max = value2; } else { max = value3; }//if the max is not value one or value two than value three is the only value left, so max would equal value3. //display the result cout << std::fixed << endl << endl; cout << "The maximum value between " << value1 <<", " << value2 << ", and " << value3 << " is " << max << endl << endl; system("pause"); return 0; }
[ "jahnavalmt@gmail.com" ]
jahnavalmt@gmail.com
4bcc07082d03d062f124cb78b3ca91327fa46d39
7d9b2b10160cf51e45593b3daf7e4d90251dd4e0
/Image_Harmonization_Datasets-master/Lalonde and Efros/colorStatistics/3rd_party/nearestneighbor/BruteSearchMex.cpp
f187dd6f55e877e4c08ba8865198ea7ab496c56f
[]
no_license
oscar00v/proyecto3
8709e2d2766154e21a5b4e34722ec2de8b006795
391747ea08074de590b9f20204fbc46af7d8a48e
refs/heads/main
2023-04-14T02:56:51.171596
2021-04-27T02:01:55
2021-04-27T02:01:55
360,209,592
0
0
null
null
null
null
UTF-8
C++
false
false
6,713
cpp
#include "mex.h" #include "BruteSearchTranspose.cpp" // In Matlab la funzione deve essere idc=NNSearch(x,y,pk,ptrtree) /* the gateway function */ void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { double *p;//reference points double *qp;//query points double* results; char* String;//Input String int String_Leng;//length of the input String int N,Nq,dim,i,j; double* distances;//distances for k-neighbors int* idck;//k-neighbors int idc;//nearest neighbor double*k; int kint; double* r; double* D;//Output distance matrix double mindist; //Errors Check if (nlhs>2) { mexErrMsgTxt("Too many outputs"); } if (nrhs<2) { mexErrMsgTxt("Not enough inputs"); } N=mxGetN(prhs[0]);//number of reference points Nq=mxGetN(prhs[1]);//number of query points dim=mxGetM(prhs[0]);//dimension of points // mexPrintf("Dimension %4.4d\n",dim); //Check is inputs has the same dimension if (mxGetM(prhs[1])!=dim) { mexErrMsgTxt("Points must have the same dimension"); } //Checking input format if( !mxIsDouble(prhs[0]) || !mxIsDouble(prhs[1]) ) { mexErrMsgTxt("Inputs points must be double matrix "); } p = mxGetPr(prhs[0]);//puntatore all'array dei punti qp = mxGetPr(prhs[1]);//puntatore all'array dei punti //Getting the Input String if (nrhs>2) { if(!mxIsChar(prhs[2]))//is the input a string { mexErrMsgTxt("Input 3 must be of type char."); } String_Leng=mxGetN(prhs[2]);//StringLength if (String_Leng>1)//Check if string is correct { mexErrMsgTxt("Input 3 must be only one String."); } String =mxArrayToString (prhs[2]);//get the string if(String == NULL) { mexErrMsgTxt("Could not convert input to string."); } // mexPrintf("The input string is: %s\n",String); } else { String=NULL; // mexPrintf("No input string\n"); } //Choose the algorithm from the input String if(String==NULL) { //Nearest Neighbor // mexPrintf("Nearest Neighbor\n"); plhs[0] = mxCreateDoubleMatrix(Nq, 1,mxREAL);//costruisce l'output array results = mxGetPr(plhs[0]);//appicicaci il puntatore if (nlhs==1) { //Search with no distance for (i=0;i<Nq;i++) { results[i]=BruteSearch(p,&qp[i*dim] ,N,dim,&mindist)+1; } // mexPrintf("end search\n"); } else //Search with distance { //build the output distance matrix plhs[1] = mxCreateDoubleMatrix(Nq, 1,mxREAL); D = mxGetPr(plhs[1]);//appicicaci il puntatore for (i=0;i<Nq;i++) { results[i]=BruteSearch(p,&qp[i*dim] ,N,dim,&mindist)+1; D[i]=sqrt(mindist); } // mexPrintf("end search\n"); } } else if(String[0]=='k') { //KNearest Neighbor // mexPrintf("KNearest Neighbor\n"); if (nrhs<4) { mexErrMsgTxt("Number of neighbours not given"); } k=mxGetPr(prhs[3]); kint=k[0]; idck=new int[kint]; distances=new double[kint]; plhs[0] = mxCreateDoubleMatrix(Nq,kint,mxREAL);//costruisce l'output array results = mxGetPr(plhs[0]);//appicicaci il puntatore if (nlhs==1) //Search without Distance matrix output { for (i=0;i<Nq;i++) { BruteKSearch(p,&qp[i*dim] ,kint,N,dim,distances,idck);//Run the query for(j=0;j<kint;j++) { results[j*Nq+i]=idck[j]+1;//plus one Matlab notation } } } else//Search with Distance matrix { plhs[1] = mxCreateDoubleMatrix(Nq,kint,mxREAL);//costruisce l'output array D = mxGetPr(plhs[1]);//appicicaci il puntatore for (i=0;i<Nq;i++) { BruteKSearch(p,&qp[i*dim] ,kint,N,dim,distances,idck);//Run the query for(j=0;j<kint;j++) { D[j*Nq+i]=sqrt(distances[j]); results[j*Nq+i]=idck[j]+1;//plus one Matlab notation } } } //deallocatememory delete [] distances; delete [] idck; } else if(String[0]=='r') { //Radius Search // mexPrintf("radius\n"); if (Nq>1) { mexErrMsgTxt("Radius Serach possible with only one query point"); } if (nrhs<4) { mexErrMsgTxt("Radius not given"); } r=mxGetPr(prhs[3]); vector<int> idcv; if (nlhs==1)//Search without distance { BruteRSearch(p,qp,*r,N,dim,&idcv); kint=idcv.size();//Size of vector plhs[0] = mxCreateDoubleMatrix(1,kint,mxREAL);//costruisce l'output array results = mxGetPr(plhs[0]); for(i=0;i<kint;i++)//copy in the otput array { // mexPrintf("%4.1d\n",idcv[i]); results[i]=idcv[i]+1;//copy the output } } else { vector<double> distvect;//declare the distance vector BruteRSearchWithDistance(p,qp,*r,N,dim,&idcv,&distvect); kint=idcv.size();//Size of vector plhs[0] = mxCreateDoubleMatrix(1,kint,mxREAL);//costruisce l'output array results = mxGetPr(plhs[0]); plhs[1] = mxCreateDoubleMatrix(1,kint,mxREAL);//costruisce l'output array D= mxGetPr(plhs[1]); for(i=0;i<kint;i++)//copy in the otput array { results[i]=idcv[i]+1;//copy the output D[i]=distvect[i];//The distance is already radsquared } } } else { mexErrMsgTxt("Invalid Input String."); } }
[ "oscar00v@gmail.com" ]
oscar00v@gmail.com
1896faeb3e1a2779c2498f0ebc2b0207060ae965
50602aa4fcabb94a61ab2d83b195d82d2f496f4a
/gateway/slamware_sdk_linux-x86_64-gcc4.8/linux-x86_64-release/include/rpos/system/serialization/i_stream.h
01dd4b36254bb9cef0affc2c5803ec908d061427
[]
no_license
zhuxibrian/SlamGateway
b7d6a050cfb33c1707ed21d773d0254b82f8b3c5
42a2dfb1daa71765749bdf8aeac46f560b896a8f
refs/heads/master
2021-05-10T22:21:08.630199
2018-04-08T06:00:53
2018-04-08T06:00:53
118,253,159
0
1
null
2018-04-06T07:10:24
2018-01-20T15:06:30
C++
UTF-8
C++
false
false
1,378
h
#pragma once #include <stdint.h> #include <vector> #include <rpos/core/rpos_core_config.h> namespace rpos { namespace system { namespace serialization { class RPOS_CORE_API IStream { public: virtual size_t read(void *buffer, size_t count) = 0; virtual size_t write(const void *buffer, size_t count) = 0; virtual bool empty(); IStream(); virtual ~IStream(); size_t readBuffer(uint8_t *buffer, size_t count); void writeBuffer(const uint8_t *buffer, size_t count); }; class RPOS_CORE_API ISerializable { public: virtual bool readFromStream(IStream &in) = 0; virtual bool writeToStream(IStream &out) const = 0; }; #define DECLARE_ISTREAM_READ_WRITE( T ) \ RPOS_CORE_API IStream& operator<<(IStream&out, const T &a); \ RPOS_CORE_API IStream& operator>>(IStream&in, T &a); DECLARE_ISTREAM_READ_WRITE(bool) DECLARE_ISTREAM_READ_WRITE(uint8_t) DECLARE_ISTREAM_READ_WRITE(int8_t) DECLARE_ISTREAM_READ_WRITE(uint16_t) DECLARE_ISTREAM_READ_WRITE(int16_t) DECLARE_ISTREAM_READ_WRITE(uint32_t) DECLARE_ISTREAM_READ_WRITE(int32_t) DECLARE_ISTREAM_READ_WRITE(uint64_t) DECLARE_ISTREAM_READ_WRITE(int64_t) DECLARE_ISTREAM_READ_WRITE(float) DECLARE_ISTREAM_READ_WRITE(double) DECLARE_ISTREAM_READ_WRITE(std::vector<uint8_t>) } } }
[ "zhuxibrian@icloud.com" ]
zhuxibrian@icloud.com
df4cc3468cce6c892f3a9266987bfecc7f5a6fa2
2a0e1052acd5d9fe1f75a93e906175306c412b3e
/Mark Lizzimore CGP600 Tutorial 8 E2/camera.h
4109c6f2896574ce08fe42520f7a251a0b0acacb
[]
no_license
Paramedic293-S/Advanced-Games-Programming
8a4adf050fc3c9ab5bc9d5ef59aec45615c96e85
805427351f86d65a30fa3644647b260a3792247f
refs/heads/master
2021-08-31T10:24:12.381505
2017-12-21T02:06:55
2017-12-21T02:06:55
105,126,416
0
0
null
null
null
null
UTF-8
C++
false
false
690
h
#include <windows.h> #include <d3d11.h> #include <d3dx11.h> #include <dxerr.h> #include <stdio.h> #define _XM_NO_INTRINSICS_ #define XM_NO_ALIGNMENT #include <xnamath.h> class camera { private: float mx; float my; float mz; float mdx; float mdz; float m_camera_rotation; XMVECTOR m_position = XMVectorSet(0.0, 0.0, -5.0, 0.0); XMVECTOR m_lookat = XMVectorSet(0.0, 0.0, -4.0, 0.0); XMVECTOR m_up = XMVectorSet(0.0, 1.0, 0.0, 0.0); XMMATRIX view = XMMatrixLookAtLH(m_position, m_lookat, m_up); public: camera(float initx, float inity, float initz, float camerarot); void rotate(float rotatedegrees); void forward(float distance); void up(); XMMATRIX GetViewMatrix(); };
[ "Paramedic292@hotmail.co.uk" ]
Paramedic292@hotmail.co.uk
70952be2dfe883aaea0b819607228b363f39bada
666e2ff7aa1a4bcf3592331062ce774373fe6fa6
/sip/sip_transport_dtls_udp.h
3c2280709225457d7b4cfc07535d096f07d8a2b7
[]
no_license
asyr625/mini_sip
aeffd6e5ea1dafafa817b1137859b41351fe9580
12ea4b9a03585b5c7e5b5faeeed0a5bc6a9c19cc
refs/heads/master
2021-01-20T12:06:33.212419
2015-11-24T02:33:26
2015-11-24T02:33:26
46,761,914
0
1
null
null
null
null
UTF-8
C++
false
false
1,301
h
#ifndef SIP_TRANSPORT_DTLS_UDP_H #define SIP_TRANSPORT_DTLS_UDP_H #include "dtls_socket.h" #include "sip_transport.h" class Sip_Transport_Dtls_Udp : public Sip_Transport { public: Sip_Transport_Dtls_Udp( SRef<Library *> lib ); ~Sip_Transport_Dtls_Udp(); virtual bool is_secure() const { return true; } virtual std::string get_protocol() const { return "udp"; } virtual std::string get_via_protocol() const { return "DTLS-UDP"; } virtual int get_socket_type() const { return SSOCKET_TYPE_DTLS_UDP; } virtual std::string get_naptr_service() const { return "SIPS+D2U"; } virtual SRef<Sip_Socket_Server *> create_server( SRef<Sip_Socket_Receiver*> receiver, bool ipv6, const std::string &ip_string, int &pref_port, SRef<Certificate_Set *> cert_db = NULL, SRef<Certificate_Chain *> cert_chain = NULL ); virtual std::string get_name() const { return "DTLS-UDP"; } virtual unsigned int get_version() const; virtual std::string get_description() const { return "SIP Transport DTLS-UDP"; } virtual std::string get_mem_object_type() const { return get_name(); } }; #endif // SIP_TRANSPORT_DTLS_UDP_H
[ "619695356@qq.com" ]
619695356@qq.com
be34c52a024a128e282e242a677f14bb5327c993
cdd335c8ab40c85628e516f1ab7060fa4ca8f40e
/SourceCode/lazada/request/lazada_api_request_update_product.h
a7717c7eb747a162ba728ee32a814fa109545825
[]
no_license
devcodegit/sghshasaghahgsjsjsjajjsjasjajsjajjsajsjjajsjajsjajsjajsjajsaj
d98252a3f93784b1f5ef07b901fe0c9f3197a392
d0aa6017feacc0b50f5b1188d9f8e1b570b3ca5b
refs/heads/master
2021-01-20T16:22:27.646522
2017-06-27T10:17:57
2017-06-27T10:17:57
90,835,207
0
0
null
null
null
null
UTF-8
C++
false
false
455
h
#ifndef LAZADA_API_REQUEST_UPDATE_PRODUCT_H #define LAZADA_API_REQUEST_UPDATE_PRODUCT_H #include "lazada_api_request_get.h" namespace Core { namespace Request { class LazadaApiRequestUpdateProduct : public LazadaApiRequestGET { public: LazadaApiRequestUpdateProduct(IApiRequestListener *a_pListener); virtual void generateParams(QHash<QString, QString>* a_pParams); }; }} #endif // LAZADA_API_REQUEST_UPDATE_PRODUCT_H
[ "datvt@vng.com.vn" ]
datvt@vng.com.vn
96cf7d3776e42b3f8ca6ae179412c48c25093ed1
80a4c44ff3085a1b3cf1dac0a7d4c0f97d75704b
/examples/ex4.cpp
933e1ce21f4b0af958165183d0024ff2bdcf6b04
[ "MIT" ]
permissive
Cryst4L/Backprop
71b9ce0eea7860dff44ed00fc6f7845e88eaad20
89d344074fa597dcf39ce851e6071ceff85d47cd
refs/heads/master
2021-09-16T23:44:04.544912
2021-08-05T10:50:20
2021-08-05T10:50:20
241,076,462
1
0
null
null
null
null
UTF-8
C++
false
false
4,344
cpp
// ConvNet + Dropout #include "Backprop/Core.h" using namespace Backprop; // 98.83 s0 | 98.86 s9 | 98.90 s10 | 99.05 s11 int main(void) { srand(0); /// Load the dataset /////////////////////////////////////////////////////// MNIST train_set("data/MNIST", TRAIN); /// Display some data ////////////////////////////////////////////////////// const int sample_size = 28; std::vector <MatrixXd> samples; for (int i = 0; i < 100; i++) { VectorXd sample = train_set.samples().row(i); MatrixXd reshaped = Map <MatrixXd> (sample.data(), sample_size, sample_size); samples.push_back(reshaped); } MatrixXd sample_map = buildMapfromData(samples, sample_size, sample_size); Display sample_display(&sample_map, "Samples"); // Setup the Net /////////////////////////////////////////////////////////// Network net; net.addConvolutionalLayer(28, 28, 7, 1, 16, 0); net.addActivationLayer(RELU); net.addDropoutLayer(0.25); net.addSamplingLayer(22, 22, 16, 2); net.addConvolutionalLayer(11, 11, 5, 16, 16); net.addActivationLayer(RELU); net.addDropoutLayer(0.25); net.addLinearLayer(784, 50); net.addActivationLayer(RELU); net.addDropoutLayer(0.25); net.addLinearLayer(50, 10); net.addActivationLayer(RELU); // Train the Net /////////////////////////////////////////////////////////// Dataset batch; const int N_BATCH = 100; const int BATCH_SIZE = 1000; VectorXd train_costs = VectorXd::Zero(N_BATCH); Plot plot(&train_costs, "train cost", "red"); Timer timer; for (int n = 0; n < N_BATCH; n++) { // Build a batch /////////////////////////////////////////////////////// batch.inputs.clear(); batch.targets.clear(); for (int i = 0; i < BATCH_SIZE; i++) { int s = rand() % train_set.samples().rows(); VectorXd sample = train_set.samples().row(s); batch.inputs.push_back(sample); VectorXd target = train_set.targets().row(s); batch.targets.push_back(target); } // Train the net on the batch ////////////////////////////////////////// train_costs(n) = SGD(net, batch, SSE, 0.01); std::cout << "Average cost = " << train_costs(n) << std::endl; // Plot the training progress ////////////////////////////////////////////// plot.render(); } float elapsed = timer.getTimeSec(); std::cout << " elapsed time : " << elapsed << "sec" << std::endl; // Display the features //////////////////////////////////////////////////// Convolutional* conv_layer_p = (Convolutional*) &(net.layer(0)); std::vector <MatrixXd> kernels = conv_layer_p->getKernels(); int kernel_size = kernels[0].rows(); MatrixXd kernel_map = buildMapfromData(kernels, kernel_size, kernel_size); Display kernel_display(&kernel_map, "Kernels"); ///////////////////////////////// Convolutional* conv_layer_2_p = (Convolutional*) &(net.layer(4)); kernels = conv_layer_2_p->getKernels(); kernel_size = kernels[0].rows(); MatrixXd kernel_map_2 = buildMapfromData(kernels, kernel_size, kernel_size); Display kernel_display_2(&kernel_map_2, "Kernels"); ///////////////////////////////// Linear* lin_layer_p = (Linear*) &(net.layer(7)); std::vector <VectorXd> unshaped_features = lin_layer_p->getFeatures(); int feature_size = 7; int nb_features_per_row = 16; std::vector <MatrixXd> features; for (int i = 0; i < (int) unshaped_features.size(); i++) { for (int j = 0; j < nb_features_per_row; j++) { int size = feature_size * feature_size; VectorXd unshaped = unshaped_features[i].segment(j * size, size); MatrixXd reshaped = Map <MatrixXd> (unshaped.data(), feature_size, feature_size); features.push_back(reshaped); } } MatrixXd feature_map = buildMapfromData(features, feature_size, feature_size); Backprop::Display feature_display(&feature_map, "Features"); // Test the net accuracy /////////////////////////////////////////////////// MNIST test_set("data/MNIST", TEST); net.disableDropout(); int acc = 0; for (int i = 0; i < test_set.nbSamples(); i++) { VectorXd sample = test_set.samples().row(i); VectorXd target = test_set.targets().row(i); VectorXd prediction = net.forwardPropagate(sample); VectorXd::Index value, guess; target.maxCoeff(&value); prediction.maxCoeff(&guess); if (value == guess) acc++; } std::cout << " accuracy = " << acc / (float) test_set.nbSamples() << std::endl; return 0; }
[ "bhalimi@outlook.fr" ]
bhalimi@outlook.fr
369b583ead02525d93573d96829397024bf9a5f7
64b1b87cb2ad937835539e45ddc9fbcd2fa3cd59
/III - GoldHook/CheatThread.hpp
28d948c69d51b1fea63c8e12549ffb59cd8c9dcd
[]
no_license
gameSecMaterials/GTAIII-DE-GoldHook
228bc4d1dac309336478e2a9c63314922caee43b
287d29032a065fabfa53919ca10a105d66a44138
refs/heads/main
2023-08-30T19:22:48.772350
2021-11-15T19:24:19
2021-11-15T19:24:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
688
hpp
DWORD m_dDummy = 0x0; static void CheatThread() { if (UI::Settings::Vehicle::m_iSpawn != 0) { static void* m_pCarID = reinterpret_cast<void*>(Game::Functions::m_uSpawnRhino + 0x6C); if (VirtualProtect(m_pCarID, 1, PAGE_EXECUTE_READWRITE, &m_dDummy)) { *reinterpret_cast<unsigned char*>(m_pCarID) = static_cast<unsigned char>(UI::Settings::Vehicle::m_iSpawn); memset(Game::Globals::m_pSpawnRhino_Vehicle, 0, sizeof(uintptr_t)); reinterpret_cast<void(__fastcall*)()>(Game::Functions::m_uSpawnRhino)(); /* * Yes tho, its easy to call func with patched vehicle id to spawn then fucking reverse the whole shit... */ UI::Settings::Vehicle::m_iSpawn = 0; } } }
[ "sneakyevildogs@gmail.com" ]
sneakyevildogs@gmail.com
9d19aca1c87f30d0e5324634f76464880c65fa57
d1cee40adee73afdbce5b3582bbe4761b595c4e1
/back/RtmpLivePushSDK/boost/boost/graph/compressed_sparse_row_graph.hpp
a87463a24ad0d4afdb387c9b597543299184f4e6
[ "BSL-1.0" ]
permissive
RickyJun/live_plugin
de6fb4fa8ef9f76fffd51e2e51262fb63cea44cb
e4472570eac0d9f388ccac6ee513935488d9577e
refs/heads/master
2023-05-08T01:49:52.951207
2021-05-30T14:09:38
2021-05-30T14:09:38
345,919,594
2
0
null
null
null
null
UTF-8
C++
false
false
68,139
hpp
// Copyright 2005-2009 The Trustees of Indiana University. // 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) // Authors: Jeremiah Willcock // Douglas Gregor // Andrew Lumsdaine // Compressed sparse row graph type #ifndef BOOST_GRAPH_COMPRESSED_SPARSE_ROW_GRAPH_HPP #define BOOST_GRAPH_COMPRESSED_SPARSE_ROW_GRAPH_HPP #include <vector> #include <utility> #include <algorithm> #include <climits> #include "assert.hpp" #include <iterator> #if 0 #include <iostream> // For some debugging code below #endif #include "graph_traits.hpp" #include "properties.hpp" #include "filtered_graph.hpp" // For keep_all #include "indexed_properties.hpp" #include "compressed_sparse_row_struct.hpp" #include "iteration_macros.hpp" #include "counting_iterator.hpp" #include "reverse_iterator.hpp" #include "zip_iterator.hpp" #include "transform_iterator.hpp" #include "tuple.hpp" #include "property_map.hpp" #include "integer.hpp" #include "iterator_facade.hpp" #include "if.hpp" #include "graph_selectors.hpp" #include "properties.hpp" #include "static_assert.hpp" #include "hash.hpp" #include "next_prior.hpp" #include "transform_value_property_map.hpp" #include "print.hpp" namespace boost { // A tag type indicating that the graph in question is a compressed // sparse row graph. This is an internal detail of the BGL. struct csr_graph_tag; // A type (edges_are_sorted_t) and a value (edges_are_sorted) used to indicate // that the edge list passed into the CSR graph is already sorted by source // vertex. enum edges_are_sorted_t {edges_are_sorted}; // A type (edges_are_sorted_global_t) and a value (edges_are_sorted_global) // used to indicate that the edge list passed into the CSR graph is already // sorted by source vertex. enum edges_are_sorted_global_t {edges_are_sorted_global}; // A type (edges_are_unsorted_t) and a value (edges_are_unsorted) used to // indicate that the edge list passed into the CSR graph is not sorted by // source vertex. This version caches the edge information in memory, and thus // requires only a single pass over the input data. enum edges_are_unsorted_t {edges_are_unsorted}; // A type (edges_are_unsorted_multi_pass_t) and a value // (edges_are_unsorted_multi_pass) used to indicate that the edge list passed // into the CSR graph is not sorted by source vertex. This version uses less // memory but requires multi-pass capability on the iterators. enum edges_are_unsorted_multi_pass_t {edges_are_unsorted_multi_pass}; // A type (edges_are_unsorted_multi_pass_global_t) and a value // (edges_are_unsorted_multi_pass_global) used to indicate that the edge list // passed into the CSR graph is not sorted by source vertex. This version uses // less memory but requires multi-pass capability on the iterators. The // global mapping and filtering is done here because it is often faster and it // greatly simplifies handling of edge properties. enum edges_are_unsorted_multi_pass_global_t {edges_are_unsorted_multi_pass_global}; // A type (construct_inplace_from_sources_and_targets_t) and a value // (construct_inplace_from_sources_and_targets) used to indicate that mutable // vectors of sources and targets (and possibly edge properties) are being used // to construct the CSR graph. These vectors are sorted in-place and then the // targets and properties are swapped into the graph data structure. enum construct_inplace_from_sources_and_targets_t {construct_inplace_from_sources_and_targets}; // A type (construct_inplace_from_sources_and_targets_global_t) and a value // (construct_inplace_from_sources_and_targets_global) used to indicate that // mutable vectors of sources and targets (and possibly edge properties) are // being used to construct the CSR graph. These vectors are sorted in-place // and then the targets and properties are swapped into the graph data // structure. It is assumed that global indices (for distributed CSR) are // used, and a map is required to convert those to local indices. This // constructor is intended for internal use by the various CSR graphs // (sequential and distributed). enum construct_inplace_from_sources_and_targets_global_t {construct_inplace_from_sources_and_targets_global}; // A type (edges_are_unsorted_global_t) and a value (edges_are_unsorted_global) // used to indicate that the edge list passed into the CSR graph is not sorted // by source vertex. The data is also stored using global vertex indices, and // must be filtered to choose only local vertices. This constructor caches the // edge information in memory, and thus requires only a single pass over the // input data. This constructor is intended for internal use by the // distributed CSR constructors. enum edges_are_unsorted_global_t {edges_are_unsorted_global}; /**************************************************************************** * Local helper macros to reduce typing and clutter later on. * ****************************************************************************/ #define BOOST_CSR_GRAPH_TEMPLATE_PARMS \ typename Directed, typename VertexProperty, typename EdgeProperty, \ typename GraphProperty, typename Vertex, typename EdgeIndex #define BOOST_CSR_GRAPH_TYPE \ compressed_sparse_row_graph<Directed, VertexProperty, EdgeProperty, \ GraphProperty, Vertex, EdgeIndex> #define BOOST_DIR_CSR_GRAPH_TEMPLATE_PARMS \ typename VertexProperty, typename EdgeProperty, \ typename GraphProperty, typename Vertex, typename EdgeIndex #define BOOST_DIR_CSR_GRAPH_TYPE \ compressed_sparse_row_graph<directedS, VertexProperty, EdgeProperty, \ GraphProperty, Vertex, EdgeIndex> #define BOOST_BIDIR_CSR_GRAPH_TEMPLATE_PARMS \ typename VertexProperty, typename EdgeProperty, \ typename GraphProperty, typename Vertex, typename EdgeIndex #define BOOST_BIDIR_CSR_GRAPH_TYPE \ compressed_sparse_row_graph<bidirectionalS, VertexProperty, EdgeProperty, \ GraphProperty, Vertex, EdgeIndex> namespace detail { template <typename T> struct default_construct_iterator: public boost::iterator_facade<default_construct_iterator<T>, T, boost::random_access_traversal_tag, const T&> { typedef boost::iterator_facade<default_construct_iterator<T>, T, std::random_access_iterator_tag, const T&> base_type; T saved_value; const T& dereference() const {return saved_value;} bool equal(default_construct_iterator i) const {return true;} void increment() {} void decrement() {} void advance(typename base_type::difference_type) {} typename base_type::difference_type distance_to(default_construct_iterator) const {return 0;} }; template <typename Less> struct compare_first { Less less; compare_first(Less less = Less()): less(less) {} template <typename Tuple> bool operator()(const Tuple& a, const Tuple& b) const { return less(a.template get<0>(), b.template get<0>()); } }; template <int N, typename Result> struct my_tuple_get_class { typedef const Result& result_type; template <typename Tuple> result_type operator()(const Tuple& t) const { return t.template get<N>(); } }; } /** Compressed sparse row graph. * * Vertex and EdgeIndex should be unsigned integral types and should * specialize numeric_limits. */ template<typename Directed = directedS, typename VertexProperty = no_property, typename EdgeProperty = no_property, typename GraphProperty = no_property, typename Vertex = std::size_t, typename EdgeIndex = Vertex> class compressed_sparse_row_graph; // Not defined template<typename VertexProperty, typename EdgeProperty, typename GraphProperty, typename Vertex, typename EdgeIndex> class compressed_sparse_row_graph<directedS, VertexProperty, EdgeProperty, GraphProperty, Vertex, EdgeIndex> : public detail::indexed_vertex_properties<BOOST_DIR_CSR_GRAPH_TYPE, VertexProperty, Vertex, typed_identity_property_map<Vertex> > { public: typedef detail::indexed_vertex_properties<compressed_sparse_row_graph, VertexProperty, Vertex, typed_identity_property_map<Vertex> > inherited_vertex_properties; public: // For Property Graph typedef GraphProperty graph_property_type; typedef typename lookup_one_property<GraphProperty, graph_bundle_t>::type graph_bundled; typedef detail::compressed_sparse_row_structure<EdgeProperty, Vertex, EdgeIndex> forward_type; public: /* At this time, the compressed sparse row graph can only be used to * create directed and bidirectional graphs. In the future, * undirected CSR graphs will also be supported. */ // BOOST_STATIC_ASSERT((is_same<Directed, directedS>::value)); // Concept requirements: // For Graph typedef Vertex vertex_descriptor; typedef detail::csr_edge_descriptor<Vertex, EdgeIndex> edge_descriptor; typedef directed_tag directed_category; typedef allow_parallel_edge_tag edge_parallel_category; class traversal_category: public incidence_graph_tag, public adjacency_graph_tag, public vertex_list_graph_tag, public edge_list_graph_tag {}; static vertex_descriptor null_vertex() { return vertex_descriptor(-1); } // For VertexListGraph typedef counting_iterator<Vertex> vertex_iterator; typedef Vertex vertices_size_type; // For EdgeListGraph typedef EdgeIndex edges_size_type; // For IncidenceGraph typedef detail::csr_out_edge_iterator<compressed_sparse_row_graph> out_edge_iterator; typedef EdgeIndex degree_size_type; // For AdjacencyGraph typedef typename std::vector<Vertex>::const_iterator adjacency_iterator; // For EdgeListGraph typedef detail::csr_edge_iterator<compressed_sparse_row_graph> edge_iterator; // For BidirectionalGraph (not implemented) typedef void in_edge_iterator; // For internal use typedef csr_graph_tag graph_tag; typedef typename forward_type::inherited_edge_properties::edge_bundled edge_bundled; typedef typename forward_type::inherited_edge_properties::edge_push_back_type edge_push_back_type; typedef typename forward_type::inherited_edge_properties::edge_property_type edge_property_type; // Constructors // Default constructor: an empty graph. compressed_sparse_row_graph(): m_property() {} // With numverts vertices compressed_sparse_row_graph(vertices_size_type numverts) : inherited_vertex_properties(numverts), m_forward(numverts) {} // From number of vertices and unsorted list of edges template <typename MultiPassInputIterator> compressed_sparse_row_graph(edges_are_unsorted_multi_pass_t, MultiPassInputIterator edge_begin, MultiPassInputIterator edge_end, vertices_size_type numverts, const GraphProperty& prop = GraphProperty()) : inherited_vertex_properties(numverts), m_property(prop) { m_forward.assign_unsorted_multi_pass_edges(edge_begin, edge_end, numverts, typed_identity_property_map<vertices_size_type>(), keep_all()); } // From number of vertices and unsorted list of edges, plus edge properties template <typename MultiPassInputIterator, typename EdgePropertyIterator> compressed_sparse_row_graph(edges_are_unsorted_multi_pass_t, MultiPassInputIterator edge_begin, MultiPassInputIterator edge_end, EdgePropertyIterator ep_iter, vertices_size_type numverts, const GraphProperty& prop = GraphProperty()) : inherited_vertex_properties(numverts), m_forward(), m_property(prop) { m_forward.assign_unsorted_multi_pass_edges(edge_begin, edge_end, ep_iter, numverts, typed_identity_property_map<vertices_size_type>(), keep_all()); } // From number of vertices and unsorted list of edges, with filter and // global-to-local map template <typename MultiPassInputIterator, typename GlobalToLocal, typename SourcePred> compressed_sparse_row_graph(edges_are_unsorted_multi_pass_global_t, MultiPassInputIterator edge_begin, MultiPassInputIterator edge_end, vertices_size_type numlocalverts, const GlobalToLocal& global_to_local, const SourcePred& source_pred, const GraphProperty& prop = GraphProperty()) : inherited_vertex_properties(numlocalverts), m_forward(), m_property(prop) { m_forward.assign_unsorted_multi_pass_edges(edge_begin, edge_end, numlocalverts, global_to_local, source_pred); } // From number of vertices and unsorted list of edges, plus edge properties, // with filter and global-to-local map template <typename MultiPassInputIterator, typename EdgePropertyIterator, typename GlobalToLocal, typename SourcePred> compressed_sparse_row_graph(edges_are_unsorted_multi_pass_global_t, MultiPassInputIterator edge_begin, MultiPassInputIterator edge_end, EdgePropertyIterator ep_iter, vertices_size_type numlocalverts, const GlobalToLocal& global_to_local, const SourcePred& source_pred, const GraphProperty& prop = GraphProperty()) : inherited_vertex_properties(numlocalverts), m_forward(), m_property(prop) { m_forward.assign_unsorted_multi_pass_edges(edge_begin, edge_end, ep_iter, numlocalverts, global_to_local, source_pred); } // From number of vertices and sorted list of edges (new interface) template<typename InputIterator> compressed_sparse_row_graph(edges_are_sorted_t, InputIterator edge_begin, InputIterator edge_end, vertices_size_type numverts, edges_size_type numedges = 0, const GraphProperty& prop = GraphProperty()) : m_property(prop) { m_forward.assign_from_sorted_edges(edge_begin, edge_end, typed_identity_property_map<vertices_size_type>(), keep_all(), numverts, numedges); inherited_vertex_properties::resize(numverts); } // From number of vertices and sorted list of edges (new interface) template<typename InputIterator, typename EdgePropertyIterator> compressed_sparse_row_graph(edges_are_sorted_t, InputIterator edge_begin, InputIterator edge_end, EdgePropertyIterator ep_iter, vertices_size_type numverts, edges_size_type numedges = 0, const GraphProperty& prop = GraphProperty()) : m_property(prop) { m_forward.assign_from_sorted_edges(edge_begin, edge_end, ep_iter, typed_identity_property_map<vertices_size_type>(), keep_all(), numverts, numedges); inherited_vertex_properties::resize(numverts); } // From number of vertices and sorted list of edges, filtered and global (new interface) template<typename InputIterator, typename GlobalToLocal, typename SourcePred> compressed_sparse_row_graph(edges_are_sorted_global_t, InputIterator edge_begin, InputIterator edge_end, const GlobalToLocal& global_to_local, const SourcePred& source_pred, vertices_size_type numverts, const GraphProperty& prop = GraphProperty()) : m_property(prop) { m_forward.assign_from_sorted_edges(edge_begin, edge_end, global_to_local, source_pred, numverts, 0); inherited_vertex_properties::resize(numverts); } // From number of vertices and sorted list of edges (new interface) template<typename InputIterator, typename EdgePropertyIterator, typename GlobalToLocal, typename SourcePred> compressed_sparse_row_graph(edges_are_sorted_global_t, InputIterator edge_begin, InputIterator edge_end, EdgePropertyIterator ep_iter, const GlobalToLocal& global_to_local, const SourcePred& source_pred, vertices_size_type numverts, const GraphProperty& prop = GraphProperty()) : m_property(prop) { m_forward.assign_from_sorted_edges(edge_begin, edge_end, ep_iter, global_to_local, source_pred, numverts, 0); inherited_vertex_properties::resize(numverts); } // From number of vertices and mutable vectors of sources and targets; // vectors are returned with unspecified contents but are guaranteed not to // share storage with the constructed graph. compressed_sparse_row_graph(construct_inplace_from_sources_and_targets_t, std::vector<vertex_descriptor>& sources, std::vector<vertex_descriptor>& targets, vertices_size_type numverts, const GraphProperty& prop = GraphProperty()) : inherited_vertex_properties(numverts), m_property(prop) { m_forward.assign_sources_and_targets_global(sources, targets, numverts, boost::typed_identity_property_map<vertices_size_type>()); } // From number of vertices and mutable vectors of sources and targets, // expressed with global vertex indices; vectors are returned with // unspecified contents but are guaranteed not to share storage with the // constructed graph. This constructor should only be used by the // distributed CSR graph. template <typename GlobalToLocal> compressed_sparse_row_graph(construct_inplace_from_sources_and_targets_global_t, std::vector<vertex_descriptor>& sources, std::vector<vertex_descriptor>& targets, vertices_size_type numlocalverts, GlobalToLocal global_to_local, const GraphProperty& prop = GraphProperty()) : inherited_vertex_properties(numlocalverts), m_property(prop) { m_forward.assign_sources_and_targets_global(sources, targets, numlocalverts, global_to_local); } // From number of vertices and mutable vectors of sources, targets, and edge // properties; vectors are returned with unspecified contents but are // guaranteed not to share storage with the constructed graph. compressed_sparse_row_graph(construct_inplace_from_sources_and_targets_t, std::vector<vertex_descriptor>& sources, std::vector<vertex_descriptor>& targets, std::vector<typename forward_type::inherited_edge_properties::edge_bundled>& edge_props, vertices_size_type numverts, const GraphProperty& prop = GraphProperty()) : inherited_vertex_properties(numverts), m_property(prop) { m_forward.assign_sources_and_targets_global(sources, targets, edge_props, numverts, boost::typed_identity_property_map<vertices_size_type>()); } // From number of vertices and mutable vectors of sources and targets and // edge properties, expressed with global vertex indices; vectors are // returned with unspecified contents but are guaranteed not to share // storage with the constructed graph. This constructor should only be used // by the distributed CSR graph. template <typename GlobalToLocal> compressed_sparse_row_graph(construct_inplace_from_sources_and_targets_global_t, std::vector<vertex_descriptor>& sources, std::vector<vertex_descriptor>& targets, std::vector<typename forward_type::inherited_edge_properties::edge_bundled>& edge_props, vertices_size_type numlocalverts, GlobalToLocal global_to_local, const GraphProperty& prop = GraphProperty()) : inherited_vertex_properties(numlocalverts), m_property(prop) { m_forward.assign_sources_and_targets_global(sources, targets, edge_props, numlocalverts, global_to_local); } // From number of vertices and single-pass range of unsorted edges. Data is // cached in coordinate form before creating the actual graph. template<typename InputIterator> compressed_sparse_row_graph(edges_are_unsorted_t, InputIterator edge_begin, InputIterator edge_end, vertices_size_type numverts, const GraphProperty& prop = GraphProperty()) : inherited_vertex_properties(numverts), m_property(prop) { std::vector<vertex_descriptor> sources, targets; boost::graph::detail::split_into_separate_coords (edge_begin, edge_end, sources, targets); m_forward.assign_sources_and_targets_global(sources, targets, numverts, boost::typed_identity_property_map<vertices_size_type>()); } // From number of vertices and single-pass range of unsorted edges and // single-pass range of edge properties. Data is cached in coordinate form // before creating the actual graph. template<typename InputIterator, typename EdgePropertyIterator> compressed_sparse_row_graph(edges_are_unsorted_t, InputIterator edge_begin, InputIterator edge_end, EdgePropertyIterator ep_iter, vertices_size_type numverts, const GraphProperty& prop = GraphProperty()) : inherited_vertex_properties(numverts), m_property(prop) { std::vector<vertex_descriptor> sources, targets; boost::graph::detail::split_into_separate_coords (edge_begin, edge_end, sources, targets); size_t numedges = sources.size(); std::vector<typename forward_type::inherited_edge_properties::edge_bundled> edge_props(numedges); for (size_t i = 0; i < numedges; ++i) { edge_props[i] = *ep_iter++; } m_forward.assign_sources_and_targets_global(sources, targets, edge_props, numverts, boost::typed_identity_property_map<vertices_size_type>()); } // From number of vertices and single-pass range of unsorted edges. Data is // cached in coordinate form before creating the actual graph. Edges are // filtered and transformed for use in a distributed graph. template<typename InputIterator, typename GlobalToLocal, typename SourcePred> compressed_sparse_row_graph(edges_are_unsorted_global_t, InputIterator edge_begin, InputIterator edge_end, vertices_size_type numlocalverts, GlobalToLocal global_to_local, const SourcePred& source_pred, const GraphProperty& prop = GraphProperty()) : inherited_vertex_properties(numlocalverts), m_property(prop) { std::vector<vertex_descriptor> sources, targets; boost::graph::detail::split_into_separate_coords_filtered (edge_begin, edge_end, sources, targets, source_pred); m_forward.assign_sources_and_targets_global(sources, targets, numlocalverts, global_to_local); } // From number of vertices and single-pass range of unsorted edges and // single-pass range of edge properties. Data is cached in coordinate form // before creating the actual graph. Edges are filtered and transformed for // use in a distributed graph. template<typename InputIterator, typename EdgePropertyIterator, typename GlobalToLocal, typename SourcePred> compressed_sparse_row_graph(edges_are_unsorted_global_t, InputIterator edge_begin, InputIterator edge_end, EdgePropertyIterator ep_iter, vertices_size_type numlocalverts, GlobalToLocal global_to_local, const SourcePred& source_pred, const GraphProperty& prop = GraphProperty()) : inherited_vertex_properties(numlocalverts), m_property(prop) { std::vector<vertex_descriptor> sources, targets; std::vector<edge_bundled> edge_props; boost::graph::detail::split_into_separate_coords_filtered (edge_begin, edge_end, ep_iter, sources, targets, edge_props, source_pred); m_forward.assign_sources_and_targets_global(sources, targets, edge_props, numlocalverts, global_to_local); } // Requires IncidenceGraph and a vertex index map template<typename Graph, typename VertexIndexMap> compressed_sparse_row_graph(const Graph& g, const VertexIndexMap& vi, vertices_size_type numverts, edges_size_type numedges) : m_property() { assign(g, vi, numverts, numedges); inherited_vertex_properties::resize(numverts); } // Requires VertexListGraph and EdgeListGraph template<typename Graph, typename VertexIndexMap> compressed_sparse_row_graph(const Graph& g, const VertexIndexMap& vi) : m_property() { typename graph_traits<Graph>::edges_size_type numedges = num_edges(g); if (is_same<typename graph_traits<Graph>::directed_category, undirectedS>::value) { numedges *= 2; // Double each edge (actual doubling done by out_edges function) } vertices_size_type numverts = num_vertices(g); assign(g, vi, numverts, numedges); inherited_vertex_properties::resize(numverts); } // Requires vertex index map plus requirements of previous constructor template<typename Graph> explicit compressed_sparse_row_graph(const Graph& g) : m_property() { typename graph_traits<Graph>::edges_size_type numedges = num_edges(g); if (is_same<typename graph_traits<Graph>::directed_category, undirectedS>::value) { numedges *= 2; // Double each edge (actual doubling done by out_edges function) } assign(g, get(vertex_index, g), num_vertices(g), numedges); } // From any graph (slow and uses a lot of memory) // Requires IncidenceGraph and a vertex index map // Internal helper function // Note that numedges must be doubled for undirected source graphs template<typename Graph, typename VertexIndexMap> void assign(const Graph& g, const VertexIndexMap& vi, vertices_size_type numverts, edges_size_type numedges) { m_forward.assign(g, vi, numverts, numedges); inherited_vertex_properties::resize(numverts); } // Requires the above, plus VertexListGraph and EdgeListGraph template<typename Graph, typename VertexIndexMap> void assign(const Graph& g, const VertexIndexMap& vi) { typename graph_traits<Graph>::edges_size_type numedges = num_edges(g); if (is_same<typename graph_traits<Graph>::directed_category, undirectedS>::value) { numedges *= 2; // Double each edge (actual doubling done by out_edges function) } vertices_size_type numverts = num_vertices(g); m_forward.assign(g, vi, numverts, numedges); inherited_vertex_properties::resize(numverts); } // Requires the above, plus a vertex_index map. template<typename Graph> void assign(const Graph& g) { typename graph_traits<Graph>::edges_size_type numedges = num_edges(g); if (is_same<typename graph_traits<Graph>::directed_category, undirectedS>::value) { numedges *= 2; // Double each edge (actual doubling done by out_edges function) } vertices_size_type numverts = num_vertices(g); m_forward.assign(g, get(vertex_index, g), numverts, numedges); inherited_vertex_properties::resize(numverts); } // Add edges from a sorted (smallest sources first) range of pairs and edge // properties template <typename BidirectionalIteratorOrig, typename EPIterOrig, typename GlobalToLocal> void add_edges_sorted_internal( BidirectionalIteratorOrig first_sorted, BidirectionalIteratorOrig last_sorted, EPIterOrig ep_iter_sorted, const GlobalToLocal& global_to_local) { m_forward.add_edges_sorted_internal(first_sorted, last_sorted, ep_iter_sorted, global_to_local); } template <typename BidirectionalIteratorOrig, typename EPIterOrig> void add_edges_sorted_internal( BidirectionalIteratorOrig first_sorted, BidirectionalIteratorOrig last_sorted, EPIterOrig ep_iter_sorted) { m_forward.add_edges_sorted_internal(first_sorted, last_sorted, ep_iter_sorted, typed_identity_property_map<vertices_size_type>()); } // Add edges from a sorted (smallest sources first) range of pairs template <typename BidirectionalIteratorOrig> void add_edges_sorted_internal( BidirectionalIteratorOrig first_sorted, BidirectionalIteratorOrig last_sorted) { m_forward.add_edges_sorted_internal(first_sorted, last_sorted, detail::default_construct_iterator<edge_bundled>()); } template <typename BidirectionalIteratorOrig, typename GlobalToLocal> void add_edges_sorted_internal_global( BidirectionalIteratorOrig first_sorted, BidirectionalIteratorOrig last_sorted, const GlobalToLocal& global_to_local) { m_forward.add_edges_sorted_internal(first_sorted, last_sorted, detail::default_construct_iterator<edge_bundled>(), global_to_local); } template <typename BidirectionalIteratorOrig, typename EPIterOrig, typename GlobalToLocal> void add_edges_sorted_internal_global( BidirectionalIteratorOrig first_sorted, BidirectionalIteratorOrig last_sorted, EPIterOrig ep_iter_sorted, const GlobalToLocal& global_to_local) { m_forward.add_edges_sorted_internal(first_sorted, last_sorted, ep_iter_sorted, global_to_local); } // Add edges from a range of (source, target) pairs that are unsorted template <typename InputIterator, typename GlobalToLocal> inline void add_edges_internal(InputIterator first, InputIterator last, const GlobalToLocal& global_to_local) { typedef compressed_sparse_row_graph Graph; typedef typename boost::graph_traits<Graph>::vertex_descriptor vertex_t; typedef typename boost::graph_traits<Graph>::vertices_size_type vertex_num; typedef typename boost::graph_traits<Graph>::edges_size_type edge_num; typedef std::vector<std::pair<vertex_t, vertex_t> > edge_vector_t; edge_vector_t new_edges(first, last); if (new_edges.empty()) return; std::sort(new_edges.begin(), new_edges.end()); this->add_edges_sorted_internal_global(new_edges.begin(), new_edges.end(), global_to_local); } template <typename InputIterator> inline void add_edges_internal(InputIterator first, InputIterator last) { this->add_edges_internal(first, last, typed_identity_property_map<vertices_size_type>()); } // Add edges from a range of (source, target) pairs and edge properties that // are unsorted template <typename InputIterator, typename EPIterator, typename GlobalToLocal> inline void add_edges_internal(InputIterator first, InputIterator last, EPIterator ep_iter, EPIterator ep_iter_end, const GlobalToLocal& global_to_local) { typedef compressed_sparse_row_graph Graph; typedef typename boost::graph_traits<Graph>::vertex_descriptor vertex_t; typedef typename boost::graph_traits<Graph>::vertices_size_type vertex_num; typedef typename boost::graph_traits<Graph>::edges_size_type edge_num; typedef std::pair<vertex_t, vertex_t> vertex_pair; typedef std::vector< boost::tuple<vertex_pair, edge_bundled> > edge_vector_t; edge_vector_t new_edges (boost::make_zip_iterator(boost::make_tuple(first, ep_iter)), boost::make_zip_iterator(boost::make_tuple(last, ep_iter_end))); if (new_edges.empty()) return; std::sort(new_edges.begin(), new_edges.end(), boost::detail::compare_first< std::less<vertex_pair> >()); m_forward.add_edges_sorted_internal (boost::make_transform_iterator( new_edges.begin(), boost::detail::my_tuple_get_class<0, vertex_pair>()), boost::make_transform_iterator( new_edges.end(), boost::detail::my_tuple_get_class<0, vertex_pair>()), boost::make_transform_iterator( new_edges.begin(), boost::detail::my_tuple_get_class <1, edge_bundled>()), global_to_local); } // Add edges from a range of (source, target) pairs and edge properties that // are unsorted template <typename InputIterator, typename EPIterator> inline void add_edges_internal(InputIterator first, InputIterator last, EPIterator ep_iter, EPIterator ep_iter_end) { this->add_edges_internal(first, last, ep_iter, ep_iter_end, typed_identity_property_map<vertices_size_type>()); } using inherited_vertex_properties::operator[]; // Directly access a edge or edge bundle edge_push_back_type& operator[](const edge_descriptor& v) { return m_forward.m_edge_properties[get(edge_index, *this, v)]; } const edge_push_back_type& operator[](const edge_descriptor& v) const { return m_forward.m_edge_properties[get(edge_index, *this, v)]; } // Directly access a graph bundle graph_bundled& operator[](graph_bundle_t) { return get_property(*this); } const graph_bundled& operator[](graph_bundle_t) const { return get_property(*this); } // private: non-portable, requires friend templates inherited_vertex_properties& vertex_properties() {return *this;} const inherited_vertex_properties& vertex_properties() const {return *this;} typename forward_type::inherited_edge_properties& edge_properties() { return m_forward; } const typename forward_type::inherited_edge_properties& edge_properties() const { return m_forward; } forward_type m_forward; GraphProperty m_property; }; template<typename VertexProperty, typename EdgeProperty, typename GraphProperty, typename Vertex, typename EdgeIndex> class compressed_sparse_row_graph<bidirectionalS, VertexProperty, EdgeProperty, GraphProperty, Vertex, EdgeIndex> : public detail::indexed_vertex_properties<BOOST_BIDIR_CSR_GRAPH_TYPE, VertexProperty, Vertex, typed_identity_property_map<Vertex> > { public: typedef detail::indexed_vertex_properties<compressed_sparse_row_graph, VertexProperty, Vertex, typed_identity_property_map<Vertex> > inherited_vertex_properties; public: // For Property Graph typedef GraphProperty graph_property_type; typedef typename lookup_one_property<GraphProperty, graph_bundle_t>::type graph_bundled; // typedef GraphProperty graph_property_type; typedef detail::compressed_sparse_row_structure<EdgeProperty, Vertex, EdgeIndex> forward_type; typedef EdgeIndex /* typename boost::mpl::if_c<boost::is_same<EdgeProperty, boost::no_property>, boost::no_property, EdgeIndex> */ backward_edge_property; typedef detail::compressed_sparse_row_structure<backward_edge_property, Vertex, EdgeIndex> backward_type; public: // Concept requirements: // For Graph typedef Vertex vertex_descriptor; typedef detail::csr_edge_descriptor<Vertex, EdgeIndex> edge_descriptor; typedef bidirectional_tag directed_category; typedef allow_parallel_edge_tag edge_parallel_category; class traversal_category: public bidirectional_graph_tag, public adjacency_graph_tag, public vertex_list_graph_tag, public edge_list_graph_tag {}; static vertex_descriptor null_vertex() { return vertex_descriptor(-1); } // For VertexListGraph typedef counting_iterator<Vertex> vertex_iterator; typedef Vertex vertices_size_type; // For EdgeListGraph typedef EdgeIndex edges_size_type; // For IncidenceGraph typedef detail::csr_out_edge_iterator<compressed_sparse_row_graph> out_edge_iterator; typedef EdgeIndex degree_size_type; // For AdjacencyGraph typedef typename std::vector<Vertex>::const_iterator adjacency_iterator; // For EdgeListGraph typedef detail::csr_edge_iterator<compressed_sparse_row_graph> edge_iterator; // For BidirectionalGraph (not implemented) typedef detail::csr_in_edge_iterator<compressed_sparse_row_graph> in_edge_iterator; // For internal use typedef csr_graph_tag graph_tag; typedef typename forward_type::inherited_edge_properties::edge_bundled edge_bundled; typedef typename forward_type::inherited_edge_properties::edge_push_back_type edge_push_back_type; typedef typename forward_type::inherited_edge_properties::edge_property_type edge_property_type; // Constructors // Default constructor: an empty graph. compressed_sparse_row_graph(): m_property() {} // With numverts vertices compressed_sparse_row_graph(vertices_size_type numverts) : inherited_vertex_properties(numverts), m_forward(numverts), m_backward(numverts) {} private: void set_up_backward_property_links() { std::pair<edge_iterator, edge_iterator> e = edges(*this); m_backward.assign_unsorted_multi_pass_edges (detail::transpose_edges( detail::make_edge_to_index_pair_iter (*this, get(vertex_index, *this), e.first)), detail::transpose_edges( detail::make_edge_to_index_pair_iter (*this, get(vertex_index, *this), e.second)), boost::counting_iterator<EdgeIndex>(0), m_forward.m_rowstart.size() - 1, typed_identity_property_map<Vertex>(), keep_all()); } public: // From number of vertices and unsorted list of edges template <typename MultiPassInputIterator> compressed_sparse_row_graph(edges_are_unsorted_multi_pass_t, MultiPassInputIterator edge_begin, MultiPassInputIterator edge_end, vertices_size_type numverts, const GraphProperty& prop = GraphProperty()) : inherited_vertex_properties(numverts), m_property(prop) { m_forward.assign_unsorted_multi_pass_edges(edge_begin, edge_end, numverts, typed_identity_property_map<Vertex>(), keep_all()); set_up_backward_property_links(); } // From number of vertices and unsorted list of edges, plus edge properties template <typename MultiPassInputIterator, typename EdgePropertyIterator> compressed_sparse_row_graph(edges_are_unsorted_multi_pass_t, MultiPassInputIterator edge_begin, MultiPassInputIterator edge_end, EdgePropertyIterator ep_iter, vertices_size_type numverts, const GraphProperty& prop = GraphProperty()) : inherited_vertex_properties(numverts), m_forward(), m_property(prop) { m_forward.assign_unsorted_multi_pass_edges(edge_begin, edge_end, ep_iter, numverts, typed_identity_property_map<Vertex>(), keep_all()); set_up_backward_property_links(); } // From number of vertices and unsorted list of edges, with filter and // global-to-local map template <typename MultiPassInputIterator, typename GlobalToLocal, typename SourcePred> compressed_sparse_row_graph(edges_are_unsorted_multi_pass_global_t, MultiPassInputIterator edge_begin, MultiPassInputIterator edge_end, vertices_size_type numlocalverts, const GlobalToLocal& global_to_local, const SourcePred& source_pred, const GraphProperty& prop = GraphProperty()) : inherited_vertex_properties(numlocalverts), m_forward(), m_property(prop) { m_forward.assign_unsorted_multi_pass_edges(edge_begin, edge_end, numlocalverts, global_to_local, source_pred); set_up_backward_property_links(); } // From number of vertices and unsorted list of edges, plus edge properties, // with filter and global-to-local map template <typename MultiPassInputIterator, typename EdgePropertyIterator, typename GlobalToLocal, typename SourcePred> compressed_sparse_row_graph(edges_are_unsorted_multi_pass_global_t, MultiPassInputIterator edge_begin, MultiPassInputIterator edge_end, EdgePropertyIterator ep_iter, vertices_size_type numlocalverts, const GlobalToLocal& global_to_local, const SourcePred& source_pred, const GraphProperty& prop = GraphProperty()) : inherited_vertex_properties(numlocalverts), m_forward(), m_property(prop) { m_forward.assign_unsorted_multi_pass_edges(edge_begin, edge_end, ep_iter, numlocalverts, global_to_local, source_pred); set_up_backward_property_links(); } // Requires IncidenceGraph and a vertex index map template<typename Graph, typename VertexIndexMap> compressed_sparse_row_graph(const Graph& g, const VertexIndexMap& vi, vertices_size_type numverts, edges_size_type numedges) : m_property() { assign(g, vi, numverts, numedges); inherited_vertex_properties::resize(numverts); } // Requires VertexListGraph and EdgeListGraph template<typename Graph, typename VertexIndexMap> compressed_sparse_row_graph(const Graph& g, const VertexIndexMap& vi) : m_property() { typename graph_traits<Graph>::edges_size_type numedges = num_edges(g); if (is_same<typename graph_traits<Graph>::directed_category, undirectedS>::value) { numedges *= 2; // Double each edge (actual doubling done by out_edges function) } vertices_size_type numverts = num_vertices(g); assign(g, vi, numverts, numedges); inherited_vertex_properties::resize(numverts); } // Requires vertex index map plus requirements of previous constructor template<typename Graph> explicit compressed_sparse_row_graph(const Graph& g) : m_property() { typename graph_traits<Graph>::edges_size_type numedges = num_edges(g); if (is_same<typename graph_traits<Graph>::directed_category, undirectedS>::value) { numedges *= 2; // Double each edge (actual doubling done by out_edges function) } assign(g, get(vertex_index, g), num_vertices(g), numedges); } // From any graph (slow and uses a lot of memory) // Requires IncidenceGraph and a vertex index map // Internal helper function // Note that numedges must be doubled for undirected source graphs template<typename Graph, typename VertexIndexMap> void assign(const Graph& g, const VertexIndexMap& vi, vertices_size_type numverts, edges_size_type numedges) { m_forward.assign(g, vi, numverts, numedges); inherited_vertex_properties::resize(numverts); set_up_backward_property_links(); } // Requires the above, plus VertexListGraph and EdgeListGraph template<typename Graph, typename VertexIndexMap> void assign(const Graph& g, const VertexIndexMap& vi) { typename graph_traits<Graph>::edges_size_type numedges = num_edges(g); if (is_same<typename graph_traits<Graph>::directed_category, undirectedS>::value) { numedges *= 2; // Double each edge (actual doubling done by out_edges function) } vertices_size_type numverts = num_vertices(g); m_forward.assign(g, vi, numverts, numedges); inherited_vertex_properties::resize(numverts); set_up_backward_property_links(); } // Requires the above, plus a vertex_index map. template<typename Graph> void assign(const Graph& g) { typename graph_traits<Graph>::edges_size_type numedges = num_edges(g); if (is_same<typename graph_traits<Graph>::directed_category, undirectedS>::value) { numedges *= 2; // Double each edge (actual doubling done by out_edges function) } vertices_size_type numverts = num_vertices(g); m_forward.assign(g, get(vertex_index, g), numverts, numedges); inherited_vertex_properties::resize(numverts); set_up_backward_property_links(); } using inherited_vertex_properties::operator[]; // Directly access a edge or edge bundle edge_push_back_type& operator[](const edge_descriptor& v) { return m_forward.m_edge_properties[get(edge_index, *this, v)]; } const edge_push_back_type& operator[](const edge_descriptor& v) const { return m_forward.m_edge_properties[get(edge_index, *this, v)]; } // private: non-portable, requires friend templates inherited_vertex_properties& vertex_properties() {return *this;} const inherited_vertex_properties& vertex_properties() const {return *this;} typename forward_type::inherited_edge_properties& edge_properties() { return m_forward; } const typename forward_type::inherited_edge_properties& edge_properties() const { return m_forward; } forward_type m_forward; backward_type m_backward; GraphProperty m_property; }; // Construction functions template<BOOST_CSR_GRAPH_TEMPLATE_PARMS> inline Vertex add_vertex(BOOST_CSR_GRAPH_TYPE& g) { add_vertex(g, typename BOOST_CSR_GRAPH_TYPE::vertex_bundled()); } template<BOOST_DIR_CSR_GRAPH_TEMPLATE_PARMS> inline Vertex add_vertex(BOOST_DIR_CSR_GRAPH_TYPE& g, typename BOOST_DIR_CSR_GRAPH_TYPE::vertex_bundled const& p) { Vertex old_num_verts_plus_one = g.m_forward.m_rowstart.size(); g.m_forward.m_rowstart.push_back(g.m_forward.m_rowstart.back()); g.vertex_properties().push_back(p); return old_num_verts_plus_one - 1; } template<BOOST_BIDIR_CSR_GRAPH_TEMPLATE_PARMS> inline Vertex add_vertex(BOOST_BIDIR_CSR_GRAPH_TYPE& g, typename BOOST_BIDIR_CSR_GRAPH_TYPE::vertex_bundled const& p) { Vertex old_num_verts_plus_one = g.m_forward.m_rowstart.size(); g.m_forward.m_rowstart.push_back(g.m_forward.m_rowstart.back()); g.m_backward.m_rowstart.push_back(g.m_backward.m_rowstart.back()); g.vertex_properties().push_back(p); return old_num_verts_plus_one - 1; } template<BOOST_DIR_CSR_GRAPH_TEMPLATE_PARMS> inline Vertex add_vertices(typename BOOST_DIR_CSR_GRAPH_TYPE::vertices_size_type count, BOOST_DIR_CSR_GRAPH_TYPE& g) { Vertex old_num_verts_plus_one = g.m_forward.m_rowstart.size(); EdgeIndex numedges = g.m_forward.m_rowstart.back(); g.m_forward.m_rowstart.resize(old_num_verts_plus_one + count, numedges); g.vertex_properties().resize(num_vertices(g)); return old_num_verts_plus_one - 1; } // Add edges from a sorted (smallest sources first) range of pairs and edge // properties template <BOOST_DIR_CSR_GRAPH_TEMPLATE_PARMS, typename BidirectionalIteratorOrig, typename EPIterOrig> void add_edges_sorted( BidirectionalIteratorOrig first_sorted, BidirectionalIteratorOrig last_sorted, EPIterOrig ep_iter_sorted, BOOST_DIR_CSR_GRAPH_TYPE& g) { g.add_edges_sorted_internal(first_sorted, last_sorted, ep_iter_sorted); } // Add edges from a sorted (smallest sources first) range of pairs template <BOOST_DIR_CSR_GRAPH_TEMPLATE_PARMS, typename BidirectionalIteratorOrig> void add_edges_sorted( BidirectionalIteratorOrig first_sorted, BidirectionalIteratorOrig last_sorted, BOOST_DIR_CSR_GRAPH_TYPE& g) { g.add_edges_sorted_internal(first_sorted, last_sorted); } template <BOOST_DIR_CSR_GRAPH_TEMPLATE_PARMS, typename BidirectionalIteratorOrig, typename EPIterOrig, typename GlobalToLocal> void add_edges_sorted_global( BidirectionalIteratorOrig first_sorted, BidirectionalIteratorOrig last_sorted, EPIterOrig ep_iter_sorted, const GlobalToLocal& global_to_local, BOOST_DIR_CSR_GRAPH_TYPE& g) { g.add_edges_sorted_internal_global(first_sorted, last_sorted, ep_iter_sorted, global_to_local); } // Add edges from a sorted (smallest sources first) range of pairs template <BOOST_DIR_CSR_GRAPH_TEMPLATE_PARMS, typename BidirectionalIteratorOrig, typename GlobalToLocal> void add_edges_sorted_global( BidirectionalIteratorOrig first_sorted, BidirectionalIteratorOrig last_sorted, const GlobalToLocal& global_to_local, BOOST_DIR_CSR_GRAPH_TYPE& g) { g.add_edges_sorted_internal_global(first_sorted, last_sorted, global_to_local); } // Add edges from a range of (source, target) pairs that are unsorted template <BOOST_DIR_CSR_GRAPH_TEMPLATE_PARMS, typename InputIterator, typename GlobalToLocal> inline void add_edges_global(InputIterator first, InputIterator last, const GlobalToLocal& global_to_local, BOOST_DIR_CSR_GRAPH_TYPE& g) { g.add_edges_internal(first, last, global_to_local); } // Add edges from a range of (source, target) pairs that are unsorted template <BOOST_DIR_CSR_GRAPH_TEMPLATE_PARMS, typename InputIterator> inline void add_edges(InputIterator first, InputIterator last, BOOST_DIR_CSR_GRAPH_TYPE& g) { g.add_edges_internal(first, last); } // Add edges from a range of (source, target) pairs and edge properties that // are unsorted template <BOOST_DIR_CSR_GRAPH_TEMPLATE_PARMS, typename InputIterator, typename EPIterator> inline void add_edges(InputIterator first, InputIterator last, EPIterator ep_iter, EPIterator ep_iter_end, BOOST_DIR_CSR_GRAPH_TYPE& g) { g.add_edges_internal(first, last, ep_iter, ep_iter_end); } template <BOOST_DIR_CSR_GRAPH_TEMPLATE_PARMS, typename InputIterator, typename EPIterator, typename GlobalToLocal> inline void add_edges_global(InputIterator first, InputIterator last, EPIterator ep_iter, EPIterator ep_iter_end, const GlobalToLocal& global_to_local, BOOST_DIR_CSR_GRAPH_TYPE& g) { g.add_edges_internal(first, last, ep_iter, ep_iter_end, global_to_local); } // From VertexListGraph template<BOOST_CSR_GRAPH_TEMPLATE_PARMS> inline Vertex num_vertices(const BOOST_CSR_GRAPH_TYPE& g) { return g.m_forward.m_rowstart.size() - 1; } template<BOOST_CSR_GRAPH_TEMPLATE_PARMS> std::pair<counting_iterator<Vertex>, counting_iterator<Vertex> > inline vertices(const BOOST_CSR_GRAPH_TYPE& g) { return std::make_pair(counting_iterator<Vertex>(0), counting_iterator<Vertex>(num_vertices(g))); } // From IncidenceGraph template<BOOST_CSR_GRAPH_TEMPLATE_PARMS> inline Vertex source(typename BOOST_CSR_GRAPH_TYPE::edge_descriptor e, const BOOST_CSR_GRAPH_TYPE&) { return e.src; } template<BOOST_CSR_GRAPH_TEMPLATE_PARMS> inline Vertex target(typename BOOST_CSR_GRAPH_TYPE::edge_descriptor e, const BOOST_CSR_GRAPH_TYPE& g) { return g.m_forward.m_column[e.idx]; } template<BOOST_CSR_GRAPH_TEMPLATE_PARMS> inline std::pair<typename BOOST_CSR_GRAPH_TYPE::out_edge_iterator, typename BOOST_CSR_GRAPH_TYPE::out_edge_iterator> out_edges(Vertex v, const BOOST_CSR_GRAPH_TYPE& g) { typedef typename BOOST_CSR_GRAPH_TYPE::edge_descriptor ed; typedef typename BOOST_CSR_GRAPH_TYPE::out_edge_iterator it; EdgeIndex v_row_start = g.m_forward.m_rowstart[v]; EdgeIndex next_row_start = g.m_forward.m_rowstart[v + 1]; return std::make_pair(it(ed(v, v_row_start)), it(ed(v, next_row_start))); } template<BOOST_CSR_GRAPH_TEMPLATE_PARMS> inline EdgeIndex out_degree(Vertex v, const BOOST_CSR_GRAPH_TYPE& g) { EdgeIndex v_row_start = g.m_forward.m_rowstart[v]; EdgeIndex next_row_start = g.m_forward.m_rowstart[v + 1]; return next_row_start - v_row_start; } template<BOOST_BIDIR_CSR_GRAPH_TEMPLATE_PARMS> inline std::pair<typename BOOST_BIDIR_CSR_GRAPH_TYPE::in_edge_iterator, typename BOOST_BIDIR_CSR_GRAPH_TYPE::in_edge_iterator> in_edges(Vertex v, const BOOST_BIDIR_CSR_GRAPH_TYPE& g) { typedef typename BOOST_BIDIR_CSR_GRAPH_TYPE::edge_descriptor ed; typedef typename BOOST_BIDIR_CSR_GRAPH_TYPE::in_edge_iterator it; EdgeIndex v_row_start = g.m_backward.m_rowstart[v]; EdgeIndex next_row_start = g.m_backward.m_rowstart[v + 1]; return std::make_pair(it(g, v_row_start), it(g, next_row_start)); } template<BOOST_BIDIR_CSR_GRAPH_TEMPLATE_PARMS> inline EdgeIndex in_degree(Vertex v, const BOOST_BIDIR_CSR_GRAPH_TYPE& g) { EdgeIndex v_row_start = g.m_backward.m_rowstart[v]; EdgeIndex next_row_start = g.m_backward.m_rowstart[v + 1]; return next_row_start - v_row_start; } // From AdjacencyGraph template<BOOST_CSR_GRAPH_TEMPLATE_PARMS> inline std::pair<typename BOOST_CSR_GRAPH_TYPE::adjacency_iterator, typename BOOST_CSR_GRAPH_TYPE::adjacency_iterator> adjacent_vertices(Vertex v, const BOOST_CSR_GRAPH_TYPE& g) { EdgeIndex v_row_start = g.m_forward.m_rowstart[v]; EdgeIndex next_row_start = g.m_forward.m_rowstart[v + 1]; return std::make_pair(g.m_forward.m_column.begin() + v_row_start, g.m_forward.m_column.begin() + next_row_start); } // Extra, common functions template<BOOST_CSR_GRAPH_TEMPLATE_PARMS> inline typename graph_traits<BOOST_CSR_GRAPH_TYPE>::vertex_descriptor vertex(typename graph_traits<BOOST_CSR_GRAPH_TYPE>::vertex_descriptor i, const BOOST_CSR_GRAPH_TYPE&) { return i; } // edge() can be provided in linear time for the new interface template<BOOST_CSR_GRAPH_TEMPLATE_PARMS> inline std::pair<typename BOOST_CSR_GRAPH_TYPE::edge_descriptor, bool> edge(Vertex i, Vertex j, const BOOST_CSR_GRAPH_TYPE& g) { typedef typename BOOST_CSR_GRAPH_TYPE::out_edge_iterator out_edge_iter; std::pair<out_edge_iter, out_edge_iter> range = out_edges(i, g); for (; range.first != range.second; ++range.first) { if (target(*range.first, g) == j) return std::make_pair(*range.first, true); } return std::make_pair(typename BOOST_CSR_GRAPH_TYPE::edge_descriptor(), false); } // Find an edge given its index in the graph template<BOOST_CSR_GRAPH_TEMPLATE_PARMS> inline typename BOOST_CSR_GRAPH_TYPE::edge_descriptor edge_from_index(EdgeIndex idx, const BOOST_CSR_GRAPH_TYPE& g) { typedef typename std::vector<EdgeIndex>::const_iterator row_start_iter; BOOST_ASSERT (idx < num_edges(g)); row_start_iter src_plus_1 = std::upper_bound(g.m_forward.m_rowstart.begin(), g.m_forward.m_rowstart.end(), idx); // Get last source whose rowstart is at most idx // upper_bound returns this position plus 1 Vertex src = (src_plus_1 - g.m_forward.m_rowstart.begin()) - 1; return typename BOOST_CSR_GRAPH_TYPE::edge_descriptor(src, idx); } template<BOOST_CSR_GRAPH_TEMPLATE_PARMS> inline EdgeIndex num_edges(const BOOST_CSR_GRAPH_TYPE& g) { return g.m_forward.m_column.size(); } template<BOOST_CSR_GRAPH_TEMPLATE_PARMS> std::pair<typename BOOST_CSR_GRAPH_TYPE::edge_iterator, typename BOOST_CSR_GRAPH_TYPE::edge_iterator> edges(const BOOST_CSR_GRAPH_TYPE& g) { typedef typename BOOST_CSR_GRAPH_TYPE::edge_iterator ei; typedef typename BOOST_CSR_GRAPH_TYPE::edge_descriptor edgedesc; if (g.m_forward.m_rowstart.size() == 1 || g.m_forward.m_column.empty()) { return std::make_pair(ei(), ei()); } else { // Find the first vertex that has outgoing edges Vertex src = 0; while (g.m_forward.m_rowstart[src + 1] == 0) ++src; return std::make_pair(ei(g, edgedesc(src, 0), g.m_forward.m_rowstart[src + 1]), ei(g, edgedesc(num_vertices(g), g.m_forward.m_column.size()), 0)); } } // For Property Graph // Graph properties template<BOOST_CSR_GRAPH_TEMPLATE_PARMS, class Tag, class Value> inline void set_property(BOOST_CSR_GRAPH_TYPE& g, Tag tag, const Value& value) { get_property_value(g.m_property, tag) = value; } template<BOOST_CSR_GRAPH_TEMPLATE_PARMS, class Tag> inline typename graph_property<BOOST_CSR_GRAPH_TYPE, Tag>::type& get_property(BOOST_CSR_GRAPH_TYPE& g, Tag tag) { return get_property_value(g.m_property, tag); } template<BOOST_CSR_GRAPH_TEMPLATE_PARMS, class Tag> inline const typename graph_property<BOOST_CSR_GRAPH_TYPE, Tag>::type& get_property(const BOOST_CSR_GRAPH_TYPE& g, Tag tag) { return get_property_value(g.m_property, tag); } template <typename G, typename Tag, typename Kind> struct csr_property_map_helper {}; // Kind == void for invalid property tags, so we can use that to SFINAE out template <BOOST_CSR_GRAPH_TEMPLATE_PARMS, typename Tag> struct csr_property_map_helper<BOOST_CSR_GRAPH_TYPE, Tag, vertex_property_tag> { typedef vertex_all_t all_tag; typedef typename property_traits<typename property_map<BOOST_CSR_GRAPH_TYPE, vertex_all_t>::type>::key_type key_type; typedef VertexProperty plist_type; typedef typename property_map<BOOST_CSR_GRAPH_TYPE, vertex_all_t>::type all_type; typedef typename property_map<BOOST_CSR_GRAPH_TYPE, vertex_all_t>::const_type all_const_type; typedef transform_value_property_map<detail::lookup_one_property_f<plist_type, Tag>, all_type> type; typedef transform_value_property_map<detail::lookup_one_property_f<const plist_type, Tag>, all_const_type> const_type; }; template <BOOST_CSR_GRAPH_TEMPLATE_PARMS, typename Tag> struct csr_property_map_helper<BOOST_CSR_GRAPH_TYPE, Tag, edge_property_tag> { typedef edge_all_t all_tag; typedef typename property_traits<typename property_map<BOOST_CSR_GRAPH_TYPE, edge_all_t>::type>::key_type key_type; typedef EdgeProperty plist_type; typedef typename property_map<BOOST_CSR_GRAPH_TYPE, edge_all_t>::type all_type; typedef typename property_map<BOOST_CSR_GRAPH_TYPE, edge_all_t>::const_type all_const_type; typedef transform_value_property_map<detail::lookup_one_property_f<plist_type, Tag>, all_type> type; typedef transform_value_property_map<detail::lookup_one_property_f<const plist_type, Tag>, all_const_type> const_type; }; template <BOOST_CSR_GRAPH_TEMPLATE_PARMS, typename Tag> struct csr_property_map_helper<BOOST_CSR_GRAPH_TYPE, Tag, graph_property_tag> { typedef graph_all_t all_tag; typedef BOOST_CSR_GRAPH_TYPE* key_type; typedef GraphProperty plist_type; typedef typename property_map<BOOST_CSR_GRAPH_TYPE, graph_all_t>::type all_type; typedef typename property_map<BOOST_CSR_GRAPH_TYPE, graph_all_t>::const_type all_const_type; typedef transform_value_property_map<detail::lookup_one_property_f<plist_type, Tag>, all_type> type; typedef transform_value_property_map<detail::lookup_one_property_f<const plist_type, Tag>, all_const_type> const_type; }; template <BOOST_CSR_GRAPH_TEMPLATE_PARMS, typename Tag> struct property_map<BOOST_CSR_GRAPH_TYPE, Tag>: csr_property_map_helper< BOOST_CSR_GRAPH_TYPE, Tag, typename detail::property_kind_from_graph<BOOST_CSR_GRAPH_TYPE, Tag> ::type> {}; template <BOOST_CSR_GRAPH_TEMPLATE_PARMS, typename Tag> typename property_map<BOOST_CSR_GRAPH_TYPE, Tag>::type get(Tag tag, BOOST_CSR_GRAPH_TYPE& g) { return typename property_map<BOOST_CSR_GRAPH_TYPE, Tag>::type(tag, get(typename property_map<BOOST_CSR_GRAPH_TYPE, Tag>::all_tag(), g)); } template <BOOST_CSR_GRAPH_TEMPLATE_PARMS, typename Tag> typename property_map<BOOST_CSR_GRAPH_TYPE, Tag>::const_type get(Tag tag, const BOOST_CSR_GRAPH_TYPE& g) { return typename property_map<BOOST_CSR_GRAPH_TYPE, Tag>::const_type(tag, get(typename property_map<BOOST_CSR_GRAPH_TYPE, Tag>::all_tag(), g)); } template <BOOST_CSR_GRAPH_TEMPLATE_PARMS, typename Tag> typename property_traits<typename property_map<BOOST_CSR_GRAPH_TYPE, Tag>::type>::reference get(Tag tag, BOOST_CSR_GRAPH_TYPE& g, typename property_map<BOOST_CSR_GRAPH_TYPE, Tag>::key_type k) { typedef typename property_map<BOOST_CSR_GRAPH_TYPE, Tag>::all_tag all_tag; typedef typename property_map<BOOST_CSR_GRAPH_TYPE, all_tag>::type outer_pm; return lookup_one_property<typename property_traits<outer_pm>::value_type, Tag>::lookup(get(all_tag(), g, k), tag); } template <BOOST_CSR_GRAPH_TEMPLATE_PARMS, typename Tag> typename property_traits<typename property_map<BOOST_CSR_GRAPH_TYPE, Tag>::const_type>::reference get(Tag tag, const BOOST_CSR_GRAPH_TYPE& g, typename property_map<BOOST_CSR_GRAPH_TYPE, Tag>::key_type k) { typedef typename property_map<BOOST_CSR_GRAPH_TYPE, Tag>::all_tag all_tag; typedef typename property_map<BOOST_CSR_GRAPH_TYPE, all_tag>::const_type outer_pm; return lookup_one_property<const typename property_traits<outer_pm>::value_type, Tag>::lookup(get(all_tag(), g, k), tag); } template <BOOST_CSR_GRAPH_TEMPLATE_PARMS, typename Tag> void put(Tag tag, BOOST_CSR_GRAPH_TYPE& g, typename property_map<BOOST_CSR_GRAPH_TYPE, Tag>::key_type k, typename lookup_one_property<typename property_map<BOOST_CSR_GRAPH_TYPE, Tag>::plist_type, Tag>::type val) { typedef typename property_map<BOOST_CSR_GRAPH_TYPE, Tag>::all_tag all_tag; typedef typename property_map<BOOST_CSR_GRAPH_TYPE, all_tag>::type outer_pm; lookup_one_property<typename property_map<BOOST_CSR_GRAPH_TYPE, Tag>::plist_type, Tag>::lookup(get(all_tag(), g, k), tag) = val; } template<BOOST_CSR_GRAPH_TEMPLATE_PARMS> struct property_map<BOOST_CSR_GRAPH_TYPE, vertex_index_t> { typedef typed_identity_property_map<Vertex> type; typedef type const_type; }; template<BOOST_CSR_GRAPH_TEMPLATE_PARMS> struct property_map<BOOST_CSR_GRAPH_TYPE, edge_index_t> { typedef detail::csr_edge_index_map<Vertex, EdgeIndex> type; typedef type const_type; }; template<BOOST_CSR_GRAPH_TEMPLATE_PARMS> struct property_map<BOOST_CSR_GRAPH_TYPE, vertex_all_t> { typedef typename BOOST_CSR_GRAPH_TYPE::inherited_vertex_properties::vertex_map_type type; typedef typename BOOST_CSR_GRAPH_TYPE::inherited_vertex_properties::const_vertex_map_type const_type; }; template<BOOST_CSR_GRAPH_TEMPLATE_PARMS> struct property_map<BOOST_CSR_GRAPH_TYPE, edge_all_t> { typedef typename BOOST_CSR_GRAPH_TYPE::forward_type::inherited_edge_properties::edge_map_type type; typedef typename BOOST_CSR_GRAPH_TYPE::forward_type::inherited_edge_properties::const_edge_map_type const_type; }; template<BOOST_CSR_GRAPH_TEMPLATE_PARMS> struct property_map<BOOST_CSR_GRAPH_TYPE, graph_all_t> { typedef boost::ref_property_map<BOOST_CSR_GRAPH_TYPE*, typename BOOST_CSR_GRAPH_TYPE::graph_property_type> type; typedef boost::ref_property_map<BOOST_CSR_GRAPH_TYPE*, const typename BOOST_CSR_GRAPH_TYPE::graph_property_type> const_type; }; template<BOOST_CSR_GRAPH_TEMPLATE_PARMS> inline typed_identity_property_map<Vertex> get(vertex_index_t, const BOOST_CSR_GRAPH_TYPE&) { return typed_identity_property_map<Vertex>(); } template<BOOST_CSR_GRAPH_TEMPLATE_PARMS> inline Vertex get(vertex_index_t, const BOOST_CSR_GRAPH_TYPE&, Vertex v) { return v; } template<BOOST_CSR_GRAPH_TEMPLATE_PARMS> inline typed_identity_property_map<Vertex> get(vertex_index_t, BOOST_CSR_GRAPH_TYPE&) { return typed_identity_property_map<Vertex>(); } template<BOOST_CSR_GRAPH_TEMPLATE_PARMS> inline Vertex get(vertex_index_t, BOOST_CSR_GRAPH_TYPE&, Vertex v) { return v; } template<BOOST_CSR_GRAPH_TEMPLATE_PARMS> inline typename property_map<BOOST_CSR_GRAPH_TYPE, edge_index_t>::const_type get(edge_index_t, const BOOST_CSR_GRAPH_TYPE&) { typedef typename property_map<BOOST_CSR_GRAPH_TYPE, edge_index_t>::const_type result_type; return result_type(); } template<BOOST_CSR_GRAPH_TEMPLATE_PARMS> inline EdgeIndex get(edge_index_t, const BOOST_CSR_GRAPH_TYPE&, typename BOOST_CSR_GRAPH_TYPE::edge_descriptor e) { return e.idx; } template<BOOST_CSR_GRAPH_TEMPLATE_PARMS> inline typename property_map<BOOST_CSR_GRAPH_TYPE, edge_index_t>::const_type get(edge_index_t, BOOST_CSR_GRAPH_TYPE&) { typedef typename property_map<BOOST_CSR_GRAPH_TYPE, edge_index_t>::const_type result_type; return result_type(); } template<BOOST_CSR_GRAPH_TEMPLATE_PARMS> inline EdgeIndex get(edge_index_t, BOOST_CSR_GRAPH_TYPE&, typename BOOST_CSR_GRAPH_TYPE::edge_descriptor e) { return e.idx; } template<BOOST_CSR_GRAPH_TEMPLATE_PARMS> inline typename property_map<BOOST_CSR_GRAPH_TYPE, vertex_all_t>::type get(vertex_all_t, BOOST_CSR_GRAPH_TYPE& g) { return g.get_vertex_bundle(get(vertex_index, g)); } template<BOOST_CSR_GRAPH_TEMPLATE_PARMS> inline typename property_map<BOOST_CSR_GRAPH_TYPE, vertex_all_t>::const_type get(vertex_all_t, const BOOST_CSR_GRAPH_TYPE& g) { return g.get_vertex_bundle(get(vertex_index, g)); } template<BOOST_CSR_GRAPH_TEMPLATE_PARMS> inline VertexProperty& get(vertex_all_t, BOOST_CSR_GRAPH_TYPE& g, Vertex v) { return get(vertex_all, g)[v]; } template<BOOST_CSR_GRAPH_TEMPLATE_PARMS> inline const VertexProperty& get(vertex_all_t, const BOOST_CSR_GRAPH_TYPE& g, Vertex v) { return get(vertex_all, g)[v]; } template<BOOST_CSR_GRAPH_TEMPLATE_PARMS> inline void put(vertex_all_t, BOOST_CSR_GRAPH_TYPE& g, Vertex v, const VertexProperty& val) { put(get(vertex_all, g), v, val); } template<BOOST_CSR_GRAPH_TEMPLATE_PARMS> inline typename property_map<BOOST_CSR_GRAPH_TYPE, edge_all_t>::type get(edge_all_t, BOOST_CSR_GRAPH_TYPE& g) { return g.m_forward.get_edge_bundle(get(edge_index, g)); } template<BOOST_CSR_GRAPH_TEMPLATE_PARMS> inline typename property_map<BOOST_CSR_GRAPH_TYPE, edge_all_t>::const_type get(edge_all_t, const BOOST_CSR_GRAPH_TYPE& g) { return g.m_forward.get_edge_bundle(get(edge_index, g)); } template<BOOST_CSR_GRAPH_TEMPLATE_PARMS> inline EdgeProperty& get(edge_all_t, BOOST_CSR_GRAPH_TYPE& g, const typename BOOST_CSR_GRAPH_TYPE::edge_descriptor& e) { return get(edge_all, g)[e]; } template<BOOST_CSR_GRAPH_TEMPLATE_PARMS> inline const EdgeProperty& get(edge_all_t, const BOOST_CSR_GRAPH_TYPE& g, const typename BOOST_CSR_GRAPH_TYPE::edge_descriptor& e) { return get(edge_all, g)[e]; } template<BOOST_CSR_GRAPH_TEMPLATE_PARMS> inline void put(edge_all_t, BOOST_CSR_GRAPH_TYPE& g, const typename BOOST_CSR_GRAPH_TYPE::edge_descriptor& e, const EdgeProperty& val) { put(get(edge_all, g), e, val); } template<BOOST_CSR_GRAPH_TEMPLATE_PARMS> inline typename property_map<BOOST_CSR_GRAPH_TYPE, graph_all_t>::type get(graph_all_t, BOOST_CSR_GRAPH_TYPE& g) { return typename property_map<BOOST_CSR_GRAPH_TYPE, graph_all_t>::type(g.m_property); } template<BOOST_CSR_GRAPH_TEMPLATE_PARMS> inline typename property_map<BOOST_CSR_GRAPH_TYPE, graph_all_t>::const_type get(graph_all_t, const BOOST_CSR_GRAPH_TYPE& g) { return typename property_map<BOOST_CSR_GRAPH_TYPE, graph_all_t>::const_type(g.m_property); } template<BOOST_CSR_GRAPH_TEMPLATE_PARMS> inline GraphProperty& get(graph_all_t, BOOST_CSR_GRAPH_TYPE& g, BOOST_CSR_GRAPH_TYPE*) { return g.m_property; } template<BOOST_CSR_GRAPH_TEMPLATE_PARMS> inline const GraphProperty& get(graph_all_t, const BOOST_CSR_GRAPH_TYPE& g, BOOST_CSR_GRAPH_TYPE*) { return g.m_property; } template<BOOST_CSR_GRAPH_TEMPLATE_PARMS> inline void put(graph_all_t, BOOST_CSR_GRAPH_TYPE& g, BOOST_CSR_GRAPH_TYPE*, const GraphProperty& val) { g.m_property = val; } #undef BOOST_CSR_GRAPH_TYPE #undef BOOST_CSR_GRAPH_TEMPLATE_PARMS #undef BOOST_DIR_CSR_GRAPH_TYPE #undef BOOST_DIR_CSR_GRAPH_TEMPLATE_PARMS #undef BOOST_BIDIR_CSR_GRAPH_TYPE #undef BOOST_BIDIR_CSR_GRAPH_TEMPLATE_PARMS } // end namespace boost #endif // BOOST_GRAPH_COMPRESSED_SPARSE_ROW_GRAPH_HPP
[ "wenwenjun@weeget.cn" ]
wenwenjun@weeget.cn
01ea1a66d5912b5d2f6d765795755be25dcfc7ff
2635bab6d16a84e6fdbfdefba3913fe54da54a22
/PG4/Node.cpp
1a7fe867a42f22e251279bf72ba1353057a2db65
[]
no_license
benharri/cs201
c32ca85a3859b126a46717b16e2db604202ec2b3
9f551a502ba39ee80a2df1c01360c2af5b70377c
refs/heads/master
2021-08-24T07:53:39.794709
2017-12-08T18:34:12
2017-12-08T18:34:12
113,461,542
1
0
null
null
null
null
UTF-8
C++
false
false
1,096
cpp
//Ben Harris //Node.cpp contains the code for each node #include <iostream> #include <string> #include <cstdlib> #include <cctype> #include "Node.h" #include "List.h" #include "PG4.h" using namespace std; Node::Node(string s, Node *n){ value = s; next = n; } Node::~Node(){delete next;} string Node::getvalue(){return value;} int Node::getcount(){return cnt;} Node * Node::getnext(){return next;} void Node::setnext(Node *n){ next = n; } Node * Node::add(string s, string l){ string lvalue = converttolower(value); if (lvalue == l) return this; if (l < lvalue) return new Node(s, this); if (!next){ next = new Node(s, NULL); return this; } next = next->add(s,l); return this; } void Node::print(){ cout << value << endl; if (next) next->print(); } Node* Node::remove(string s, Node *prev, List *l){ string lvalue = converttolower(value); if (next) next = next->remove(s, this, l); if (lvalue.find(s) < value.length() && lvalue.find(s) >= 0){ Node *t = next; next = NULL; delete this; return t; } return this; }
[ "mail@benharris.ch" ]
mail@benharris.ch
c9ab3462075af7b03fd3d66f7097feeeb0faa96d
2336d94ed08becd1e680491fed2757964b41645e
/src/features/EnvironmentFeatureClass.cpp
dee787c22eb1adb8f2f0ab5dbf84004fd9552d08
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
adjustive/triumph4php
1360e6110dd717717bc10a5bb09b4ca14a8c525f
5eda79f0a9bf9bd6b5752bb66e9015cabb23f5cf
refs/heads/master
2021-01-17T21:47:13.337615
2015-07-22T00:43:18
2015-07-22T00:43:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,271
cpp
/** * @copyright 2009-2011 Roberto Perpuly * @license http://www.opensource.org/licenses/mit-license.php The MIT License * * This software is released under the terms of the MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "features/EnvironmentFeatureClass.h" #include <wx/filename.h> #include <wx/string.h> #include <vector> #include "Triumph.h" const wxEventType t4p::EVENT_APACHE_FILE_READ_COMPLETE = wxNewEventType(); t4p::ApacheFileReadCompleteEventClass::ApacheFileReadCompleteEventClass(int eventId, const t4p::ApacheClass &apache) : wxEvent(eventId, t4p::EVENT_APACHE_FILE_READ_COMPLETE) , Apache(apache) { } wxEvent* t4p::ApacheFileReadCompleteEventClass::Clone() const { t4p::ApacheFileReadCompleteEventClass* evt = new t4p::ApacheFileReadCompleteEventClass(GetId(), Apache); return evt; } t4p::ApacheFileReaderClass::ApacheFileReaderClass(t4p::RunningThreadsClass& runningThreads, int eventId) : BackgroundFileReaderClass(runningThreads, eventId) , ApacheResults() { } bool t4p::ApacheFileReaderClass::Init(const wxString& startDirectory) { ApacheResults.ManualConfiguration = false; ApacheResults.ClearMappings(); return BackgroundFileReaderClass::Init(startDirectory); } wxString t4p::ApacheFileReaderClass::GetLabel() const { return wxT("Apache File Reader"); } bool t4p::ApacheFileReaderClass::BackgroundFileMatch(const wxString& file) { return true; } bool t4p::ApacheFileReaderClass::BackgroundFileRead(t4p::DirectorySearchClass& search) { bool ret = false; if (search.Walk(ApacheResults)) { ret = true; } if (!search.More() && !IsCancelled()) { // when we are done recursing, parse the matched files std::vector<wxString> possibleConfigFiles = search.GetMatchedFiles(); // there may be multiple files, at this point just exist as soon as we find one file // that we can recognize as a config file bool found = false; for (size_t i = 0; i < possibleConfigFiles.size(); ++i) { if (ApacheResults.SetHttpdPath(possibleConfigFiles[i])) { found = true; break; } } // send the event once we have searched all files if (found) { t4p::ApacheFileReadCompleteEventClass evt(wxID_ANY, ApacheResults); PostEvent(evt); } } return ret; } t4p::EnvironmentFeatureClass::EnvironmentFeatureClass(t4p::AppClass& app) : FeatureClass(app) { } void t4p::EnvironmentFeatureClass::OnPreferencesSaved(wxCommandEvent& event) { wxConfigBase* config = wxConfigBase::Get(); App.Globals.Environment.SaveToConfig(config); if (App.Globals.Environment.Php.IsAuto && App.Globals.Environment.Php.Installed) { App.Globals.Environment.Php.AutoDetermine(); } // signal that this app has modified the config file, that way the external // modification check fails and the user will not be prompted to reload the config App.UpdateConfigModifiedTime(); } BEGIN_EVENT_TABLE(t4p::EnvironmentFeatureClass, wxEvtHandler) EVT_COMMAND(wxID_ANY, t4p::EVENT_APP_PREFERENCES_SAVED, t4p::EnvironmentFeatureClass::OnPreferencesSaved) END_EVENT_TABLE()
[ "robertop2004@gmail.com" ]
robertop2004@gmail.com
b12a509c057b13d720100c661b5e05a52732a5d5
d6ebbcf78baa559cf138d073ca0e6174373a8ee8
/algorithm/404.sum-of-left-leaves.cpp
650675d7eb1efd3e29180ad3ab71635565ae60d1
[]
no_license
silencelee/leetcode
91bd93704a83a48f9afa86744e871d1b3ef098e5
32d1bca2009635423cfdc0f022fb335c9baf4c7e
refs/heads/master
2021-07-09T15:19:50.735419
2021-03-22T03:26:06
2021-03-22T03:26:06
236,697,573
0
0
null
null
null
null
UTF-8
C++
false
false
1,754
cpp
/* * @lc app=leetcode id=404 lang=cpp * * [404] Sum of Left Leaves * * https://leetcode.com/problems/sum-of-left-leaves/description/ * * algorithms * Easy (50.23%) * Likes: 1433 * Dislikes: 142 * Total Accepted: 213.1K * Total Submissions: 409.8K * Testcase Example: '[3,9,20,null,null,15,7]' * * Find the sum of all left leaves in a given binary tree. * * Example: * * ⁠ 3 * ⁠ / \ * ⁠ 9 20 * ⁠ / \ * ⁠ 15 7 * * There are two left leaves in the binary tree, with values 9 and 15 * respectively. Return 24. * * */ // @lc code=start /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: bool isLeaf(TreeNode* node) { return node->left == nullptr && node->right == nullptr; } int sumOfLeftLeaves(TreeNode* root) { if (root == nullptr) return 0; int res = 0; queue<TreeNode*> q; q.emplace(root); while (!q.empty()) { auto t = q.front(); q.pop(); if (t->left != nullptr) { if (isLeaf(t->left)) { res += t->left->val; } else { q.emplace(t->left); } } if (t->right != nullptr) { if (!isLeaf(t->right)) { q.emplace(t->right); } } } return res; } }; // @lc code=end
[ "lij311@qq.com" ]
lij311@qq.com
6d4622a3fd3fc1ed6e8d83124497da680e31cf0c
238ef97fb594cbf10d0bc5f078cda08de40bea3a
/third_party/mlir/include/mlir/Dialect/LLVMIR/LLVMDialect.h
e8f3025b0a50e088b2bfe1871e2a217840d49dc9
[ "Apache-2.0" ]
permissive
yechens/tensorflow
01a06f81a225b97347141397751966a6e8915e19
382261952391abea73884374fb8abbc294a53596
refs/heads/master
2020-08-11T13:26:33.939969
2019-10-11T22:46:21
2019-10-12T03:11:56
214,570,519
1
0
Apache-2.0
2019-10-12T03:25:40
2019-10-12T03:25:39
null
UTF-8
C++
false
false
6,655
h
//===- LLVMDialect.h - MLIR LLVM IR dialect ---------------------*- C++ -*-===// // // Copyright 2019 The MLIR 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. // ============================================================================= // // This file defines the LLVM IR dialect in MLIR, containing LLVM operations and // LLVM type system. // //===----------------------------------------------------------------------===// #ifndef MLIR_DIALECT_LLVMIR_LLVMDIALECT_H_ #define MLIR_DIALECT_LLVMIR_LLVMDIALECT_H_ #include "mlir/IR/Dialect.h" #include "mlir/IR/Function.h" #include "mlir/IR/OpDefinition.h" #include "mlir/IR/OpImplementation.h" #include "mlir/IR/TypeSupport.h" #include "mlir/IR/Types.h" #include "llvm/IR/DerivedTypes.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Module.h" #include "llvm/IR/Type.h" #include "mlir/Dialect/LLVMIR/LLVMOpsEnums.h.inc" namespace llvm { class Type; class LLVMContext; } // end namespace llvm namespace mlir { namespace LLVM { class LLVMDialect; namespace detail { struct LLVMTypeStorage; struct LLVMDialectImpl; } // namespace detail class LLVMType : public mlir::Type::TypeBase<LLVMType, mlir::Type, detail::LLVMTypeStorage> { public: enum Kind { LLVM_TYPE = FIRST_LLVM_TYPE, }; using Base::Base; static bool kindof(unsigned kind) { return kind == LLVM_TYPE; } LLVMDialect &getDialect(); llvm::Type *getUnderlyingType() const; /// Utilities to identify types. bool isFloatTy() { return getUnderlyingType()->isFloatTy(); } /// Array type utilities. LLVMType getArrayElementType(); unsigned getArrayNumElements(); bool isArrayTy(); /// Vector type utilities. LLVMType getVectorElementType(); bool isVectorTy(); /// Function type utilities. LLVMType getFunctionParamType(unsigned argIdx); unsigned getFunctionNumParams(); LLVMType getFunctionResultType(); bool isFunctionTy(); /// Pointer type utilities. LLVMType getPointerTo(unsigned addrSpace = 0); LLVMType getPointerElementTy(); bool isPointerTy(); /// Struct type utilities. LLVMType getStructElementType(unsigned i); bool isStructTy(); /// Utilities used to generate floating point types. static LLVMType getDoubleTy(LLVMDialect *dialect); static LLVMType getFloatTy(LLVMDialect *dialect); static LLVMType getHalfTy(LLVMDialect *dialect); /// Utilities used to generate integer types. static LLVMType getIntNTy(LLVMDialect *dialect, unsigned numBits); static LLVMType getInt1Ty(LLVMDialect *dialect) { return getIntNTy(dialect, /*numBits=*/1); } static LLVMType getInt8Ty(LLVMDialect *dialect) { return getIntNTy(dialect, /*numBits=*/8); } static LLVMType getInt8PtrTy(LLVMDialect *dialect) { return getInt8Ty(dialect).getPointerTo(); } static LLVMType getInt16Ty(LLVMDialect *dialect) { return getIntNTy(dialect, /*numBits=*/16); } static LLVMType getInt32Ty(LLVMDialect *dialect) { return getIntNTy(dialect, /*numBits=*/32); } static LLVMType getInt64Ty(LLVMDialect *dialect) { return getIntNTy(dialect, /*numBits=*/64); } /// Utilities used to generate other miscellaneous types. static LLVMType getArrayTy(LLVMType elementType, uint64_t numElements); static LLVMType getFunctionTy(LLVMType result, ArrayRef<LLVMType> params, bool isVarArg); static LLVMType getFunctionTy(LLVMType result, bool isVarArg) { return getFunctionTy(result, llvm::None, isVarArg); } static LLVMType getStructTy(LLVMDialect *dialect, ArrayRef<LLVMType> elements, bool isPacked = false); static LLVMType getStructTy(LLVMDialect *dialect, bool isPacked = false) { return getStructTy(dialect, llvm::None, isPacked); } template <typename... Args> static typename std::enable_if<llvm::are_base_of<LLVMType, Args...>::value, LLVMType>::type getStructTy(LLVMType elt1, Args... elts) { SmallVector<LLVMType, 8> fields({elt1, elts...}); return getStructTy(&elt1.getDialect(), fields); } static LLVMType getVectorTy(LLVMType elementType, unsigned numElements); static LLVMType getVoidTy(LLVMDialect *dialect); private: friend LLVMDialect; /// Get an LLVMType with a pre-existing llvm type. static LLVMType get(MLIRContext *context, llvm::Type *llvmType); /// Get an LLVMType with an llvm type that may cause changes to the underlying /// llvm context when constructed. static LLVMType getLocked(LLVMDialect *dialect, llvm::function_ref<llvm::Type *()> typeBuilder); }; ///// Ops ///// #define GET_OP_CLASSES #include "mlir/Dialect/LLVMIR/LLVMOps.h.inc" class LLVMDialect : public Dialect { public: explicit LLVMDialect(MLIRContext *context); ~LLVMDialect(); static StringRef getDialectNamespace() { return "llvm"; } llvm::LLVMContext &getLLVMContext(); llvm::Module &getLLVMModule(); /// Parse a type registered to this dialect. Type parseType(StringRef tyData, Location loc) const override; /// Print a type registered to this dialect. void printType(Type type, raw_ostream &os) const override; /// Verify a region argument attribute registered to this dialect. /// Returns failure if the verification failed, success otherwise. LogicalResult verifyRegionArgAttribute(Operation *op, unsigned regionIdx, unsigned argIdx, NamedAttribute argAttr) override; private: friend LLVMType; std::unique_ptr<detail::LLVMDialectImpl> impl; }; /// Create an LLVM global containing the string "value" at the module containing /// surrounding the insertion point of builder. Obtain the address of that /// global and use it to compute the address of the first character in the /// string (operations inserted at the builder insertion point). Value *createGlobalString(Location loc, OpBuilder &builder, StringRef name, StringRef value, LLVM::LLVMDialect *llvmDialect); } // end namespace LLVM } // end namespace mlir #endif // MLIR_DIALECT_LLVMIR_LLVMDIALECT_H_
[ "gardener@tensorflow.org" ]
gardener@tensorflow.org
1bfdeff9fee93925456fcc9aa4ac8feab155f5b6
948f4e13af6b3014582909cc6d762606f2a43365
/testcases/juliet_test_suite/testcases/CWE762_Mismatched_Memory_Management_Routines/s01/CWE762_Mismatched_Memory_Management_Routines__delete_array_class_realloc_82_goodB2G.cpp
73affa9a5a6fb4a1e6d7efcaf8b9ee0e856317da
[]
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
1,111
cpp
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE762_Mismatched_Memory_Management_Routines__delete_array_class_realloc_82_goodB2G.cpp Label Definition File: CWE762_Mismatched_Memory_Management_Routines__delete_array.label.xml Template File: sources-sinks-82_goodB2G.tmpl.cpp */ /* * @description * CWE: 762 Mismatched Memory Management Routines * BadSource: realloc Allocate data using realloc() * GoodSource: Allocate data using new [] * Sinks: * GoodSink: Deallocate data using free() * BadSink : Deallocate data using delete [] * Flow Variant: 82 Data flow: data passed in a parameter to an virtual method called via a pointer * * */ #ifndef OMITGOOD #include "std_testcase.h" #include "CWE762_Mismatched_Memory_Management_Routines__delete_array_class_realloc_82.h" namespace CWE762_Mismatched_Memory_Management_Routines__delete_array_class_realloc_82 { void CWE762_Mismatched_Memory_Management_Routines__delete_array_class_realloc_82_goodB2G::action(TwoIntsClass * data) { /* FIX: Free memory using free() */ free(data); } } #endif /* OMITGOOD */
[ "yzhang0701@gmail.com" ]
yzhang0701@gmail.com
4ee391d03894a1ef468ecf2cca3fea4f87ae53cf
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/CMake/CMake-gumtree/Kitware_CMake_repos_basic_block_block_18351.cpp
a80fdce2a01fdbf3561ca37a67833b3610e94340
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
33
cpp
{ ctx->message[index++] = 0; }
[ "993273596@qq.com" ]
993273596@qq.com
ad51684db2f77a805d8ffdf03b2a83f5c35c606f
c46e692abab08e7c3a84d8b85463cb56fbdce542
/src/util.h
2cbd89f5b209013bf4c4578baf3523b2399af3ee
[ "MIT", "LicenseRef-scancode-other-permissive" ]
permissive
cinnamoncoin/datacoin
abd7ab62bb659b19d3b8d0bc5d4571a2de8a570d
b009ce2e5c26309ef88254a7689276fac5bf5461
refs/heads/master
2020-04-25T13:51:13.317290
2014-11-13T21:57:13
2014-11-13T21:57:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
17,023
h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Copyright (c) 2013 The Primecoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_UTIL_H #define BITCOIN_UTIL_H #include "uint256.h" #include <stdarg.h> #ifndef WIN32 #include <sys/types.h> #include <sys/time.h> #include <sys/resource.h> #else typedef int pid_t; /* define for Windows compatibility */ #endif #include <map> #include <list> #include <utility> #include <vector> #include <string> #include <boost/version.hpp> #include <boost/thread.hpp> #include <boost/filesystem.hpp> #include <boost/filesystem/path.hpp> #include <boost/date_time/gregorian/gregorian_types.hpp> #include <boost/date_time/posix_time/posix_time_types.hpp> #include "netbase.h" // for AddTimeData typedef long long int64; typedef unsigned long long uint64; static const int64 COIN = 100000000; static const int64 CENT = 1000000; #define loop for (;;) #define BEGIN(a) ((char*)&(a)) #define END(a) ((char*)&((&(a))[1])) #define UBEGIN(a) ((unsigned char*)&(a)) #define UEND(a) ((unsigned char*)&((&(a))[1])) #define ARRAYLEN(array) (sizeof(array)/sizeof((array)[0])) #ifndef PRI64d #if defined(_MSC_VER) || defined(__MSVCRT__) #define PRI64d "I64d" #define PRI64u "I64u" #define PRI64x "I64x" #else #define PRI64d "lld" #define PRI64u "llu" #define PRI64x "llx" #endif #endif /* Format characters for (s)size_t and ptrdiff_t */ #if defined(_MSC_VER) || defined(__MSVCRT__) /* (s)size_t and ptrdiff_t have the same size specifier in MSVC: http://msdn.microsoft.com/en-us/library/tcxf1dw6%28v=vs.100%29.aspx */ #define PRIszx "Ix" #define PRIszu "Iu" #define PRIszd "Id" #define PRIpdx "Ix" #define PRIpdu "Iu" #define PRIpdd "Id" #else /* C99 standard */ #define PRIszx "zx" #define PRIszu "zu" #define PRIszd "zd" #define PRIpdx "tx" #define PRIpdu "tu" #define PRIpdd "td" #endif // This is needed because the foreach macro can't get over the comma in pair<t1, t2> #define PAIRTYPE(t1, t2) std::pair<t1, t2> // Align by increasing pointer, must have extra space at end of buffer template <size_t nBytes, typename T> T* alignup(T* p) { union { T* ptr; size_t n; } u; u.ptr = p; u.n = (u.n + (nBytes-1)) & ~(nBytes-1); return u.ptr; } #ifdef WIN32 #define MSG_NOSIGNAL 0 #define MSG_DONTWAIT 0 #ifndef S_IRUSR #define S_IRUSR 0400 #define S_IWUSR 0200 #endif #else #define MAX_PATH 1024 #endif inline void MilliSleep(int64 n) { // Boost's sleep_for was uninterruptable when backed by nanosleep from 1.50 // until fixed in 1.52. Use the deprecated sleep method for the broken case. // See: https://svn.boost.org/trac/boost/ticket/7238 #if BOOST_VERSION >= 105000 && (!defined(BOOST_HAS_NANOSLEEP) || BOOST_VERSION >= 105200) boost::this_thread::sleep_for(boost::chrono::milliseconds(n)); #else boost::this_thread::sleep(boost::posix_time::milliseconds(n)); #endif } /* This GNU C extension enables the compiler to check the format string against the parameters provided. * X is the number of the "format string" parameter, and Y is the number of the first variadic parameter. * Parameters count from 1. */ #ifdef __GNUC__ #define ATTR_WARN_PRINTF(X,Y) __attribute__((format(printf,X,Y))) #else #define ATTR_WARN_PRINTF(X,Y) #endif extern std::map<std::string, std::string> mapArgs; extern std::map<std::string, std::vector<std::string> > mapMultiArgs; extern bool fDebug; extern bool fDebugNet; extern bool fPrintToConsole; extern bool fPrintToDebugger; extern bool fDaemon; extern bool fServer; extern bool fCommandLine; extern std::string strMiscWarning; extern bool fTestNet; extern bool fNoListen; extern bool fLogTimestamps; extern volatile bool fReopenDebugLog; void RandAddSeed(); void RandAddSeedPerfmon(); int ATTR_WARN_PRINTF(1,2) OutputDebugStringF(const char* pszFormat, ...); /* Rationale for the real_strprintf / strprintf construction: It is not allowed to use va_start with a pass-by-reference argument. (C++ standard, 18.7, paragraph 3). Use a dummy argument to work around this, and use a macro to keep similar semantics. */ /** Overload strprintf for char*, so that GCC format type warnings can be given */ std::string ATTR_WARN_PRINTF(1,3) real_strprintf(const char *format, int dummy, ...); /** Overload strprintf for std::string, to be able to use it with _ (translation). * This will not support GCC format type warnings (-Wformat) so be careful. */ std::string real_strprintf(const std::string &format, int dummy, ...); #define strprintf(format, ...) real_strprintf(format, 0, __VA_ARGS__) std::string vstrprintf(const char *format, va_list ap); bool ATTR_WARN_PRINTF(1,2) error(const char *format, ...); /* Redefine printf so that it directs output to debug.log * * Do this *after* defining the other printf-like functions, because otherwise the * __attribute__((format(printf,X,Y))) gets expanded to __attribute__((format(OutputDebugStringF,X,Y))) * which confuses gcc. */ #define printf OutputDebugStringF void LogException(std::exception* pex, const char* pszThread); void PrintException(std::exception* pex, const char* pszThread); void PrintExceptionContinue(std::exception* pex, const char* pszThread); void ParseString(const std::string& str, char c, std::vector<std::string>& v); std::string FormatMoney(int64 n, bool fPlus=false); bool ParseMoney(const std::string& str, int64& nRet); bool ParseMoney(const char* pszIn, int64& nRet); std::vector<unsigned char> ParseHex(const char* psz); std::vector<unsigned char> ParseHex(const std::string& str); bool IsHex(const std::string& str); std::vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid = NULL); std::string DecodeBase64(const std::string& str); std::string EncodeBase64(const unsigned char* pch, size_t len); std::string EncodeBase64(const std::string& str); std::vector<unsigned char> DecodeBase32(const char* p, bool* pfInvalid = NULL); std::string DecodeBase32(const std::string& str); std::string EncodeBase32(const unsigned char* pch, size_t len); std::string EncodeBase32(const std::string& str); void ParseParameters(int argc, const char*const argv[]); bool WildcardMatch(const char* psz, const char* mask); bool WildcardMatch(const std::string& str, const std::string& mask); void FileCommit(FILE *fileout); int GetFilesize(FILE* file); bool TruncateFile(FILE *file, unsigned int length); int RaiseFileDescriptorLimit(int nMinFD); void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length); bool RenameOver(boost::filesystem::path src, boost::filesystem::path dest); boost::filesystem::path GetDefaultDataDir(); const boost::filesystem::path &GetDataDir(bool fNetSpecific = true); boost::filesystem::path GetConfigFile(); boost::filesystem::path GetPidFile(); void CreatePidFile(const boost::filesystem::path &path, pid_t pid); void ReadConfigFile(std::map<std::string, std::string>& mapSettingsRet, std::map<std::string, std::vector<std::string> >& mapMultiSettingsRet); #ifdef WIN32 boost::filesystem::path GetSpecialFolderPath(int nFolder, bool fCreate = true); #endif boost::filesystem::path GetTempPath(); void ShrinkDebugFile(); int GetRandInt(int nMax); uint64 GetRand(uint64 nMax); uint256 GetRandHash(); int64 GetTime(); void SetMockTime(int64 nMockTimeIn); int64 GetAdjustedTime(); int64 GetTimeOffset(); std::string FormatFullVersion(); std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments); void AddTimeData(const CNetAddr& ip, int64 nTime); void runCommand(std::string strCommand); inline std::string i64tostr(int64 n) { return strprintf("%"PRI64d, n); } inline std::string itostr(int n) { return strprintf("%d", n); } inline int64 atoi64(const char* psz) { #ifdef _MSC_VER return _atoi64(psz); #else return strtoll(psz, NULL, 10); #endif } inline int64 atoi64(const std::string& str) { #ifdef _MSC_VER return _atoi64(str.c_str()); #else return strtoll(str.c_str(), NULL, 10); #endif } inline int atoi(const std::string& str) { return atoi(str.c_str()); } inline int roundint(double d) { return (int)(d > 0 ? d + 0.5 : d - 0.5); } inline int64 roundint64(double d) { return (int64)(d > 0 ? d + 0.5 : d - 0.5); } inline int64 abs64(int64 n) { return (n >= 0 ? n : -n); } template<typename T> std::string HexStr(const T itbegin, const T itend, bool fSpaces=false) { std::string rv; static const char hexmap[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; rv.reserve((itend-itbegin)*3); for(T it = itbegin; it < itend; ++it) { unsigned char val = (unsigned char)(*it); if(fSpaces && it != itbegin) rv.push_back(' '); rv.push_back(hexmap[val>>4]); rv.push_back(hexmap[val&15]); } return rv; } inline std::string HexStr(const std::vector<unsigned char>& vch, bool fSpaces=false) { return HexStr(vch.begin(), vch.end(), fSpaces); } template<typename T> void PrintHex(const T pbegin, const T pend, const char* pszFormat="%s", bool fSpaces=true) { printf(pszFormat, HexStr(pbegin, pend, fSpaces).c_str()); } inline void PrintHex(const std::vector<unsigned char>& vch, const char* pszFormat="%s", bool fSpaces=true) { printf(pszFormat, HexStr(vch, fSpaces).c_str()); } inline int64 GetPerformanceCounter() { int64 nCounter = 0; #ifdef WIN32 QueryPerformanceCounter((LARGE_INTEGER*)&nCounter); #else timeval t; gettimeofday(&t, NULL); nCounter = (int64) t.tv_sec * 1000000 + t.tv_usec; #endif return nCounter; } inline int64 GetTimeMillis() { return (boost::posix_time::ptime(boost::posix_time::microsec_clock::universal_time()) - boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_milliseconds(); } inline int64 GetTimeMicros() { return (boost::posix_time::ptime(boost::posix_time::microsec_clock::universal_time()) - boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_microseconds(); } inline std::string DateTimeStrFormat(const char* pszFormat, int64 nTime) { time_t n = nTime; struct tm* ptmTime = gmtime(&n); char pszTime[200]; strftime(pszTime, sizeof(pszTime), pszFormat, ptmTime); return pszTime; } template<typename T> void skipspaces(T& it) { while (isspace(*it)) ++it; } inline bool IsSwitchChar(char c) { #ifdef WIN32 return c == '-' || c == '/'; #else return c == '-'; #endif } /** * Return string argument or default value * * @param strArg Argument to get (e.g. "-foo") * @param default (e.g. "1") * @return command-line argument or default value */ std::string GetArg(const std::string& strArg, const std::string& strDefault); /** * Return integer argument or default value * * @param strArg Argument to get (e.g. "-foo") * @param default (e.g. 1) * @return command-line argument (0 if invalid number) or default value */ int64 GetArg(const std::string& strArg, int64 nDefault); /** * Return boolean argument or default value * * @param strArg Argument to get (e.g. "-foo") * @param default (true or false) * @return command-line argument or default value */ bool GetBoolArg(const std::string& strArg, bool fDefault=false); /** * Set an argument if it doesn't already have a value * * @param strArg Argument to set (e.g. "-foo") * @param strValue Value (e.g. "1") * @return true if argument gets set, false if it already had a value */ bool SoftSetArg(const std::string& strArg, const std::string& strValue); /** * Set a boolean argument if it doesn't already have a value * * @param strArg Argument to set (e.g. "-foo") * @param fValue Value (e.g. false) * @return true if argument gets set, false if it already had a value */ bool SoftSetBoolArg(const std::string& strArg, bool fValue); /** * MWC RNG of George Marsaglia * This is intended to be fast. It has a period of 2^59.3, though the * least significant 16 bits only have a period of about 2^30.1. * * @return random value */ extern uint32_t insecure_rand_Rz; extern uint32_t insecure_rand_Rw; static inline uint32_t insecure_rand(void) { insecure_rand_Rz = 36969 * (insecure_rand_Rz & 65535) + (insecure_rand_Rz >> 16); insecure_rand_Rw = 18000 * (insecure_rand_Rw & 65535) + (insecure_rand_Rw >> 16); return (insecure_rand_Rw << 16) + insecure_rand_Rz; } /** * Seed insecure_rand using the random pool. * @param Deterministic Use a determinstic seed */ void seed_insecure_rand(bool fDeterministic=false); /** * Timing-attack-resistant comparison. * Takes time proportional to length * of first argument. */ template <typename T> bool TimingResistantEqual(const T& a, const T& b) { if (b.size() == 0) return a.size() == 0; size_t accumulator = a.size() ^ b.size(); for (size_t i = 0; i < a.size(); i++) accumulator |= a[i] ^ b[i%b.size()]; return accumulator == 0; } /** Median filter over a stream of values. * Returns the median of the last N numbers */ template <typename T> class CMedianFilter { private: std::vector<T> vValues; std::vector<T> vSorted; unsigned int nSize; public: CMedianFilter(unsigned int size, T initial_value): nSize(size) { vValues.reserve(size); vValues.push_back(initial_value); vSorted = vValues; } void input(T value) { if(vValues.size() == nSize) { vValues.erase(vValues.begin()); } vValues.push_back(value); vSorted.resize(vValues.size()); std::copy(vValues.begin(), vValues.end(), vSorted.begin()); std::sort(vSorted.begin(), vSorted.end()); } T median() const { int size = vSorted.size(); assert(size>0); if(size & 1) // Odd number of elements { return vSorted[size/2]; } else // Even number of elements { return (vSorted[size/2-1] + vSorted[size/2]) / 2; } } int size() const { return vValues.size(); } std::vector<T> sorted () const { return vSorted; } }; bool NewThread(void(*pfn)(void*), void* parg); #ifdef WIN32 inline void SetThreadPriority(int nPriority) { SetThreadPriority(GetCurrentThread(), nPriority); } #else #define THREAD_PRIORITY_LOWEST PRIO_MAX #define THREAD_PRIORITY_BELOW_NORMAL 2 #define THREAD_PRIORITY_NORMAL 0 #define THREAD_PRIORITY_ABOVE_NORMAL 0 inline void SetThreadPriority(int nPriority) { // It's unclear if it's even possible to change thread priorities on Linux, // but we really and truly need it for the generation threads. #ifdef PRIO_THREAD setpriority(PRIO_THREAD, 0, nPriority); #else setpriority(PRIO_PROCESS, 0, nPriority); #endif } inline void ExitThread(size_t nExitCode) { pthread_exit((void*)nExitCode); } #endif void RenameThread(const char* name); inline uint32_t ByteReverse(uint32_t value) { value = ((value & 0xFF00FF00) >> 8) | ((value & 0x00FF00FF) << 8); return (value<<16) | (value>>16); } // Standard wrapper for do-something-forever thread functions. // "Forever" really means until the thread is interrupted. // Use it like: // new boost::thread(boost::bind(&LoopForever<void (*)()>, "dumpaddr", &DumpAddresses, 900000)); // or maybe: // boost::function<void()> f = boost::bind(&FunctionWithArg, argument); // threadGroup.create_thread(boost::bind(&LoopForever<boost::function<void()> >, "nothing", f, milliseconds)); template <typename Callable> void LoopForever(const char* name, Callable func, int64 msecs) { std::string s = strprintf("primecoin-%s", name); RenameThread(s.c_str()); printf("%s thread start\n", name); try { while (1) { MilliSleep(msecs); func(); } } catch (boost::thread_interrupted) { printf("%s thread stop\n", name); throw; } catch (std::exception& e) { PrintException(&e, name); } catch (...) { PrintException(NULL, name); } } // .. and a wrapper that just calls func once template <typename Callable> void TraceThread(const char* name, Callable func) { std::string s = strprintf("primecoin-%s", name); RenameThread(s.c_str()); try { printf("%s thread start\n", name); func(); printf("%s thread exit\n", name); } catch (boost::thread_interrupted) { printf("%s thread interrupt\n", name); throw; } catch (std::exception& e) { PrintException(&e, name); } catch (...) { PrintException(NULL, name); } } #endif
[ "mustiigezen@gmail.com" ]
mustiigezen@gmail.com
a3ee5f0158a04fd4b0505f61fce450034d345445
6cc1cbf9e27498770168b3983537e2cf9d6f61b3
/Usage Meter/2.00/Meter 2.00/MyMonthSyncro.cpp
bdd2f4cbc97652810164007e753e2e340e58e670
[ "Apache-2.0" ]
permissive
VajiraK/UsageMeter
2ceb96c3a3d5b5da631ec9f7a83b11f9d51a1afb
140f0d27e44461add7b179473a9565d8c7ad51ba
refs/heads/master
2022-11-11T08:04:05.149500
2022-10-23T18:06:24
2022-10-23T18:06:24
248,560,884
0
0
null
null
null
null
UTF-8
C++
false
false
1,512
cpp
// MyMonthSyncro.cpp: implementation of the CMyMonthSyncro class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "Usage Meter.h" #include "MyMonthSyncro.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif ////////////////////////////////////////////////////////////////////// CMyMonthSyncro::CMyMonthSyncro() { m_regmonth=RegGet(HKEY_LOCAL_MACHINE,"Month"); } ////////////////////////////////////////////////////////////////////// bool CMyMonthSyncro::DetectMonChange() { SYSTEMTIME ST; DWORD sys_mon; ::GetLocalTime(&ST); sys_mon = ST.wMonth; if(sys_mon!=m_regmonth) {//month has changed //update registry m_regmonth = sys_mon; RegSet(HKEY_LOCAL_MACHINE,"Month",sys_mon); return true; }else{ return false; } } ////////////////////////////////////////////////////////////////////// int CMyMonthSyncro::GetSystemMonth() { SYSTEMTIME ST; ::GetLocalTime(&ST); return ST.wMonth; } ////////////////////////////////////////////////////////////////////// CString CMyMonthSyncro::NumToMothname(int monnum) { switch(monnum) { case 1: return "January"; case 2: return "February"; case 3: return "March"; case 4: return "April"; case 5: return "May"; case 6: return "June"; case 7: return "July"; case 8: return "August"; case 9: return "September"; case 10: return "October"; case 11: return "November"; case 12: return "December"; } return "invalid"; }
[ "vajira.kulatunga@pearson.com" ]
vajira.kulatunga@pearson.com
4d8976a13be240260fdcc1afc37542d3ccb8fe8e
7551f34c288cfa7081e771a599dde4dea297210f
/BN_proc/pre_proc.hpp
ba77d6815cbc5ea0a0bd7ca8504d618ea77a98b8
[]
no_license
Slavmir/CPP
38c86517716ecda67077ff3b22845099252b8bba
7bea0e119068ef1de6056ceca377b16566ff582c
refs/heads/master
2021-04-03T05:09:35.725437
2018-04-16T14:19:24
2018-04-16T14:19:24
124,794,593
0
0
null
null
null
null
UTF-8
C++
false
false
525
hpp
#ifndef PRE_PROC_HPP_INCLUDED #define PRE_PROC_HPP_INCLUDED /// zeta_String - wynik dodawania dwoch liczb w formie std::string /// a - ULL liczba z std::mt19937_64 /// b - wykladnik potegi w UI /// xx - tymczasowy ULL -> przepisz na (a) /// seed - ziarno c zasowe generatora std::mt19937_64 z std::chrono #include <iostream> #include <string> #include <chrono> #include <random> typedef unsigned long long ULL; typedef unsigned int UI; #endif // PRE_PROC_HPP_INCLUDED // 44 1090 1782 0000 0001 3410 8636 ///Kuba KFC
[ "SJaniga@outlook.com" ]
SJaniga@outlook.com
75e120aba03001311e7ec97fb4ca7df43a1db2ee
5c71b075d41e9db8aee2e1137b42196c3c73c5cc
/15 Puzzle/15 Puzzle/main.cpp
5788d40ec07d7de56536191a78577d2c9ffbc690
[]
no_license
Jack47744/algorithm
a6134f38aa024329e97c22d0f24cc4ff1d7a332e
645dfd01a63531198551a0aa73dd9ae72e53d497
refs/heads/master
2021-03-15T05:22:20.278193
2020-05-20T03:00:58
2020-05-20T03:00:58
246,827,435
0
0
null
null
null
null
UTF-8
C++
false
false
1,469
cpp
// // main.cpp // 15 Puzzle // // Created by Metis Sotangkur on 3/30/20. // Copyright © 2020 Metis Sotangkur. All rights reserved. // #include <iostream> #include <queue> #include <vector> #include <map> #include <set> int data[5][5]; using namespace std; map<int, pair<int, int>> mp; int costFunction(map<int, pair<int, int>> m){ int ans = 0; for(int i=0; i<16; i++){ ans += (mp[i].first - m[i].first)*(mp[i].first - m[i].first); ans += (mp[i].second - m[i].second)*(mp[i].second-m[i].second); } return ans; } struct board{ map<int, pair<int, int>> location; int cost = -1; int count = 0; void cal(){ cost = costFunction(location); } bool operator<(const board other){ return cost>other.cost; } }; int main(int argc, const char * argv[]) { int p=1; map<int, pair<int, int>> start; for(int i=0; i<4; i++){ for(int j=0; j<4; j++){ int n; cin>>n; start[n] = {i, j}; mp[p] = {i, j}; } } mp[0] = {3,3}; board ss; ss.count = 0; ss.location = start; ss.cal(); set<board> s; priority_queue<board> pq; pq.push(ss); s.insert(ss); while(pq.size()>0){ board tmp = pq.top(); pq.pop(); if(tmp.cost == 0){ cout<<tmp.count<<endl; exit(0); } if(s.find(tmp)==s.end()){ } } return 0; }
[ "jack10899@gmail.com" ]
jack10899@gmail.com
3103eeb9b9510a0cf6e9d1ebe4a08171a55222da
edabddd23276d9a40c7f8bf6d6986fb451adbc34
/Archive/Multi-University Training Contest/2019/7th/1006.cpp
277c50e5da0b9479baf3ef3d5b68d8d710ab52e1
[]
no_license
Akatsukis/ACM_Training
b70f49435b8c7bada6b52366e4a6a8010ff80ef9
0503f50bc033ba01c7993de346ac241b0d9d5625
refs/heads/master
2021-06-06T09:00:15.665775
2019-12-24T20:13:14
2019-12-24T20:13:14
103,283,338
2
0
null
null
null
null
UTF-8
C++
false
false
750
cpp
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef unsigned long long ull; typedef pair<int, int> pii; #define sc(x) scanf("%d", &x) #define pb push_back #define mk make_pair #define fi first #define se second #define ALL(x) x.begin(), x.end() #define SZ(x) ((int)x.size()) #define sqr(x) ((x)*(x)) #define ABS(x) ((x)>=0?(x):(-(x))) #define fastio ios::sync_with_stdio(0),cin.tie(0) template<class T>T gcd(T a, T b){return b?gcd(b, a%b):a;} int main() { int T; scanf("%d", &T); while(T--) { ll n, m, k; scanf("%lld%lld%lld", &n, &m, &k); ll base = n-k+1; ll scr = m/base+1; ll ans = scr*n; ans -= n-k-m%base; printf("%lld\n", ans); } return 0; }
[ "akatsuki6725@gmail.com" ]
akatsuki6725@gmail.com
ccd1c0ac41c1474807d7b7c9660edea469360e2c
bd7486a56e71b520d0016f170aafa9633d44f05b
/multiwinia/code/UI/ServerTitleInfoButton.h
ef3a9f22ed62eb9450fd7cc578d02b261e96ca71
[]
no_license
bsella/Darwinia-and-Multiwinia-Source-Code
3bf1d7117f1be48a7038e2ab9f7d385bf82852d1
22f2069b9228a02c7e2953ace1ea63c2ef534e41
refs/heads/master
2022-05-31T18:35:59.264774
2022-04-24T22:40:30
2022-04-24T22:40:30
290,299,680
0
0
null
2020-08-25T19:02:29
2020-08-25T19:02:29
null
UTF-8
C++
false
false
2,038
h
#ifndef __SERVERTITLEINFOBUTTON__ #define __SERVERTITLEINFOBUTTON__ class ServerTitleInfoButton : public DarwiniaButton { public: ServerTitleInfoButton() : DarwiniaButton() { } void Render( int realX, int realY, bool highlighted, bool clicked ) { glColor4f( 0.0f, 0.0f, 0.0f, 0.5f ); glBegin( GL_QUADS ); glVertex2f( realX, realY ); glVertex2f( realX + m_w, realY ); glVertex2f( realX + m_w, realY + m_h ); glVertex2f( realX, realY + m_h ); glEnd(); int x = realX; int y = realY + (m_h/2.0f);// - (m_fontSize / 4.0f); x += m_w * 0.05f; g_gameFont.SetRenderOutline(true); glColor4f(1.0f,1.0f,1.0f,0.0f); g_gameFont.DrawText2D( x, y, m_fontSize, LANGUAGEPHRASE("multiwinia_join_host") ); g_gameFont.SetRenderOutline(false); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); g_gameFont.DrawText2D( x, y, m_fontSize, LANGUAGEPHRASE("multiwinia_join_host") ); x += m_w * 0.25f; g_gameFont.SetRenderOutline(true); glColor4f(1.0f,1.0f,1.0f,0.0f); g_gameFont.DrawText2D( x, y, m_fontSize, LANGUAGEPHRASE("multiwinia_join_type") ); g_gameFont.SetRenderOutline(false); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); g_gameFont.DrawText2D( x, y, m_fontSize, LANGUAGEPHRASE("multiwinia_join_type") ); x += m_w * 0.1f; g_gameFont.SetRenderOutline(true); glColor4f(1.0f,1.0f,1.0f,0.0f); g_gameFont.DrawText2D( x, y, m_fontSize, LANGUAGEPHRASE("multiwinia_join_map") ); g_gameFont.SetRenderOutline(false); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); g_gameFont.DrawText2D( x, y, m_fontSize, LANGUAGEPHRASE("multiwinia_join_map") ); x = realX + m_w * 0.98f; g_gameFont.SetRenderOutline(true); glColor4f(1.0f,1.0f,1.0f,0.0f); g_gameFont.DrawText2DRight( x, y, m_fontSize, LANGUAGEPHRASE("multiwinia_join_players") ); g_gameFont.SetRenderOutline(false); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); g_gameFont.DrawText2DRight( x, y, m_fontSize, LANGUAGEPHRASE("multiwinia_join_players") ); } }; #endif
[ "root@9244cb4f-d52e-49a9-a756-7d4e53ad8306" ]
root@9244cb4f-d52e-49a9-a756-7d4e53ad8306
5fa6ced69f23821d2ddcdf3bde0d5d1c44c20a50
60b30b09333f305b833e41a31e58ac927661f995
/libraries/AIO/examples/EthernetClient/EthernetClient.ino
0b6ed10e51e653cd66062e1d295922347dfbce56
[ "MIT" ]
permissive
amdx/ArduinoCore-AIO
51bfd7af518b218631d2d2a0652fa6bf9e63adc3
bdf41ce7ec772190d5bee0b3bab1231e6bd0bcbf
refs/heads/master
2020-04-17T14:41:39.092092
2019-01-20T15:21:39
2019-01-20T15:21:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,889
ino
/** * AMDX AIO arduino library * * Copyright (C) 2019 Archimedes Exhibitions GmbH * All rights reserved. * * MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons * to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ // Tests the onboard W5500 ethernet controller on the AIO XL #include <Arduino.h> #include <Ethernet.h> #include <AIO.h> using namespace AIO; const uint8_t MAX_CHUNK_SIZE = 128; uint8_t mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; EthernetClient client; void fetch_page(const char* host) { uint8_t chunk[MAX_CHUNK_SIZE]; Serial.print(F(">>> Connecting to: ")); Serial.println(host); if (client.connect(host, 80)) { client.write("HEAD / HTTP/1.1\nHost:"); client.write(host); client.write("\nConnection: close\n\n"); Serial.println(F(">>> Retrieving data:")); while (1) { int length = client.read(chunk, MAX_CHUNK_SIZE); if (length > 0) { Serial.write(chunk, length); } else if (!client.connected()) { Serial.println(); Serial.println(F(">>> Head fetched")); break; } } } else { Serial.println(F("*** Cannot connect to the remote end")); } } void setup() { // Open serial communications and wait for port to open: Serial.begin(115200); Serial.print(F("Initializing..")); Ethernet.init(ETH_CS_PIN); Ethernet.begin(mac, IPAddress(0, 0, 0, 0)); Serial.println("done."); Serial.print(F("Waiting for link..")); while (Ethernet.linkStatus() != LinkON) { delay(500); Serial.print("."); } Serial.println(F("link is up.")); Serial.print(F("Requesting IP via DHCP..")); // Initialize the ethernet library Ethernet.begin(mac); Serial.println(F("done.")); fetch_page("www.google.com"); } void loop() { }
[ "x@xul.it" ]
x@xul.it
9bd52727349e4eff070e71c6937a53e2511dbe5e
34143cd84540d99cef21fd5edd468c7cd40ac335
/AOJ/0008.cc
7baee375e5c27dfa3acd7d30a20409db513b3947
[]
no_license
osak/Contest
0094f87c674d24ebfc0d764fca284493ab90df99
22c9edb994b6506b1a4f65b53a6046145a6cce41
refs/heads/master
2023-03-06T02:23:53.795410
2023-02-26T11:32:11
2023-02-26T11:32:11
5,219,104
8
9
null
2015-02-09T06:09:14
2012-07-29T01:16:42
C++
UTF-8
C++
false
false
377
cc
#include <iostream> using namespace std; int main() { int n; while(cin >> n) { int cnt = 0; for(int i = 0; i <= 9; ++i) for(int j = 0; j <= 9; ++j) for(int k = 0; k <= 9; ++k) for(int l = 0; l <= 9; ++l) if(i+j+k+l == n) ++cnt; cout << cnt << endl; } return 0; }
[ "osak.63@gmail.com" ]
osak.63@gmail.com
d67bd527e62cfdd265bb754e7ca48f0537c6c95f
7101b53574ad4e2338b05450b7f3448c50f61005
/thirdparty/google/protobuf/any.grpc.pb.h
64359b90f607b317e3c6f5f6015ce447c7f316b0
[ "Apache-2.0" ]
permissive
kobeya/GVA-demo
4d6af374ea95be32aee8214947600e6a3e8bd2c4
41a57bfff01ab0de2f56ddcd7611514e550472ff
refs/heads/master
2022-08-07T00:52:39.986363
2020-06-01T16:10:09
2020-06-01T16:10:09
268,522,738
0
0
null
null
null
null
UTF-8
C++
false
true
2,710
h
// Generated by the gRPC C++ plugin. // If you make any local change, they will be lost. // source: google/protobuf/any.proto // Original file comments: // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // 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. // #ifndef GRPC_google_2fprotobuf_2fany_2eproto__INCLUDED #define GRPC_google_2fprotobuf_2fany_2eproto__INCLUDED #include "google/protobuf/any.pb.h" #include <grpcpp/impl/codegen/async_generic_service.h> #include <grpcpp/impl/codegen/async_stream.h> #include <grpcpp/impl/codegen/async_unary_call.h> #include <grpcpp/impl/codegen/method_handler_impl.h> #include <grpcpp/impl/codegen/proto_utils.h> #include <grpcpp/impl/codegen/rpc_method.h> #include <grpcpp/impl/codegen/service_type.h> #include <grpcpp/impl/codegen/status.h> #include <grpcpp/impl/codegen/stub_options.h> #include <grpcpp/impl/codegen/sync_stream.h> namespace grpc { class CompletionQueue; class Channel; class ServerCompletionQueue; class ServerContext; } // namespace grpc namespace google { namespace protobuf { } // namespace protobuf } // namespace google #endif // GRPC_google_2fprotobuf_2fany_2eproto__INCLUDED
[ "347511974@qq.com" ]
347511974@qq.com
ec4409076b28c6aafc50f80fb792991c4b73124f
16cb55beea26cf910d8360a252d00578403d5044
/leetcode_cpp/include/leetcode/problem_28.hpp
d84e2d3c4124623f1db8083e355f45112a5a1ffc
[]
no_license
hbina/leetcode-solutions
463141b28521b5983fe27b94652a6dcd2dd8e7d4
e823d03a2723fa9599144056a2958ddb35aef2d7
refs/heads/master
2021-08-19T00:57:07.699954
2020-04-03T17:54:53
2020-04-03T17:54:53
152,827,421
0
0
null
null
null
null
UTF-8
C++
false
false
627
hpp
#pragma once #include "util/generic/find_range.hpp" namespace leetcode { template <typename Iterable> static constexpr int strStr( const Iterable &haystack, const Iterable &needle) { if (needle.size() == 0) { return 0; } using IteratorType = typename Iterable::const_iterator; const IteratorType result = util::generic::find_range( std::cbegin(haystack), std::cend(haystack), std::cbegin(needle), std::cend(needle)); return result == std::cend(haystack) ? -1 : static_cast<int>(std::distance(std::cbegin(haystack), result)); } } // namespace leetcode
[ "hanif.ariffin.4326@gmail.com" ]
hanif.ariffin.4326@gmail.com
b6e8a8c66cf8c8ae17455e6e39049b47e90f3735
a1f0ba9ff989aed7f58b1e9ac59403968f955e68
/cPlusPlus/src/cpp11/SmartPointers.cpp
274b137100324c47e57ad6830ba6ecbb7d65c05a
[]
no_license
kajalv/advanced-cpp
faf9e51c27e001529d9b06af748ceda5cffac584
1e609f393cad3d253a220f2b23fe3e821281bfb8
refs/heads/master
2020-07-07T17:59:51.443268
2018-07-31T18:38:33
2018-07-31T18:38:33
203,430,401
0
0
null
null
null
null
UTF-8
C++
false
false
1,628
cpp
#include "SmartPointers.h" // need to #include <memory> to use smart or shared pointers // smart - aka unique pointers or auto pointers class TestSmartPtr { public: TestSmartPtr() { cout << "created" << endl; } void greet() { cout << "Hello" << endl; } ~TestSmartPtr() { cout << "destroyed" << endl; } }; class TempSmart { private: unique_ptr<TestSmartPtr[]> pTest; // private unique pointer. // unique_ptr<TestSmartPtr[]> pTest(new TestSmartPtr[2]); // this won't work here because we are trying to call constructor // hence we need a public constructor for this class public: TempSmart() : pTest(new TestSmartPtr[2]) // have to use initialization list to do this { } }; void runSmartPointers() { // simple int example unique_ptr<int> pointerTestInt(new int); // no need to say int *, just int. // because we want the pointer to manage the memory allocated by new itself, we cannot say = new int. It has to be done within constructor. *pointerTestInt = 7; cout << *pointerTestInt << endl; // use like a regular pointer, but will be automatically deallocated. // example with objects to make it clear with destructors unique_ptr<TestSmartPtr> pointerTestObj(new TestSmartPtr); pointerTestObj->greet(); // Prior to C++11, there was auto_ptr which is similar to unique_ptr.But now it is deprecated. // Also, we cannot use auto_ptr on arrays but we can use unique_ptr on arrays. unique_ptr<TestSmartPtr[]> pTest(new TestSmartPtr[2]); pTest[1].greet(); TempSmart temp; cout << "Finished" << endl; // after this, memory is automatically cleaned up. When the variables go out of scope. }
[ "Kajal_Varma@intuit.com" ]
Kajal_Varma@intuit.com
0588c3835baf0aadba693b6091babc53e6f32619
6647e0e5df82385b52b61290b5a1d5f7bf128292
/libkram/eastl/include/EASTL/vector_multiset.h
399b2fb0e93179ec68e5af9165fd7deffdc5c6d5
[ "Unlicense", "Apache-2.0", "MIT" ]
permissive
asdlei99/kram
3f4dad9cb982c64894ed92dc2be1a86d2ba81eb3
cad0a407ba28329dd38dbdcfd300acd404660556
refs/heads/main
2023-08-16T06:42:04.087175
2021-10-12T05:58:14
2021-10-12T05:58:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
29,288
h
/////////////////////////////////////////////////////////////////////////////// // Copyright (c) Electronic Arts Inc. All rights reserved. ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// // This file implements vector_multiset. It acts much like std::multiset, except // its underlying representation is a random access container such as vector. // These containers are sometimes also known as "sorted vectors." // vector_sets have an advantage over conventional sets in that their memory // is contiguous and node-less. The result is that lookups are faster, more // cache friendly (which potentially more so benefits speed), and the container // uses less memory. The downside is that inserting new items into the container // is slower if they are inserted in random order instead of in sorted order. // This tradeoff is well-worth it for many cases. Note that vector_multiset allows // you to use a deque or other random access container which may perform // better for you than vector. // // Note that with vector_set, vector_multiset, vector_map, vector_multimap // that the modification of the container potentially invalidates all // existing iterators into the container, unlike what happens with conventional // sets and maps. ////////////////////////////////////////////////////////////////////////////// #pragma once #include <EASTL/internal/config.h> #include <EASTL/allocator.h> #include <EASTL/functional.h> #include <EASTL/vector.h> #include <EASTL/utility.h> #include <EASTL/algorithm.h> #include <EASTL/initializer_list.h> #include <stddef.h> namespace eastl { /// EASTL_VECTOR_MULTISET_DEFAULT_NAME /// /// Defines a default container name in the absence of a user-provided name. /// #ifndef EASTL_VECTOR_MULTISET_DEFAULT_NAME #define EASTL_VECTOR_MULTISET_DEFAULT_NAME EASTL_DEFAULT_NAME_PREFIX " vector_multiset" // Unless the user overrides something, this is "EASTL vector_multiset". #endif /// EASTL_VECTOR_MULTISET_DEFAULT_ALLOCATOR /// #ifndef EASTL_VECTOR_MULTISET_DEFAULT_ALLOCATOR #define EASTL_VECTOR_MULTISET_DEFAULT_ALLOCATOR allocator_type(EASTL_VECTOR_MULTISET_DEFAULT_NAME) #endif /// vector_multiset /// /// Implements a multiset via a random access container such as a vector. /// This container is also known as a sorted_vector. We choose to call it /// vector_multiset, as that is a more consistent universally applicable name /// for it in this library. /// /// Note that with vector_set, vector_multiset, vector_map, vector_multimap /// that the modification of the container potentially invalidates all /// existing iterators into the container, unlike what happens with conventional /// sets and maps. /// /// To consider: std::multiset has the limitation that values in the set cannot /// be modified, with the idea that modifying them would change their sort /// order. We have the opportunity to make it so that values can be modified /// via changing iterators to be non-const, with the downside being that /// the container can get screwed up if the user screws up. Alternatively, /// we can do what std STL does and require the user to make their stored /// classes use 'mutable' as needed. See the C++ standard defect report /// #103 (DR 103) for a discussion of this. /// /// Note that the erase functions return iterator and not void. This allows for /// more efficient use of the container and is consistent with the C++ language /// defect report #130 (DR 130) /// template <typename Key, typename Compare = eastl::less<Key>, typename Allocator = EASTLAllocatorType, typename RandomAccessContainer = eastl::vector<Key, Allocator> > class vector_multiset : public RandomAccessContainer { public: typedef RandomAccessContainer base_type; typedef vector_multiset<Key, Compare, Allocator, RandomAccessContainer> this_type; typedef Allocator allocator_type; typedef Key key_type; typedef Key value_type; typedef Compare key_compare; typedef Compare value_compare; typedef value_type* pointer; typedef const value_type* const_pointer; typedef value_type& reference; typedef const value_type& const_reference; typedef typename base_type::size_type size_type; typedef typename base_type::difference_type difference_type; typedef typename base_type::iterator iterator; // **Currently typedefing from iterator instead of const_iterator due to const issues **: Note that we typedef from const_iterator. This is by design, as sets are sorted and values cannot be modified. To consider: allow values to be modified and thus risk changing their sort values. typedef typename base_type::const_iterator const_iterator; typedef typename base_type::reverse_iterator reverse_iterator; // See notes directly above regarding const_iterator. typedef typename base_type::const_reverse_iterator const_reverse_iterator; using base_type::begin; using base_type::end; using base_type::get_allocator; protected: value_compare mCompare; // To consider: Declare this instead as: 'key_compare mKeyCompare' public: // We have an empty ctor and a ctor that takes an allocator instead of one for both // because this way our RandomAccessContainer wouldn't be required to have an constructor // that takes allocator_type. vector_multiset(); explicit vector_multiset(const allocator_type& allocator); explicit vector_multiset(const key_compare& comp, const allocator_type& allocator = EASTL_VECTOR_MULTISET_DEFAULT_ALLOCATOR); vector_multiset(const this_type& x); vector_multiset(this_type&& x); vector_multiset(this_type&& x, const allocator_type& allocator); vector_multiset(std::initializer_list<value_type> ilist, const key_compare& compare = key_compare(), const allocator_type& allocator = EASTL_VECTOR_MULTISET_DEFAULT_ALLOCATOR); template <typename InputIterator> vector_multiset(InputIterator first, InputIterator last); // allocator arg removed because VC7.1 fails on the default arg. To do: Make a second version of this function without a default arg. template <typename InputIterator> vector_multiset(InputIterator first, InputIterator last, const key_compare& compare); // allocator arg removed because VC7.1 fails on the default arg. To do: Make a second version of this function without a default arg. this_type& operator=(const this_type& x); this_type& operator=(std::initializer_list<value_type> ilist); this_type& operator=(this_type&& x); void swap(this_type& x); const key_compare& key_comp() const; key_compare& key_comp(); const value_compare& value_comp() const; value_compare& value_comp(); // Inherited from base class: // // allocator_type& get_allocator(); // void set_allocator(const allocator_type& allocator); // // iterator begin(); // const_iterator begin() const; // const_iterator cbegin() const; // // iterator end(); // const_iterator end() const; // const_iterator cend() const; // // reverse_iterator rbegin(); // const_reverse_iterator rbegin() const; // const_reverse_iterator crbegin() const; // // reverse_iterator rend(); // const_reverse_iterator rend() const; // const_reverse_iterator crend() const; // // size_type size() const; // bool empty() const; // void clear(); template <class... Args> iterator emplace(Args&&... args); template <class... Args> iterator emplace_hint(const_iterator position, Args&&... args); iterator insert(const value_type& value); // The signature of this function was change in EASTL v2.05.00 from (the mistaken) pair<iterator, bool> to (the correct) iterator. iterator insert(const_iterator position, const value_type& value); iterator insert(const_iterator position, value_type&& value); void insert(std::initializer_list<value_type> ilist); template <typename P> iterator insert(P&& otherValue); template <typename InputIterator> void insert(InputIterator first, InputIterator last); iterator erase(const_iterator position); iterator erase(const_iterator first, const_iterator last); size_type erase(const key_type& k); reverse_iterator erase(const_reverse_iterator position); reverse_iterator erase(const_reverse_iterator first, const_reverse_iterator last); iterator find(const key_type& k); const_iterator find(const key_type& k) const; template <typename U, typename BinaryPredicate> iterator find_as(const U& u, BinaryPredicate predicate); template <typename U, typename BinaryPredicate> const_iterator find_as(const U& u, BinaryPredicate predicate) const; size_type count(const key_type& k) const; iterator lower_bound(const key_type& k); const_iterator lower_bound(const key_type& k) const; iterator upper_bound(const key_type& k); const_iterator upper_bound(const key_type& k) const; eastl::pair<iterator, iterator> equal_range(const key_type& k); eastl::pair<const_iterator, const_iterator> equal_range(const key_type& k) const; /// equal_range_small /// This is a special version of equal_range which is optimized for the /// case of there being few or no duplicated keys in the tree. eastl::pair<iterator, iterator> equal_range_small(const key_type& k) { // Defined inline because VC7.1 is broken for when it's defined outside. const iterator itLower(lower_bound(k)); iterator itUpper(itLower); while((itUpper != end()) && !mCompare(k, *itUpper)) ++itUpper; return eastl::pair<iterator, iterator>(itLower, itUpper); } eastl::pair<const_iterator, const_iterator> equal_range_small(const key_type& k) const; // Functions which are disallowed due to being unsafe. void push_back(const value_type& value) = delete; reference push_back() = delete; void* push_back_uninitialized() = delete; template <class... Args> reference emplace_back(Args&&...) = delete; // NOTE(rparolin): It is undefined behaviour if user code fails to ensure the container // invariants are respected by performing an explicit call to 'sort' before any other // operations on the container are performed that do not clear the elements. // // 'push_back_unsorted' and 'emplace_back_unsorted' do not satisfy container invariants // for being sorted. We provide these overloads explicitly labelled as '_unsorted' as an // optimization opportunity when batch inserting elements so users can defer the cost of // sorting the container once when all elements are contained. This was done to clarify // the intent of code by leaving a trace that a manual call to sort is required. // template <typename... Args> decltype(auto) push_back_unsorted(Args&&... args) { return base_type::push_back(eastl::forward<Args>(args)...); } template <typename... Args> decltype(auto) emplace_back_unsorted(Args&&... args) { return base_type::emplace_back(eastl::forward<Args>(args)...); } }; // vector_multiset /////////////////////////////////////////////////////////////////////// // vector_multiset /////////////////////////////////////////////////////////////////////// template <typename K, typename C, typename A, typename RAC> inline vector_multiset<K, C, A, RAC>::vector_multiset() : base_type(), mCompare(C()) { get_allocator().set_name(EASTL_VECTOR_MULTISET_DEFAULT_NAME); } template <typename K, typename C, typename A, typename RAC> inline vector_multiset<K, C, A, RAC>::vector_multiset(const allocator_type& allocator) : base_type(allocator), mCompare(C()) { // Empty } template <typename K, typename C, typename A, typename RAC> inline vector_multiset<K, C, A, RAC>::vector_multiset(const key_compare& comp, const allocator_type& allocator) : base_type(allocator), mCompare(comp) { // Empty } template <typename K, typename C, typename A, typename RAC> template <typename InputIterator> inline vector_multiset<K, C, A, RAC>::vector_multiset(InputIterator first, InputIterator last) : base_type(EASTL_VECTOR_MULTISET_DEFAULT_ALLOCATOR), mCompare(key_compare()) { insert(first, last); } template <typename K, typename C, typename A, typename RAC> template <typename InputIterator> inline vector_multiset<K, C, A, RAC>::vector_multiset(InputIterator first, InputIterator last, const key_compare& compare) : base_type(EASTL_VECTOR_MULTISET_DEFAULT_ALLOCATOR), mCompare(compare) { insert(first, last); } template <typename K, typename C, typename A, typename RAC> inline vector_multiset<K, C, A, RAC>::vector_multiset(const this_type& x) : base_type(x), mCompare(x.mCompare) { // Empty } template <typename K, typename C, typename A, typename RAC> inline vector_multiset<K, C, A, RAC>::vector_multiset(this_type&& x) : base_type(eastl::move(x)), mCompare(x.mCompare) { // Empty. Note: x is left with empty contents but its original mValueCompare instead of the default one. } template <typename K, typename C, typename A, typename RAC> inline vector_multiset<K, C, A, RAC>::vector_multiset(this_type&& x, const allocator_type& allocator) : base_type(eastl::move(x), allocator), mCompare(x.mCompare) { // Empty. Note: x is left with empty contents but its original mValueCompare instead of the default one. } template <typename K, typename C, typename A, typename RAC> inline vector_multiset<K, C, A, RAC>::vector_multiset(std::initializer_list<value_type> ilist, const key_compare& compare, const allocator_type& allocator) : base_type(allocator), mCompare(compare) { insert(ilist.begin(), ilist.end()); } template <typename K, typename C, typename A, typename RAC> inline vector_multiset<K, C, A, RAC>& vector_multiset<K, C, A, RAC>::operator=(const this_type& x) { base_type::operator=(x); mCompare = value_compare(x.mCompare); return *this; } template <typename K, typename C, typename A, typename RAC> inline vector_multiset<K, C, A, RAC>& vector_multiset<K, C, A, RAC>::operator=(this_type&& x) { base_type::operator=(eastl::move(x)); eastl::swap(mCompare, x.mCompare); return *this; } template <typename K, typename C, typename A, typename RAC> inline vector_multiset<K, C, A, RAC>& vector_multiset<K, C, A, RAC>::operator=(std::initializer_list<value_type> ilist) { base_type::clear(); insert(ilist.begin(), ilist.end()); return *this; } template <typename K, typename C, typename A, typename RAC> inline void vector_multiset<K, C, A, RAC>::swap(this_type& x) { base_type::swap(x); eastl::swap(mCompare, x.mCompare); } template <typename K, typename C, typename A, typename RAC> inline const typename vector_multiset<K, C, A, RAC>::key_compare& vector_multiset<K, C, A, RAC>::key_comp() const { return mCompare; } template <typename K, typename C, typename A, typename RAC> inline typename vector_multiset<K, C, A, RAC>::key_compare& vector_multiset<K, C, A, RAC>::key_comp() { return mCompare; } template <typename K, typename C, typename A, typename RAC> inline const typename vector_multiset<K, C, A, RAC>::value_compare& vector_multiset<K, C, A, RAC>::value_comp() const { return mCompare; } template <typename K, typename C, typename A, typename RAC> inline typename vector_multiset<K, C, A, RAC>::value_compare& vector_multiset<K, C, A, RAC>::value_comp() { return mCompare; } template <typename K, typename C, typename A, typename RAC> template <class... Args> typename vector_multiset<K, C, A, RAC>::iterator vector_multiset<K, C, A, RAC>::emplace(Args&&... args) { #if EASTL_USE_FORWARD_WORKAROUND auto value = value_type(eastl::forward<Args>(args)...); // Workaround for compiler bug in VS2013 which results in a compiler internal crash while compiling this code. #else value_type value(eastl::forward<Args>(args)...); #endif return insert(eastl::move(value)); } template <typename K, typename C, typename A, typename RAC> template <class... Args> typename vector_multiset<K, C, A, RAC>::iterator vector_multiset<K, C, A, RAC>::emplace_hint(const_iterator position, Args&&... args) { #if EASTL_USE_FORWARD_WORKAROUND auto value = value_type(eastl::forward<Args>(args)...); // Workaround for compiler bug in VS2013 which results in a compiler internal crash while compiling this code. #else value_type value(eastl::forward<Args>(args)...); #endif return insert(position, eastl::move(value)); } template <typename K, typename C, typename A, typename RAC> inline typename vector_multiset<K, C, A, RAC>::iterator vector_multiset<K, C, A, RAC>::insert(const value_type& value) { const iterator itUB(upper_bound(value)); return base_type::insert(itUB, value); } template <typename K, typename C, typename A, typename RAC> template <typename P> typename vector_multiset<K, C, A, RAC>::iterator vector_multiset<K, C, A, RAC>::insert(P&& otherValue) { value_type value(eastl::forward<P>(otherValue)); const iterator itUB(upper_bound(value)); return base_type::insert(itUB, eastl::move(value)); } template <typename K, typename C, typename A, typename RAC> inline void vector_multiset<K, C, A, RAC>::insert(std::initializer_list<value_type> ilist) { insert(ilist.begin(), ilist.end()); } template <typename K, typename C, typename A, typename RAC> inline typename vector_multiset<K, C, A, RAC>::iterator vector_multiset<K, C, A, RAC>::insert(const_iterator position, const value_type& value) { // We assume that the user knows what he is doing and has supplied us with // a position that is right where value should be inserted (put in front of). // We do a test to see if the position is correct. If so then we insert, // if not then we ignore the input position. However, if((position == end()) || !mCompare(*position, value)) // If value is <= the element at position... { if((position == begin()) || !mCompare(value, *(position - 1))) // If value is >= the element before position... return base_type::insert(position, value); } // In this case we have an incorrect position. We fall back to the regular insert function. return insert(value); } template <typename K, typename C, typename A, typename RAC> typename vector_multiset<K, C, A, RAC>::iterator vector_multiset<K, C, A, RAC>::insert(const_iterator position, value_type&& value) { if((position == end()) || !mCompare(*position, value)) // If value is <= the element at position... { if((position == begin()) || !mCompare(value, *(position - 1))) // If value is >= the element before position... return base_type::insert(position, eastl::move(value)); } // In this case we have an incorrect position. We fall back to the regular insert function. return insert(eastl::move(value)); } template <typename K, typename C, typename A, typename RAC> template <typename InputIterator> inline void vector_multiset<K, C, A, RAC>::insert(InputIterator first, InputIterator last) { // To consider: Improve the speed of this by getting the length of the // input range and resizing our container to that size // before doing the insertions. We can't use reserve // because we don't know if we are using a vector or not. // Alternatively, force the user to do the reservation. // To consider: When inserting values that come from a container // like this container, use the property that they are // known to be sorted and speed up the inserts here. for(; first != last; ++first) base_type::insert(upper_bound(*first), *first); } template <typename K, typename C, typename A, typename RAC> inline typename vector_multiset<K, C, A, RAC>::iterator vector_multiset<K, C, A, RAC>::erase(const_iterator position) { // Note that we return iterator and not void. This allows for more efficient use of // the container and is consistent with the C++ language defect report #130 (DR 130) return base_type::erase(position); } template <typename K, typename C, typename A, typename RAC> inline typename vector_multiset<K, C, A, RAC>::iterator vector_multiset<K, C, A, RAC>::erase(const_iterator first, const_iterator last) { return base_type::erase(first, last); } template <typename K, typename C, typename A, typename RAC> inline typename vector_multiset<K, C, A, RAC>::reverse_iterator vector_multiset<K, C, A, RAC>::erase(const_reverse_iterator position) { return reverse_iterator(base_type::erase((++position).base())); } template <typename K, typename C, typename A, typename RAC> inline typename vector_multiset<K, C, A, RAC>::reverse_iterator vector_multiset<K, C, A, RAC>::erase(const_reverse_iterator first, const_reverse_iterator last) { return reverse_iterator(base_type::erase((++last).base(), (++first).base())); } template <typename K, typename C, typename A, typename RAC> inline typename vector_multiset<K, C, A, RAC>::size_type vector_multiset<K, C, A, RAC>::erase(const key_type& k) { const eastl::pair<iterator, iterator> pairIts(equal_range(k)); if(pairIts.first != pairIts.second) base_type::erase(pairIts.first, pairIts.second); return (size_type)eastl::distance(pairIts.first, pairIts.second); // This can result in any value >= 0. } template <typename K, typename C, typename A, typename RAC> inline typename vector_multiset<K, C, A, RAC>::iterator vector_multiset<K, C, A, RAC>::find(const key_type& k) { const eastl::pair<iterator, iterator> pairIts(equal_range(k)); return (pairIts.first != pairIts.second) ? pairIts.first : end(); } template <typename K, typename C, typename A, typename RAC> template <typename U, typename BinaryPredicate> inline typename vector_multiset<K, C, A, RAC>::iterator vector_multiset<K, C, A, RAC>::find_as(const U& u, BinaryPredicate predicate) { const eastl::pair<iterator, iterator> pairIts(eastl::equal_range(begin(), end(), u, predicate)); return (pairIts.first != pairIts.second) ? pairIts.first : end(); } template <typename K, typename C, typename A, typename RAC> template <typename U, typename BinaryPredicate> inline typename vector_multiset<K, C, A, RAC>::const_iterator vector_multiset<K, C, A, RAC>::find_as(const U& u, BinaryPredicate predicate) const { const eastl::pair<const_iterator, const_iterator> pairIts(eastl::equal_range(begin(), end(), u, predicate)); return (pairIts.first != pairIts.second) ? pairIts.first : end(); } template <typename K, typename C, typename A, typename RAC> inline typename vector_multiset<K, C, A, RAC>::const_iterator vector_multiset<K, C, A, RAC>::find(const key_type& k) const { const eastl::pair<const_iterator, const_iterator> pairIts(equal_range(k)); return (pairIts.first != pairIts.second) ? pairIts.first : end(); } template <typename K, typename C, typename A, typename RAC> inline typename vector_multiset<K, C, A, RAC>::size_type vector_multiset<K, C, A, RAC>::count(const key_type& k) const { const eastl::pair<const_iterator, const_iterator> pairIts(equal_range(k)); return (size_type)eastl::distance(pairIts.first, pairIts.second); } template <typename K, typename C, typename A, typename RAC> inline typename vector_multiset<K, C, A, RAC>::iterator vector_multiset<K, C, A, RAC>::lower_bound(const key_type& k) { return eastl::lower_bound(begin(), end(), k, mCompare); } template <typename K, typename C, typename A, typename RAC> inline typename vector_multiset<K, C, A, RAC>::const_iterator vector_multiset<K, C, A, RAC>::lower_bound(const key_type& k) const { return eastl::lower_bound(begin(), end(), k, mCompare); } template <typename K, typename C, typename A, typename RAC> inline typename vector_multiset<K, C, A, RAC>::iterator vector_multiset<K, C, A, RAC>::upper_bound(const key_type& k) { return eastl::upper_bound(begin(), end(), k, mCompare); } template <typename K, typename C, typename A, typename RAC> inline typename vector_multiset<K, C, A, RAC>::const_iterator vector_multiset<K, C, A, RAC>::upper_bound(const key_type& k) const { return eastl::upper_bound(begin(), end(), k, mCompare); } template <typename K, typename C, typename A, typename RAC> inline eastl::pair<typename vector_multiset<K, C, A, RAC>::iterator, typename vector_multiset<K, C, A, RAC>::iterator> vector_multiset<K, C, A, RAC>::equal_range(const key_type& k) { return eastl::equal_range(begin(), end(), k, mCompare); } template <typename K, typename C, typename A, typename RAC> inline eastl::pair<typename vector_multiset<K, C, A, RAC>::const_iterator, typename vector_multiset<K, C, A, RAC>::const_iterator> vector_multiset<K, C, A, RAC>::equal_range(const key_type& k) const { return eastl::equal_range(begin(), end(), k, mCompare); } /* // VC++ fails to compile this when defined here, saying the function isn't a memgber of vector_multimap. template <typename K, typename C, typename A, typename RAC> inline eastl::pair<typename vector_multiset<K, C, A, RAC>::iterator, typename vector_multiset<K, C, A, RAC>::iterator> vector_multiset<K, C, A, RAC>::equal_range_small(const key_type& k) { const iterator itLower(lower_bound(k)); iterator itUpper(itLower); while((itUpper != end()) && !mCompare(k, *itUpper)) ++itUpper; return eastl::pair<iterator, iterator>(itLower, itUpper); } */ template <typename K, typename C, typename A, typename RAC> inline eastl::pair<typename vector_multiset<K, C, A, RAC>::const_iterator, typename vector_multiset<K, C, A, RAC>::const_iterator> vector_multiset<K, C, A, RAC>::equal_range_small(const key_type& k) const { const const_iterator itLower(lower_bound(k)); const_iterator itUpper(itLower); while((itUpper != end()) && !mCompare(k, *itUpper)) ++itUpper; return eastl::pair<const_iterator, const_iterator>(itLower, itUpper); } /////////////////////////////////////////////////////////////////////////// // global operators /////////////////////////////////////////////////////////////////////////// template <typename Key, typename Compare, typename Allocator, typename RandomAccessContainer> inline bool operator==(const vector_multiset<Key, Compare, Allocator, RandomAccessContainer>& a, const vector_multiset<Key, Compare, Allocator, RandomAccessContainer>& b) { return (a.size() == b.size()) && eastl::equal(b.begin(), b.end(), a.begin()); } template <typename Key, typename Compare, typename Allocator, typename RandomAccessContainer> inline bool operator<(const vector_multiset<Key, Compare, Allocator, RandomAccessContainer>& a, const vector_multiset<Key, Compare, Allocator, RandomAccessContainer>& b) { return eastl::lexicographical_compare(a.begin(), a.end(), b.begin(), b.end(), a.value_comp()); } template <typename Key, typename Compare, typename Allocator, typename RandomAccessContainer> inline bool operator!=(const vector_multiset<Key, Compare, Allocator, RandomAccessContainer>& a, const vector_multiset<Key, Compare, Allocator, RandomAccessContainer>& b) { return !(a == b); } template <typename Key, typename Compare, typename Allocator, typename RandomAccessContainer> inline bool operator>(const vector_multiset<Key, Compare, Allocator, RandomAccessContainer>& a, const vector_multiset<Key, Compare, Allocator, RandomAccessContainer>& b) { return b < a; } template <typename Key, typename Compare, typename Allocator, typename RandomAccessContainer> inline bool operator<=(const vector_multiset<Key, Compare, Allocator, RandomAccessContainer>& a, const vector_multiset<Key, Compare, Allocator, RandomAccessContainer>& b) { return !(b < a); } template <typename Key, typename Compare, typename Allocator, typename RandomAccessContainer> inline bool operator>=(const vector_multiset<Key, Compare, Allocator, RandomAccessContainer>& a, const vector_multiset<Key, Compare, Allocator, RandomAccessContainer>& b) { return !(a < b); } template <typename Key, typename Compare, typename Allocator, typename RandomAccessContainer> inline void swap(vector_multiset<Key, Compare, Allocator, RandomAccessContainer>& a, vector_multiset<Key, Compare, Allocator, RandomAccessContainer>& b) { a.swap(b); } } // namespace eastl
[ "alecmiller@yahoo.com" ]
alecmiller@yahoo.com
32f36458fb426a081b6394ec7f23f0c05c2a9510
1316b85727f58f258c72b846c1fff1bf4bdbe762
/build-watchman-Desktop_Qt_5_12_2_MinGW_64_bit-Debug/ui_niveles.h
69f62af5ac91044791a7bdd5e8203abde562fb51
[]
no_license
JohanMora73/Watchman
326e7eab312e33f45fffb60d5d0dcb6b987faa48
d4f20475b2bbcbd5c5c5cec6b939925413a8289b
refs/heads/master
2023-03-03T02:42:10.285475
2021-02-05T21:56:12
2021-02-05T21:56:12
326,210,984
0
0
null
null
null
null
UTF-8
C++
false
false
3,485
h
/******************************************************************************** ** Form generated from reading UI file 'niveles.ui' ** ** Created by: Qt User Interface Compiler version 5.12.2 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_NIVELES_H #define UI_NIVELES_H #include <QtCore/QVariant> #include <QtWidgets/QApplication> #include <QtWidgets/QGraphicsView> #include <QtWidgets/QMainWindow> #include <QtWidgets/QMenuBar> #include <QtWidgets/QPushButton> #include <QtWidgets/QStatusBar> #include <QtWidgets/QWidget> QT_BEGIN_NAMESPACE class Ui_Niveles { public: QWidget *centralwidget; QGraphicsView *graphicsView; QPushButton *pushButton; QPushButton *pushButton_2; QPushButton *pushButton_3; QMenuBar *menubar; QStatusBar *statusbar; void setupUi(QMainWindow *Niveles) { if (Niveles->objectName().isEmpty()) Niveles->setObjectName(QString::fromUtf8("Niveles")); Niveles->resize(300, 250); Niveles->setMinimumSize(QSize(300, 250)); Niveles->setMaximumSize(QSize(300, 250)); centralwidget = new QWidget(Niveles); centralwidget->setObjectName(QString::fromUtf8("centralwidget")); graphicsView = new QGraphicsView(centralwidget); graphicsView->setObjectName(QString::fromUtf8("graphicsView")); graphicsView->setGeometry(QRect(0, 0, 300, 240)); graphicsView->setMinimumSize(QSize(300, 240)); graphicsView->setMaximumSize(QSize(300, 200)); pushButton = new QPushButton(centralwidget); pushButton->setObjectName(QString::fromUtf8("pushButton")); pushButton->setGeometry(QRect(90, 30, 111, 41)); QFont font; font.setFamily(QString::fromUtf8("Comic Sans MS")); font.setPointSize(14); font.setBold(true); font.setWeight(75); pushButton->setFont(font); pushButton_2 = new QPushButton(centralwidget); pushButton_2->setObjectName(QString::fromUtf8("pushButton_2")); pushButton_2->setGeometry(QRect(90, 90, 111, 41)); pushButton_2->setFont(font); pushButton_3 = new QPushButton(centralwidget); pushButton_3->setObjectName(QString::fromUtf8("pushButton_3")); pushButton_3->setGeometry(QRect(90, 150, 111, 41)); pushButton_3->setFont(font); Niveles->setCentralWidget(centralwidget); menubar = new QMenuBar(Niveles); menubar->setObjectName(QString::fromUtf8("menubar")); menubar->setGeometry(QRect(0, 0, 300, 20)); Niveles->setMenuBar(menubar); statusbar = new QStatusBar(Niveles); statusbar->setObjectName(QString::fromUtf8("statusbar")); Niveles->setStatusBar(statusbar); retranslateUi(Niveles); QMetaObject::connectSlotsByName(Niveles); } // setupUi void retranslateUi(QMainWindow *Niveles) { Niveles->setWindowTitle(QApplication::translate("Niveles", "MainWindow", nullptr)); pushButton->setText(QApplication::translate("Niveles", "Nivel 1", nullptr)); pushButton_2->setText(QApplication::translate("Niveles", "Nivel 2", nullptr)); pushButton_3->setText(QApplication::translate("Niveles", "salir", nullptr)); } // retranslateUi }; namespace Ui { class Niveles: public Ui_Niveles {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_NIVELES_H
[ "johan.morar@udea.edu.co" ]
johan.morar@udea.edu.co
2dd1b2cc3ba40d94e304379ec58a2e4712d3edfe
0b9f6534a99ff551f0006df78a24e8af30340580
/Source/ChartProj/ChartMaker_TCP/main.cpp
c58b274b0d275a900ef7ae3b45ee04be5515de5d
[]
no_license
jayirum/ChartProjSvr
9bac49865d1e081de0cbd7559d0d2cbdd26279c2
d69edfcb3ac3698e1bdfcf5862d5e63bb305cb52
refs/heads/master
2020-03-24T03:22:18.176911
2019-07-05T01:38:03
2019-07-05T01:38:03
142,416,528
1
1
null
null
null
null
UHC
C++
false
false
17,217
cpp
#pragma warning(disable:4786) #pragma warning(disable:4503) #include "../../IRUM_UTIL/TcpClient.h" #include "ChartMaker.h" #include "../../IRUM_UTIL/ADOFunc.h" #include "main.h" #include <winsvc.h> #include <stdio.h> #include <time.h> #include "../../IRUM_UTIL/util.h" #include "../../IRUM_UTIL/Prop.h" #include "../../IRUM_UTIL/MemPool.h" #include "../../IRUM_UTIL/LogMsg.h" //#include "../../IRUM_UTIL/NanoPubSub.h" #include "../../IRUM_UTIL/IRUM_Common.h" #include <list> #include <map> #include <string> #include <Windows.h> //서비스 메인 본체 void __stdcall ServiceStart(DWORD argc, LPTSTR* argv); //서비스 제어 void __stdcall SCMHandler(DWORD opcode); //서비스 환경 설정 void __stdcall SetStatus(DWORD dwState, DWORD dwAccept = SERVICE_ACCEPT_STOP|SERVICE_ACCEPT_PAUSE_CONTINUE); void install(); void uninstall(); SC_HANDLE hScm ; SC_HANDLE hSrv ; SERVICE_STATUS ss; PSECURITY_DESCRIPTOR pSD; // Pointer to SD. SECURITY_ATTRIBUTES sa; //DWORD m_dwThrID; //쓰레드 아이디 SERVICE_STATUS_HANDLE g_hXSS; //서비스 환경 글로벌 핸들 DWORD g_XSS; //서비스 현재 상태 저장변수 BOOL g_bDebug; HANDLE g_hDieEvent; // 프로그램 전체를 끝내는 이벤트 volatile BOOL g_bContinue = TRUE; // 프로그램 전체를 끝내는 플래그 char g_zConfig[_MAX_PATH]; char g_zMsg[1024]; BOOL DBOpen(); BOOL LoadSymbol(); BOOL InitApiClient(); BOOL InitMemPool(); static unsigned WINAPI RecvMDThread(LPVOID lp); void RecvMDThreadFn(); static unsigned WINAPI ChartSaveThread(LPVOID lp); CRITICAL_SECTION g_Console; CLogMsg g_log; CDBPoolAdo *g_ado = NULL; CTcpClient *g_pApiRecv = NULL; CMemPool *g_pMemPool = NULL; HANDLE g_hRecvThread = NULL, g_hSaveThread = NULL; unsigned int g_unRecvThread = 0, g_unSaveThread = 0; std::map<std::string, CChartMaker*> g_mapSymbol; char SERVICENAME[128], DISPNAME[128], DESC[128]; int _Start() { char msg[512] = { 0, }; char szDir[_MAX_PATH]; char szNotificationServer[32], szNotificationPort[32]; CUtil::GetConfig(g_zConfig, "DIR", "LOG", szDir); CUtil::GetConfig(g_zConfig, "NOTIFICATION", "NOTIFICATION_SERVER_IP", szNotificationServer); CUtil::GetConfig(g_zConfig, "NOTIFICATION", "NOTIFICATION_SERVER_PORT", szNotificationPort); g_log.OpenLogEx(szDir, EXENAME, szNotificationServer, atoi(szNotificationPort), SERVICENAME); g_log.log(LOGTP_SUCC, "-----------------------------------------------------"); g_log.log(LOGTP_SUCC, "Version[%s]%s", __DATE__, __APP_VERSION); g_log.log(LOGTP_SUCC, "-----------------------------------------------------"); printf("Version[%s]%s\n", __DATE__, __APP_VERSION); //--------------------------------------------- // 프로그램 전체를 끝내는 이벤트 //--------------------------------------------- g_hDieEvent = CreateEvent(&sa, TRUE, FALSE, NULL); if (g_bDebug) { //CUtil::LogPrint(&g_log, TRUE, "**************************\n"); //CUtil::LogPrint(&g_log, TRUE, "** 서비스를 시작합니다. **\n"); //CUtil::LogPrint(&g_log, TRUE, "**************************\n"); } else { SetStatus(SERVICE_RUNNING); //log.LogEventInf(-1," 서비스를 시작합니다."); } if (!InitMemPool()) { return 0; } if (!DBOpen()) { g_log.log(NOTIFY, "Failed to connect to DB"); return 0; } while (!InitApiClient() ) { if (!g_bContinue) return 0; g_log.log(NOTIFY, "Failed to connect to API server"); Sleep(10000); continue; } // 차트 저장 스레드 g_hRecvThread = (HANDLE)_beginthreadex(NULL, 0, &RecvMDThread, NULL, 0, &g_unRecvThread); g_hSaveThread = (HANDLE)_beginthreadex(NULL, 0, &ChartSaveThread, NULL, 0, &g_unSaveThread); if (!LoadSymbol()) { g_log.log(NOTIFY, "Failed to LoadSymbol"); return 0; } DWORD ret = WaitForSingleObject(g_hDieEvent, INFINITE); std::map<std::string, CChartMaker*>::iterator it; for (it = g_mapSymbol.begin(); it != g_mapSymbol.end();it++) { CChartMaker* p = (*it).second; delete p; } //printf("----------------1\n"); //SAFE_DELETE(g_ado); //printf("----------------2\n"); //SAFE_DELETE(g_pApiRecv); //printf("----------------3\n"); //SAFE_CLOSEHANDLE(g_hRecvThread); //printf("----------------4\n"); //SAFE_CLOSEHANDLE(g_hSaveThread); //printf("----------------5\n"); //SAFE_DELETE(g_pMemPool); //printf("----------------6\n"); CoUninitialize(); return 0; } BOOL InitMemPool() { g_pMemPool = new CMemPool(MEM_PRE_ALLOC, MEM_MAX_ALLOC, MEM_BLOCK_SIZE); if(g_pMemPool->available()==0) { return FALSE; } return TRUE; } static unsigned WINAPI RecvMDThread(LPVOID lp) { __try { RecvMDThreadFn(); } __except (ReportException(GetExceptionCode(), "RecvMDThread", g_zMsg)) { g_log.log(LOGTP_FATAL, g_zMsg); exit(0); } return 0; } void RecvMDThreadFn() { ST_PACK2CHART_EX* pSise; char zSymbol[128]; while (g_bContinue) { Sleep(1); if (g_pApiRecv->HappenedRecvError()) { g_log.log(LOGTP_ERR, "TCP RECV ERROR:%s", g_pApiRecv->GetMsg()); printf("TCP RECV ERROR:%s\n", g_pApiRecv->GetMsg()); continue; } char* pBuf = NULL;; if (!g_pMemPool->get(&pBuf)) { g_log.log(LOGTP_ERR, "memory pool get error"); printf("memory pool get error\n"); continue; } int nLen = g_pApiRecv->GetOneRecvedPacket(pBuf); if (nLen == 0){ g_pMemPool->release(pBuf); continue; } if (nLen < 0) { g_log.log(LOGTP_ERR, "PAKCET Error(%s)(%s)", pBuf, g_pApiRecv->GetMsg()); //printf("PAKCET Error(%s)\n", g_pApiRecv->GetMsg()); g_pMemPool->release(pBuf); continue; } if (nLen > 0) { pSise = (ST_PACK2CHART_EX*)pBuf; char tm[9]; sprintf(tm, "%.2s:%.2s:%.2s", pSise->Time, pSise->Time + 2, pSise->Time + 4); memcpy(pSise->Time, tm, sizeof(pSise->Time)); sprintf(zSymbol, "%.*s", sizeof(pSise->ShortCode), pSise->ShortCode); CUtil::TrimAll(zSymbol, strlen(zSymbol)); //ir_cvtcode_uro_6e(zSymbol, zTemp); std::string sSymbol = zSymbol; //printf("%s\n", zSymbol); std::map<std::string, CChartMaker*>::iterator it = g_mapSymbol.find(sSymbol); if (it == g_mapSymbol.end()) { g_pMemPool->release(pBuf); } else { CChartMaker* p = (*it).second; PostThreadMessage(p->GetChartThreadId(), WM_RECV_API_MD, 0, (LPARAM)pBuf); } } } return ; } static unsigned WINAPI ChartSaveThread(LPVOID lp) { char zQ[1024]; char zGroupKey[LEN_GROUP_KEY + 1]; while (g_bContinue) { Sleep(1); MSG msg; while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { if (msg.message == WM_SAVE_CHART) { ST_SHM_CHART_UNIT* p = (ST_SHM_CHART_UNIT*)msg.lParam; sprintf(zGroupKey, "%.*s", LEN_GROUP_KEY, p->Reserved); CDBHandlerAdo db(g_ado->Get()); sprintf(zQ, "EXEC CHART_SAVE " "'%.*s', " //@I_GROUP_KEY VARCHAR(5)--// CLN71 "'%.*s', " //@I_STK_CD "'%.*s', " //, @I_CHART_NM VARCHAR(20) "'%.*s', " //, @I_PREV_NM VARCHAR(20) "'%.*s', " //@I_CHART_GB CHAR(1)--// +,-, 0 "'%.*s', " //@I_OPEN_PRC VARCHAR(20) "'%.*s', " //@I_HIGH_PRC VARCHAR(20) "'%.*s', " //@I_LOW_PRC VARCHAR(20) "'%.*s', " //@I_CLOSE_PRC VARCHAR(20) "'%.*s', " //@I_CNTR_QTY VARCHAR(20) "'%.*s', " //@I_DOT_CNT VARCHAR(20) "'%.*s', " //@I_SMA_SHORT VARCHAR(20) "'%.*s', " //@I_SMA_LONG VARCHAR(20) "'%.*s' " //@I_SMA_SHORT_5 VARCHAR(20) , LEN_GROUP_KEY, zGroupKey, sizeof(p->stk_cd), p->stk_cd, sizeof(p->Nm), p->Nm, sizeof(p->prevNm), p->prevNm, sizeof(p->gb), p->gb, sizeof(p->open), p->open, sizeof(p->high), p->high, sizeof(p->low), p->low, sizeof(p->close), p->close, sizeof(p->cntr_qty), p->cntr_qty, sizeof(p->dotcnt), p->dotcnt, sizeof(p->sma_short), p->sma_short, sizeof(p->sma_long), p->sma_long, sizeof(p->sma_shortest), p->sma_shortest ); if (FALSE == db->ExecQuery(zQ)) { g_log.log(LOGTP_ERR, "CHART DATA Save err(%s)(%s)", db->GetError(), zQ); //printf("CHART DATA Save 에러(%s)(%s)\n", db->GetError(), zQ); } else { //g_log.log(LOGTP_SUCC, "DB SAVE(%s)", zQ); } delete p; db->Close(); } //if (msg.message == WM_SAVE_CHART) } // while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) } // while (TRUE) return 0; } BOOL DBOpen() { char ip[32], id[32], pwd[32], cnt[32], name[32]; CUtil::GetConfig(g_zConfig, "DBINFO", "DB_IP", ip); CUtil::GetConfig(g_zConfig, "DBINFO", "DB_ID", id); CUtil::GetConfig(g_zConfig, "DBINFO", "DB_PWD", pwd); CUtil::GetConfig(g_zConfig, "DBINFO", "DB_NAME", name); CUtil::GetConfig(g_zConfig, "DBINFO", "DB_POOL_CNT", cnt); g_ado = new CDBPoolAdo(ip, id, pwd, name); if (!g_ado->Init(atoi(cnt))) { g_log.log(LOGTP_ERR, "DB OPEN FAIL(MSG:%s)", g_ado->GetMsg()); g_log.log(LOGTP_ERR, "(IP:%s)(ID:%s)(PWD:%s)(DB:%s)", ip, id, pwd, name); SAFE_DELETE(g_ado); return FALSE; } g_log.log(LOGTP_SUCC, "DB OPEN OK(IP:%s)(ID:%s)(PWD:%s)(DB:%s)", ip, id, pwd, name); return TRUE; } /* ALTER PROCEDURE [dbo].[AA_GET_SYMBOL] -- Add the parameters for the stored procedure here AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON; SELECT API_CD,STK_CD,STK_NM,ARTC_CD,DOT_CNT,TICK_SIZE FROM AA_STK_MST WHERE USE_YN = 'Y' SET NOCOUNT OFF */ BOOL LoadSymbol() { CDBHandlerAdo db(g_ado->Get()); char zStkCdQry[1024]; strcpy(zStkCdQry, "EXEC AA_GET_SYMBOL"); if (!db->ExecQuery(zStkCdQry)) { g_log.log(LOGTP_ERR, "GET SYMBOL ERROR()%s)(%s)", zStkCdQry, db->GetError()); return FALSE; } char saveYn[32], yearLen[32], euroDollar[32]; CUtil::GetConfig(g_zConfig, "CHART_SAVE", "SAVEONDB", saveYn); CUtil::GetConfig(g_zConfig, "SYMBOL_TYPE", "YEAR_LENGTH", yearLen); CUtil::GetConfig(g_zConfig, "SYMBOL_TYPE", "EURO_DOLLAR", euroDollar); char zSymbol[32], zArtc[32]; int nDotCnt = 0; while (db->IsNextRow()) { db->GetStr("ARTC_CD", zArtc); db->GetStr("STK_CD", zSymbol); nDotCnt = db->GetLong("DOT_CNT"); //TODO //if (strncmp(zArtc, "6A", 2) != 0) { // db->Next(); // continue; //} std::string symbol = zSymbol; CChartMaker* p = new CChartMaker(zSymbol, zArtc, nDotCnt, g_unSaveThread, (saveYn[0]=='Y')); g_mapSymbol[symbol] = p; g_log.log(LOGTP_SUCC, "[%s][%s] Chart Symbol", zArtc, zSymbol); printf("[%s][%s] 차트구성종목\n", zArtc, zSymbol); db->Next(); } db->Close(); return TRUE; } BOOL InitApiClient() { // API 로 부터 시세 수신 char zIP[32], port[32]; CUtil::GetConfig(g_zConfig, "CHART_SOCKET_INFO", "IP", zIP); CUtil::GetConfig(g_zConfig, "CHART_SOCKET_INFO", "PORT", port); printf("API IP(%s)PORT(%s)", zIP, port); g_pApiRecv = new CTcpClient("ChartMaker"); if (!g_pApiRecv->Begin(zIP, atoi(port), 10)) { g_log.log(LOGTP_FATAL, "%s", g_pApiRecv->GetMsg()); return FALSE; } else g_log.log(LOGTP_SUCC, "TCP CLIENT Initialize and connect OK(IP:%s)(PORT:%s)", zIP, port); g_pApiRecv->StartRecvData(); return TRUE; } BOOL WINAPI ControlHandler ( DWORD dwCtrlType ) { switch( dwCtrlType ) { case CTRL_BREAK_EVENT: // use Ctrl+C or Ctrl+Break to simulate case CTRL_C_EVENT: // SERVICE_CONTROL_STOP in debug mode case CTRL_CLOSE_EVENT: case CTRL_LOGOFF_EVENT: case CTRL_SHUTDOWN_EVENT: printf("Stopping %s...\n", DISPNAME); SetEvent(g_hDieEvent); g_bContinue = FALSE; return TRUE; break; } return FALSE; } int main(int argc, LPSTR *argv) { g_bDebug = FALSE; CHAR szDir[_MAX_PATH]; // GET LOG DIR CProp prop; prop.SetBaseKey(HKEY_LOCAL_MACHINE, IRUM_DIRECTORY); strcpy(szDir, prop.GetValue("CONFIG_DIR_CHART")); CUtil::GetCnfgFileNm(szDir, EXENAME, g_zConfig); CUtil::GetConfig(g_zConfig, "SERVICE", "SERVICE_NAME", SERVICENAME); CUtil::GetConfig(g_zConfig, "SERVICE", "DISP_NAME", DISPNAME); CUtil::GetConfig(g_zConfig, "SERVICE", "DESC", DESC); if ((argc > 1) && ((*argv[1] == '-') || (*argv[1] == '/'))) { if (_stricmp("install", argv[1] + 1) == 0) { install(); } else if (_stricmp("remove", argv[1] + 1) == 0 || _stricmp("delete", argv[1] + 1) == 0) { uninstall(); } else if (_stricmp("debug", argv[1] + 1) == 0) { g_bDebug = TRUE; SetConsoleCtrlHandler(ControlHandler, TRUE); InitializeCriticalSection(&g_Console); _Start(); DeleteCriticalSection(&g_Console); printf("Stopped.\n"); return 0; } else { return 0; } } SERVICE_TABLE_ENTRY stbl[] = { { SERVICENAME, (LPSERVICE_MAIN_FUNCTION)ServiceStart }, { NULL, NULL } }; if (!StartServiceCtrlDispatcher(stbl)) { return -1; } return 0; } void __stdcall SetStatus(DWORD dwState, DWORD dwAccept) { ss.dwServiceType = SERVICE_WIN32_OWN_PROCESS; ss.dwCurrentState = dwState; ss.dwControlsAccepted = SERVICE_ACCEPT_STOP; ss.dwWin32ExitCode = 0; ss.dwServiceSpecificExitCode = 0; ss.dwCheckPoint = 0; ss.dwWaitHint = 0; g_XSS = dwState; //현재 상태 보관 SetServiceStatus(g_hXSS, &ss); return ; } void __stdcall SCMHandler(DWORD opcode) { if(opcode == g_XSS) return; switch(opcode) { case SERVICE_CONTROL_PAUSE: SetStatus(SERVICE_PAUSE_PENDING,0); SetStatus(SERVICE_PAUSED); break; case SERVICE_CONTROL_CONTINUE: SetStatus(SERVICE_CONTINUE_PENDING, 0); break; case SERVICE_CONTROL_STOP: case SERVICE_CONTROL_SHUTDOWN: SetStatus(SERVICE_STOP_PENDING, 0); SetEvent(g_hDieEvent); g_bContinue = FALSE; break; case SERVICE_CONTROL_INTERROGATE: break; default: SetStatus(g_XSS); break; } } void __stdcall ServiceStart(DWORD argc, LPTSTR* argv) { g_hXSS = RegisterServiceCtrlHandler(SERVICENAME, (LPHANDLER_FUNCTION)SCMHandler); if(g_hXSS ==0) { //log.LogEventErr(-1,"서비스 컨트롤 핸들러를 등록할 수 없습니다."); return ; } //서비스가 시작 중임을 알린다 SetStatus(SERVICE_START_PENDING); //// Allocate memory for the security descriptor. pSD = (PSECURITY_DESCRIPTOR) LocalAlloc( LPTR //Specifies how to allocate memory // Allocates fixed memory && Initializes memory contents to zero. ,SECURITY_DESCRIPTOR_MIN_LENGTH //number of bytes to allocate ); //// Initialize the new security descriptor. InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION); //// Add a NULL descriptor ACL to the security descriptor. SetSecurityDescriptorDacl(pSD, TRUE, (PACL) NULL, FALSE); sa.nLength = sizeof(sa); sa.lpSecurityDescriptor = pSD; sa.bInheritHandle = TRUE; g_bDebug = FALSE; _Start(); //서비스 실행 //log.LogEventInf(-1,"서비스가 정상적으로 종료했습니다."); SetStatus(SERVICE_STOPPED, 0); ///서비스 멈춤 return; } void install() { char SrvPath[MAX_PATH]; SERVICE_DESCRIPTION lpDes; char Desc[64]; strcpy(Desc, SERVICENAME); strcat(Desc, " Service"); hScm = OpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE); if(hScm == NULL) { //log.LogEventErr(-1, "서비스 메니져와 연결할 수 없습니다"); return ; } GetCurrentDirectory(MAX_PATH, SrvPath); strcat(SrvPath, "\\"); strcat(SrvPath, EXENAME); //sprintf(SrvPath, "D:\\IBSSERVER(BACKUPSYSTEM)\\RealShmUP\\Release\\RealShmUP.exe"); if(_access(SrvPath, 0) != 0) { CloseServiceHandle(hScm); //log.LogEventErr(-1, "서비스 프로그램이 같은 디렉토리에 없습니다"); printf("There is no service process in same directory"); return; } //// 종속 서비스 CHAR szDir[_MAX_PATH]; char szDependency[64] = { 0, }; CProp prop; prop.SetBaseKey(HKEY_LOCAL_MACHINE, IRUM_DIRECTORY); strcpy(szDir, prop.GetValue("CONFIG_DIR_CHART")); CUtil::GetCnfgFileNm(szDir, EXENAME, g_zConfig); CUtil::GetConfig(g_zConfig, "SERVICE", "DEPENDENCY", szDependency); hSrv = CreateService(hScm, SERVICENAME, DISPNAME, SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, SrvPath, NULL, NULL, szDependency, NULL, NULL); if(hSrv == NULL) { printf("Failed to install the service : %d\n", GetLastError()); } else { lpDes.lpDescription = Desc; ChangeServiceConfig2(hSrv, SERVICE_CONFIG_DESCRIPTION, &lpDes); printf("Succeeded in installing the service.(dependency:%s)\n", szDependency); CloseServiceHandle(hSrv); } CloseServiceHandle(hScm); } void uninstall() { hScm = OpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE); if(hScm == NULL) { //log.LogEventErr(-1, "서비스 메니져와 연결할 수 없습니다"); printf("Can't connect to SCM\n"); return; } hSrv = OpenService(hScm, SERVICENAME, SERVICE_ALL_ACCESS); if(hSrv == NULL) { CloseServiceHandle(hScm); //log.LogEventErr(-1, "서비스가 설치되어 있지 않습니다"); printf("Service is not installed: %d\n", GetLastError()); return ; } //서비스 중지 QueryServiceStatus(hSrv, &ss); if(ss.dwCurrentState != SERVICE_STOPPED) { ControlService(hSrv, SERVICE_CONTROL_STOP, &ss); Sleep(2000); } //서비스 제거 if(DeleteService(hSrv)) { //log.LogEventInf(-1, "성공적으로 서비스를 제거했습니다"); printf("Succeeded in removing the service \n"); } else{ printf("Failed in removing the service\n"); } CloseServiceHandle(hSrv); CloseServiceHandle(hScm); }
[ "jay.bwkim@gmail.com" ]
jay.bwkim@gmail.com
16cbba561bc05742ebce08bc6e89ba721e6a52f7
bc251acb2f67530b2cfbff50af776bcce208ee90
/TOKEN2.CPP
7b7e2c41e25ff455385f02d505da4a15de18b142
[]
no_license
bhavinnirmal29/C_CPP_Programs
707459d6e96c322029929943c44e4c31f920f5aa
ef5609ff0e48ff4c815b37d2d4bcff7414ea5d43
refs/heads/master
2020-06-03T10:37:56.242045
2019-06-12T09:12:40
2019-06-12T09:12:40
191,537,470
3
0
null
null
null
null
UTF-8
C++
false
false
893
cpp
#include<iostream.h> #include<conio.h> #include<string.h> void main() { char a[50]; int i,n,token=1,beg=0,end,loc; int y; clrscr(); printf("enter the string\n"); gets(a); n=strlen(a); printf("string lenght is %d\n",n); printf("token=1\n"); for(i=0;i<n;i++) { loc=i; if(a[i]!=' ') { printf("%c",a[i]); } if(a[i]==' '|| a[i+1]=='\0') { if((a[beg]>=65 && a[beg]<=91) || (a[beg]>=97 && a[loc]<=122)) { printf("\tvariable"); printf("\n"); } if(a[beg]>='0' && a[beg]<='9' || a[beg]>=33 &&a[beg]<=47) { if(a[loc-1]>='0' && a[loc-1]<='9') { printf("\tliteral\n"); } else if(a[loc-1]>=33 && a[loc-1]<=47) { printf("Symbols"); } else { printf("Invalid\n"); } } beg=loc+1; loc=i+1; if(i+1==n) { break; } token++; printf("\ntoken=%d\n",token); } } getch(); }
[ "bhavinnirmal29@gmail.com" ]
bhavinnirmal29@gmail.com
8a51751f597b04f70872c12c101223840fa18a44
f5ecd45ff4c65f4805a580cfe9f58426bc610511
/src/P2p/P2pProtocolTypes.h
c891c94c027323124a3706775cda7407c6352a5a
[ "MIT" ]
permissive
JacopoDT/numerare-core
3d0f115f4f557439ce821842abb32e5a22fd99af
a98b32150a9b2e6ea7535d12b7e8e1aac0589e2f
refs/heads/master
2021-06-28T08:32:45.221794
2020-08-30T23:50:22
2020-08-30T23:50:22
131,741,111
0
0
null
null
null
null
UTF-8
C++
false
false
2,435
h
/*** MIT License Copyright (c) 2018 NUMERARE 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. Parts of this file are originally Copyright (c) 2012-2017 The CryptoNote developers, The Bytecoin developers ***/ #pragma once #include <string.h> #include <tuple> #include <boost/uuid/uuid.hpp> #include "Common/StringTools.h" namespace CryptoNote { typedef boost::uuids::uuid uuid; typedef boost::uuids::uuid net_connection_id; typedef uint64_t PeerIdType; #pragma pack (push, 1) struct NetworkAddress { uint32_t ip; uint32_t port; }; struct PeerlistEntry { NetworkAddress adr; PeerIdType id; uint64_t last_seen; }; struct connection_entry { NetworkAddress adr; PeerIdType id; bool is_income; }; #pragma pack(pop) inline bool operator < (const NetworkAddress& a, const NetworkAddress& b) { return std::tie(a.ip, a.port) < std::tie(b.ip, b.port); } inline bool operator == (const NetworkAddress& a, const NetworkAddress& b) { return memcmp(&a, &b, sizeof(a)) == 0; } inline std::ostream& operator << (std::ostream& s, const NetworkAddress& na) { return s << Common::ipAddressToString(na.ip) << ":" << std::to_string(na.port); } inline uint32_t hostToNetwork(uint32_t n) { return (n << 24) | (n & 0xff00) << 8 | (n & 0xff0000) >> 8 | (n >> 24); } inline uint32_t networkToHost(uint32_t n) { return hostToNetwork(n); // the same } }
[ "38866023+numerare@users.noreply.github.com" ]
38866023+numerare@users.noreply.github.com
39e0192e97156808b75b886f6c3bcfa0db97ad05
c561904995db136c5880b97ca39ad8d497f069a9
/MathLib/collider.cpp
9fc888f19f973f30efef0b136f37c2315f820ce9
[]
no_license
William-Quinn-Bentjen/Dont-Fall
a9b8fb8bf306bbff6367cd4870e66fc8f977d1a6
f56ea670141b36251653e5ef373ada626a2e8878
refs/heads/master
2021-08-22T08:33:21.460984
2017-11-29T19:09:47
2017-11-29T19:09:47
110,878,579
0
0
null
null
null
null
UTF-8
C++
false
false
194
cpp
#include "collider.h" Collision collides(const Transform & at, const Collider & ac, const Transform & bt, const Collider & bc) { return isect_AABB(ac.getGlobalBox(at), bc.getGlobalBox(bt)); }
[ "s179051@SEA-8D0AB9" ]
s179051@SEA-8D0AB9
7ee39b7a4a4a579086a452fa14db36a2ab1e94e4
1fd30b1df13d20666edddc0f83f7ae517c00ee4f
/recurssion/replacePi.cpp
ee743c61eaf18fae934737d6011949103442413a
[]
no_license
manalarora/coding-blocks-online-questions
0d93b0a1d458fe2c7143788363ba76b07524aa27
0b60bb28ed11ab844eccd3fda0024d7fb37d196a
refs/heads/master
2020-04-21T07:09:19.293649
2019-02-11T19:07:42
2019-02-11T19:07:42
169,385,383
3
1
null
null
null
null
UTF-8
C++
false
false
625
cpp
#include <iostream> #include <string> using namespace std; void format(char* in, char* out, int i, int j){ if(in[i]==NULL){ out[j]='\0'; cout<<out<<endl; return; } if(in[i]=='p' && in[i+1]=='i'){ out[j] = '3'; out[j+1]='.'; out[j+2]='1'; out[j+3]='4'; format(in, out, i+2, j+4); } else{ out[j]=in[i]; format(in, out, i+1, j+1); } } int main() { int test; cin>>test; for(int i=0;i<test;i++){ char input[100] ; cin>>input; char output[100]; format(input,output, 0,0); } return 0; }
[ "manalarora21@gmail.com" ]
manalarora21@gmail.com
2a30b5e84420007d0488d5f6ea5d96f7c39ac080
e2d981a21d9316e8bde61ba0e4633d6e3bf39471
/[obsolete][develop]nba2k_shotchart_project/ref_hackbase/HackBase/dxgihook.cpp
16ef9db935b372eced31bd45e35bc11ab3bba0b1
[ "MIT" ]
permissive
wxngzhxxg/Daily_GUI_Tools
c66ff82e7992f7d985ee69afab49a4d1116623ce
dfb5a62066dab2c48ea34dd773323f9063c39b2b
refs/heads/master
2022-02-27T20:34:59.492453
2019-07-19T17:38:45
2019-07-19T17:38:45
208,992,423
0
0
MIT
2019-09-17T07:52:33
2019-09-17T07:52:32
null
UTF-8
C++
false
false
3,859
cpp
#include "hackbase.h" DXGIHook *mSingleton = 0; HackBase *mDXGIBase = 0; DXGIHook *DXGIHook::Singleton() { mDXGIBase = HackBase::Singleton(); if(!mSingleton) { if(mDXGIBase) mSingleton = new DXGIHook(); else dbglogln("Error creating DXGIHook!"); } return mSingleton; } typedef HRESULT (__stdcall* DXGIPresent_t)(IDXGISwapChain *SwapChain, UINT SyncInterval, UINT Flags); DXGIPresent_t pDXGIPresent; DWORD Present = NULL; DWORD SwapChain = NULL; bool DXGIFailedGettingSwapChain = false; HRESULT __stdcall hkDXGIPresent(IDXGISwapChain *pSwapChain, UINT SyncInterval, UINT Flags) { __asm pushad static bool FirstRun = true; if(FirstRun) { FirstRun = false; ID3D10Device *pD3D10Device = 0; ID3D11Device *pD3D11Device = 0; if(!FAILED(pSwapChain->GetDevice(__uuidof(pD3D11Device), (void**)&pD3D11Device))) { SAFE_RELEASE(pD3D11Device); mDXGIBase->setD3DVersion(D3DVersion_D3D11); mDXGIBase->setRenderer(new D3D11Renderer(pSwapChain)); } else if(!FAILED(pSwapChain->GetDevice(__uuidof(pD3D10Device), (void**)&pD3D10Device))) { SAFE_RELEASE(pD3D10Device); mDXGIBase->setD3DVersion(D3DVersion_D3D10); mDXGIBase->setRenderer(new D3D10Renderer(pSwapChain)); } } else { if(mDXGIBase->getRenderer()) { mDXGIBase->getRenderer()->BeginScene(); if(pSwapChain) { switch(mDXGIBase->getD3DVersion()) { case D3DVersion_D3D10: ((D3D10Renderer*)mDXGIBase->getRenderer())->RefreshData(pSwapChain); break; case D3DVersion_D3D11: ((D3D11Renderer*)mDXGIBase->getRenderer())->RefreshData(pSwapChain); break; } } if(mDXGIBase->mOnRender) mDXGIBase->mOnRender(mDXGIBase->getRenderer()); mDXGIBase->getRenderer()->EndScene(); } else { dbglogln("Unable to render: Renderer == NULL"); MessageBox(0, "Error!", "", 0); ExitProcess(0); } } __asm popad return pDXGIPresent(pSwapChain, SyncInterval, Flags); } LRESULT CALLBACK DXGIMsgProc(HWND hwnd,UINT uMsg,WPARAM wParam,LPARAM lParam){return DefWindowProc(hwnd, uMsg, wParam, lParam);} DXGIHook::DXGIHook() { if(Imports::Singleton()->D3D10CreateDeviceAndSwapChain) { IDXGISwapChain *pSwapChain = 0; ID3D11Device *pDevice = 0; WNDCLASSEXA wc = {sizeof(WNDCLASSEX),CS_CLASSDC,DXGIMsgProc,0L,0L,GetModuleHandleA(NULL),NULL,NULL,NULL,NULL,"DX",NULL}; RegisterClassExA(&wc); HWND hWnd = CreateWindowA("DX",NULL,WS_OVERLAPPEDWINDOW,100,100,300,300,NULL,NULL,wc.hInstance,NULL); DXGI_SWAP_CHAIN_DESC swapChainDesc; ZeroMemory(&swapChainDesc, sizeof(swapChainDesc)); swapChainDesc.BufferCount = 1; swapChainDesc.BufferDesc.Width = 1; swapChainDesc.BufferDesc.Height = 1; swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; swapChainDesc.OutputWindow = hWnd; swapChainDesc.SampleDesc.Count = 1; swapChainDesc.SampleDesc.Quality = 0; swapChainDesc.Windowed = TRUE; if(!FAILED(Imports::Singleton()->D3D10CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_REFERENCE, NULL, NULL, D3D10_SDK_VERSION, &swapChainDesc, &pSwapChain, &pDevice))) { DWORD *pVTable = (DWORD*)pSwapChain; pVTable = (DWORD*)pVTable[0]; Present = pVTable[8]; } SAFE_RELEASE(pSwapChain); SAFE_RELEASE(pDevice); DestroyWindow(hWnd); } if(!Present) return; DWORD hookAddress = CheckPointer(Present); #ifdef DEBUGLOG if(hookAddress != Present) { dbglogln("Hooking IDXGISwapChain::Present\nat [0x%08X -> 0x%08X]", Present, hookAddress); } else { dbglogln("Hooking IDXGISwapChain::Present\nat [0x%08X]", Present); } #endif pDXGIPresent = (DXGIPresent_t)DetourCreate((LPVOID)hookAddress, hkDXGIPresent, DETOUR_TYPE_PUSH_RET); } DXGIHook::~DXGIHook() { if(pDXGIPresent) { #ifdef DEBUGLOG dbglogln("Removing IDXGISwapChain::Present public hook"); #endif DetourRemove(pDXGIPresent); pDXGIPresent = NULL; } }
[ "cht@bupt.edu.cn" ]
cht@bupt.edu.cn
e4c430a3abe514f78959a45c56ca9e47ac65e312
9c88726209d8aec7e8f61009a83858252cdac815
/main.cpp
dc3e2b26b07f9a35a414399a2b9baf01491b9a39
[]
no_license
ana-henao/parcial2
0182b1645f6708492fca7c12709c3141111c98ac
70f65a8f14717bee57ed307c4517ee4316dee8ef
refs/heads/master
2023-01-29T22:00:52.685867
2020-12-14T01:02:03
2020-12-14T01:02:03
320,861,389
0
0
null
null
null
null
UTF-8
C++
false
false
2,649
cpp
#include <iostream> #include <math.h> #include"batalla.h" #define G 9.81 #define pi 3.141617 using namespace std; batalla batalla_=batalla(); void DisparoOfensivoEfectivo (int Voo){ canionDefensivo disparoD=canionDefensivo(); canionOfensivo disparoO=canionOfensivo(); Impacto impactoEfectivo=batalla_.DisparoOfensivo(disparoD, disparoO, Voo, false); cout <<"disparo ofensivo efectivo"<< endl; impactoEfectivo.ImprimirResultados1(); Impacto impactoDefensivo=batalla_.DisparoDefensivo2(disparoD,disparoO,Voo,impactoEfectivo.getangle(),impactoEfectivo.getV0o(),false); cout <<"disparo defensivo que compromete la efectividad del ataque ofensivo"<< endl; impactoDefensivo.ImprimirResultados1(); cout <<"disparos que neutralizan el ataque defensivo" <<endl; batalla_.DisparoOfensivo2(disparoD,disparoO, Voo,impactoDefensivo.getangle(),impactoDefensivo.getV0o()); } int main() { int Voo,opcion; cout<<"Simulador de disparos. "<<endl; cout <<"Ingrese Vo desde la cual quiere probar: "<<endl; cin >> Voo; cout <<"Seleccione una opcion: "<<endl; cout <<"1.disparos ofensivos que comprometen la integridad del canion defensivo. "<<endl; cout <<"2.disparos defensivos que comprometen la integridad del canion ofensivo. "<<endl; cout <<"3.disparos defensivos que impidan que el canion defensivo sea destruido "<<endl; cout <<"4.disparos defensivos que impidan que los caniones defensivo y ofensivo puedan ser destruidos."<<endl; cout <<"5.disparos que neutralicen el ataque defensivo y permitan que el ataque ofensivo sea efectivo."<<endl; cin>>opcion; canionDefensivo disparoDefensivo=canionDefensivo(); canionOfensivo disparoOfensivo=canionOfensivo(); canionDefensivo disparoDefensivo1=canionDefensivo(); canionOfensivo disparoOfensivo1=canionOfensivo(); while(opcion <=5){ if (opcion==1){ batalla_.DisparoOfensivo(disparoDefensivo, disparoOfensivo, Voo, true); break; } else if (opcion==2){ batalla_.DisparoDefensivo(disparoDefensivo, disparoOfensivo, Voo); break; } else if(opcion==3){ batalla_.DisparoDefensivo2(disparoDefensivo, disparoOfensivo,Voo,31,85,true); break; } else if(opcion==4){ batalla_.DisparoOfensivo2(disparoDefensivo,disparoOfensivo, Voo, 150,109); //break; } else if(opcion==5){ DisparoOfensivoEfectivo(Voo); break; } else{ cout <<"La opcion ingresada no existe."<< endl; } } return 0; }
[ "ana.henao8@udea.edu.co" ]
ana.henao8@udea.edu.co
4ad537d77f98d88d510d334fd78d0f70a09f3848
c016ae565f787f84720f96a43d14b897b26f92af
/gdb-tutorial/child.cpp
ba6ea987dd758d71501cb7599181eb1cc868f2da
[]
no_license
jpevarnek/turnt-tribble
9bacd6653e25e85fc8894d3087b656dae73feaa3
a8e7869aea81205b980ab8338ecbd1a8c9c71c56
refs/heads/master
2021-01-19T08:37:54.481227
2013-10-04T14:58:35
2013-10-04T14:58:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
334
cpp
#include <iostream> #include <csignal> #include <cstdlib> void *child(void *arg) { std::cout << "Entering child" << std::endl; int a = rand(); /* the two lines below are just to make explaining gdb easier */ signal(SIGUSR1, SIG_IGN); raise(SIGUSR1); std::cout << "Exiting child, a was " << a << std::endl; return NULL; }
[ "pevarnj@gmail.com" ]
pevarnj@gmail.com
d65b63d2b5b58dbca0dd97c3dd436c4e40d2bc8c
73cfd700522885a3fec41127e1f87e1b78acd4d3
/_Include/boost/fusion/functional/invocation/invoke_function_object.hpp
f63b123459e67173dc610723f27eacbb970ef9d6
[ "BSL-1.0" ]
permissive
pu2oqa/muServerDeps
88e8e92fa2053960671f9f57f4c85e062c188319
92fcbe082556e11587887ab9d2abc93ec40c41e4
refs/heads/master
2023-03-15T12:37:13.995934
2019-02-04T10:07:14
2019-02-04T10:07:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,707
hpp
/*============================================================================= Copyright (c) 2005-2006 Joao Abecasis Copyright (c) 2006-2007 Tobias Schwinger Use modification and distribution are subject to the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt). ==============================================================================*/ #if !defined(BOOST_FUSION_FUNCTIONAL_INVOCATION_INVOKE_FUNCTION_OBJECT_HPP_INCLUDED) #if !defined(BOOST_PP_IS_ITERATING) #include <boost/preprocessor/cat.hpp> #include <boost/preprocessor/iteration/iterate.hpp> #include <boost/preprocessor/arithmetic/dec.hpp> #include <boost/preprocessor/repetition/repeat_from_to.hpp> #include <boost/preprocessor/repetition/enum.hpp> #include <boost/preprocessor/repetition/enum_params.hpp> #include <boost/utility/result_of.hpp> #include <boost/type_traits/remove_reference.hpp> #include <boost/type_traits/remove_const.hpp> #include <boost/utility/result_of.hpp> #include <boost/fusion/support/category_of.hpp> #include <boost/fusion/support/detail/enabler.hpp> #include <boost/fusion/sequence/intrinsic/size.hpp> #include <boost/fusion/sequence/intrinsic/at.hpp> #include <boost/fusion/sequence/intrinsic/begin.hpp> #include <boost/fusion/iterator/next.hpp> #include <boost/fusion/iterator/deref.hpp> #include <boost/fusion/functional/invocation/limits.hpp> namespace boost { namespace fusion { namespace detail { template< class Function, class Sequence, int N = result_of::size<Sequence>::value, bool RandomAccess = traits::is_random_access<Sequence>::value, typename Enable = void > struct invoke_function_object_impl; template <class Sequence, int N> struct invoke_function_object_param_types; #define BOOST_PP_FILENAME_1 \ <boost/fusion/functional/invocation/invoke_function_object.hpp> #define BOOST_PP_ITERATION_LIMITS \ (0, BOOST_FUSION_INVOKE_FUNCTION_OBJECT_MAX_ARITY) #include BOOST_PP_ITERATE() } namespace result_of { template <class Function, class Sequence, class Enable = void> struct invoke_function_object; template <class Function, class Sequence> struct invoke_function_object<Function, Sequence, typename detail::enabler< typename detail::invoke_function_object_impl< typename boost::remove_reference<Function>::type, Sequence >::result_type >::type> { typedef typename detail::invoke_function_object_impl< typename boost::remove_reference<Function>::type, Sequence >::result_type type; }; } template <class Function, class Sequence> BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED inline typename result_of::invoke_function_object<Function,Sequence>::type invoke_function_object(Function f, Sequence & s) { return detail::invoke_function_object_impl< typename boost::remove_reference<Function>::type,Sequence >::call(f,s); } template <class Function, class Sequence> BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED inline typename result_of::invoke_function_object<Function,Sequence const>::type invoke_function_object(Function f, Sequence const & s) { return detail::invoke_function_object_impl< typename boost::remove_reference<Function>::type,Sequence const >::call(f,s); } }} #define BOOST_FUSION_FUNCTIONAL_INVOCATION_INVOKE_FUNCTION_OBJECT_HPP_INCLUDED #else // defined(BOOST_PP_IS_ITERATING) /////////////////////////////////////////////////////////////////////////////// // // Preprocessor vertical repetition code // /////////////////////////////////////////////////////////////////////////////// #define N BOOST_PP_ITERATION() #define M(z,j,data) \ typename result_of::at_c<Sequence,j>::type template <class Function, class Sequence> struct invoke_function_object_impl<Function,Sequence,N,true, typename enabler< typename boost::result_of<Function (BOOST_PP_ENUM(N,M,~)) >::type >::type> { public: typedef typename boost::result_of< Function (BOOST_PP_ENUM(N,M,~)) >::type result_type; #undef M #if N > 0 template <class F> BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED static inline result_type call(F & f, Sequence & s) { #define M(z,j,data) fusion::at_c<j>(s) return f( BOOST_PP_ENUM(N,M,~) ); #undef M } #else template <class F> BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED static inline result_type call(F & f, Sequence & /*s*/) { return f(); } #endif }; #define M(z,j,data) \ typename invoke_function_object_param_types<Sequence,N>::T ## j template <class Function, class Sequence> struct invoke_function_object_impl<Function,Sequence,N,false, typename enabler< typename boost::result_of<Function (BOOST_PP_ENUM(N,M,~)) >::type >::type> #undef M { private: typedef invoke_function_object_param_types<Sequence,N> seq; public: typedef typename boost::result_of< Function (BOOST_PP_ENUM_PARAMS(N,typename seq::T)) >::type result_type; #if N > 0 template <class F> BOOST_CXX14_CONSTEXPR BOOST_FUSION_GPU_ENABLED static inline result_type call(F & f, Sequence & s) { typename seq::I0 i0 = fusion::begin(s); #define M(z,j,data) \ typename seq::I##j i##j = \ fusion::next(BOOST_PP_CAT(i,BOOST_PP_DEC(j))); BOOST_PP_REPEAT_FROM_TO(1,N,M,~) #undef M return f( BOOST_PP_ENUM_PARAMS(N,*i) ); } #else template <class F> BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED static inline result_type call(F & f, Sequence & /*s*/) { return f(); } #endif }; template <class Sequence> struct invoke_function_object_param_types<Sequence,N> { #if N > 0 typedef typename result_of::begin<Sequence>::type I0; typedef typename result_of::deref<I0>::type T0; #define M(z,i,data) \ typedef typename result_of::next< \ BOOST_PP_CAT(I,BOOST_PP_DEC(i))>::type I##i; \ typedef typename result_of::deref<I##i>::type T##i; BOOST_PP_REPEAT_FROM_TO(1,N,M,~) #undef M #endif }; #undef N #endif // defined(BOOST_PP_IS_ITERATING) #endif ///////////////////////////////////////////////// // vnDev.Games - Trong.LIVE - DAO VAN TRONG // ////////////////////////////////////////////////////////////////////////////////
[ "langley.joshua@gmail.com" ]
langley.joshua@gmail.com
39c692d85b0dbc48fb2727249b51e5b004d249d4
fbc8bbdf2fcafbbcf06ea87aac99aad103dfc773
/VTK/Rendering/OpenGL2/vtkOpenGLLabeledContourMapper.cxx
2d6e5872b1fa4ec5bbb6327c1e688f6ecf0ce35b
[ "BSD-3-Clause" ]
permissive
vildenst/In_Silico_Heart_Models
a6d3449479f2ae1226796ca8ae9c8315966c231e
dab84821e678f98cdd702620a3f0952699eace7c
refs/heads/master
2020-12-02T20:50:19.721226
2017-07-24T17:27:45
2017-07-24T17:27:45
96,219,496
4
0
null
null
null
null
UTF-8
C++
false
false
5,787
cxx
/*============================================================================== Program: Visualization Toolkit Module: vtkOpenGLLabeledContourMapper.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. ==============================================================================*/ #include "vtkOpenGLLabeledContourMapper.h" #include "vtkActor.h" #include "vtkMatrix4x4.h" #include "vtkObjectFactory.h" #include "vtkOpenGLActor.h" #include "vtkOpenGLCamera.h" #include "vtkOpenGLError.h" #include "vtkOpenGLRenderUtilities.h" #include "vtkOpenGLRenderWindow.h" #include "vtkOpenGLShaderCache.h" #include "vtkOpenGLTexture.h" #include "vtkRenderer.h" #include "vtkShaderProgram.h" #include "vtkTextActor3D.h" #include "vtkOpenGLHelper.h" //------------------------------------------------------------------------------ vtkStandardNewMacro(vtkOpenGLLabeledContourMapper) //------------------------------------------------------------------------------ void vtkOpenGLLabeledContourMapper::PrintSelf(std::ostream &os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); } //------------------------------------------------------------------------------ vtkOpenGLLabeledContourMapper::vtkOpenGLLabeledContourMapper() { this->StencilBO = new vtkOpenGLHelper; this->TempMatrix4 = vtkMatrix4x4::New(); } //------------------------------------------------------------------------------ vtkOpenGLLabeledContourMapper::~vtkOpenGLLabeledContourMapper() { delete this->StencilBO; this->StencilBO = 0; this->TempMatrix4->Delete(); } //------------------------------------------------------------------------------ bool vtkOpenGLLabeledContourMapper::CreateLabels(vtkActor *actor) { if (!this->Superclass::CreateLabels(actor)) { return false; } if (vtkMatrix4x4 *actorMatrix = actor->GetMatrix()) { for (vtkIdType i = 0; i < this->NumberOfUsedTextActors; ++i) { vtkMatrix4x4 *labelMatrix = this->TextActors[i]->GetUserMatrix(); vtkMatrix4x4::Multiply4x4(actorMatrix, labelMatrix, labelMatrix); this->TextActors[i]->SetUserMatrix(labelMatrix); } } return true; } //------------------------------------------------------------------------------ void vtkOpenGLLabeledContourMapper::ReleaseGraphicsResources(vtkWindow *win) { this->Superclass::ReleaseGraphicsResources(win); this->StencilBO->ReleaseGraphicsResources(win); } //------------------------------------------------------------------------------ bool vtkOpenGLLabeledContourMapper::ApplyStencil(vtkRenderer *ren, vtkActor *act) { // Draw stencil quads into stencil buffer: // compile and bind it if needed vtkOpenGLRenderWindow *renWin = vtkOpenGLRenderWindow::SafeDownCast(ren->GetVTKWindow()); if (!this->StencilBO->Program) { this->StencilBO->Program = renWin->GetShaderCache()->ReadyShaderProgram( // vertex shader "//VTK::System::Dec\n" "attribute vec4 vertexMC;\n" "uniform mat4 MCDCMatrix;\n" "void main() { gl_Position = MCDCMatrix*vertexMC; }\n", // fragment shader "//VTK::System::Dec\n" "//VTK::Output::Dec\n" "void main() { gl_FragData[0] = vec4(1.0,1.0,1.0,1.0); }", // geometry shader ""); } else { renWin->GetShaderCache()->ReadyShaderProgram(this->StencilBO->Program); } if (!this->StencilBO->Program) { return false; } // Save some state: GLboolean colorMask[4]; glGetBooleanv(GL_COLOR_WRITEMASK, colorMask); GLboolean depthMask; glGetBooleanv(GL_DEPTH_WRITEMASK, &depthMask); // Enable rendering into the stencil buffer: glEnable(GL_STENCIL_TEST); glStencilMask(0xFF); glClearStencil(0); glClear(GL_STENCIL_BUFFER_BIT); glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); glDepthMask(GL_FALSE); glStencilFunc(GL_ALWAYS, 1, 0xFF); glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE); vtkOpenGLCamera *cam = (vtkOpenGLCamera *)(ren->GetActiveCamera()); vtkMatrix4x4 *wcdc; vtkMatrix4x4 *wcvc; vtkMatrix3x3 *norms; vtkMatrix4x4 *vcdc; cam->GetKeyMatrices(ren,wcvc,norms,vcdc,wcdc); if (!act->GetIsIdentity()) { vtkMatrix4x4 *mcwc; vtkMatrix3x3 *anorms; ((vtkOpenGLActor *)act)->GetKeyMatrices(mcwc,anorms); vtkMatrix4x4::Multiply4x4(mcwc, wcdc, this->TempMatrix4); this->StencilBO->Program->SetUniformMatrix("MCDCMatrix", this->TempMatrix4); } else { this->StencilBO->Program->SetUniformMatrix("MCDCMatrix", wcdc); } vtkOpenGLRenderUtilities::RenderTriangles( this->StencilQuads, this->StencilQuadsSize/3, this->StencilQuadIndices, this->StencilQuadIndicesSize, NULL, this->StencilBO->Program, this->StencilBO->VAO); // Restore state: glColorMask(colorMask[0], colorMask[1], colorMask[2], colorMask[3]); glDepthMask(depthMask); // Setup GL to only draw in unstenciled regions: glStencilMask(0x00); glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP); glStencilFunc(GL_EQUAL, 0, 0xFF); vtkOpenGLCheckErrorMacro("failed after ApplyStencil()"); return this->Superclass::ApplyStencil(ren, act); } //------------------------------------------------------------------------------ bool vtkOpenGLLabeledContourMapper::RemoveStencil() { glDisable(GL_STENCIL_TEST); vtkOpenGLCheckErrorMacro("failed after RemoveStencil()"); return this->Superclass::RemoveStencil(); }
[ "vilde@Vildes-MBP" ]
vilde@Vildes-MBP
8b0d7c4809fa2adf643390df52ba422df1372f95
5ae94f18bf988944f79816c4f1156c434b12930f
/lib/cpp/Mutex.cpp
7cc89a197a307085c10ff3aaccd93c040c47a655
[ "BSD-2-Clause" ]
permissive
mfkiwl/osal-1
d7ce29f6197350df02001d5ea46f9ceb8dd25ce0
54d679dde284ee09a9c1034bc0241feb8a2cc48e
refs/heads/master
2023-07-28T04:48:06.452084
2021-09-12T15:17:02
2021-09-12T15:17:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,604
cpp
///////////////////////////////////////////////////////////////////////////////////// /// /// @file /// @author Kuba Sejdak /// @copyright BSD 2-Clause License /// /// Copyright (c) 2020-2021, Kuba Sejdak <kuba.sejdak@gmail.com> /// All rights reserved. /// /// Redistribution and use in source and binary forms, with or without /// modification, are permitted provided that the following conditions are met: /// /// 1. Redistributions of source code must retain the above copyright notice, this /// list of conditions and the following disclaimer. /// /// 2. Redistributions in binary form must reproduce the above copyright notice, /// this list of conditions and the following disclaimer in the documentation /// and/or other materials provided with the distribution. /// /// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" /// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE /// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE /// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE /// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL /// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR /// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER /// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, /// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE /// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /// ///////////////////////////////////////////////////////////////////////////////////// #include "osal/Mutex.hpp" #include <chrono> namespace osal { Mutex::Mutex(OsalMutexType type) { osalMutexCreate(&m_mutex, type); } Mutex::Mutex(Mutex&& other) noexcept { std::swap(m_mutex, other.m_mutex); } Mutex::~Mutex() { if (m_mutex.initialized) osalMutexDestroy(&m_mutex); } std::error_code Mutex::lock() { return osalMutexLock(&m_mutex); } std::error_code Mutex::tryLock() { return osalMutexTryLock(&m_mutex); } std::error_code Mutex::tryLockIsr() { return osalMutexTryLockIsr(&m_mutex); } std::error_code Mutex::timedLock(Timeout timeout) { std::uint32_t timeoutMs = std::chrono::duration_cast<std::chrono::milliseconds>(timeout.timeLeft()).count(); return osalMutexTimedLock(&m_mutex, timeoutMs); } std::error_code Mutex::unlock() { return osalMutexUnlock(&m_mutex); } std::error_code Mutex::unlockIsr() { return osalMutexUnlockIsr(&m_mutex); } } // namespace osal
[ "kuba.sejdak@gmail.com" ]
kuba.sejdak@gmail.com
67e3fa96d468e5eb961dcc0d522d909e22663402
801f7ed77fb05b1a19df738ad7903c3e3b302692
/optimisationRefactoring/differentiatedCAD/occt-min-topo-src/src/HLRBRep/HLRBRep_PolyAlgo.cxx
9b8d75d8701adc2707504caa43238cbb1d3c52aa
[]
no_license
salvAuri/optimisationRefactoring
9507bdb837cabe10099d9481bb10a7e65331aa9d
e39e19da548cb5b9c0885753fe2e3a306632d2ba
refs/heads/master
2021-01-20T03:47:54.825311
2017-04-27T11:31:24
2017-04-27T11:31:24
89,588,404
0
1
null
null
null
null
UTF-8
C++
false
false
128,567
cxx
// Created on: 1995-05-05 // Created by: Christophe MARION // Copyright (c) 1995-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. // Modified by cma, Tue Apr 1 11:39:48 1997 // Modified by cma, Tue Apr 1 11:40:30 1997 #include <BRep_Builder.hxx> #include <BRep_Tool.hxx> #include <BRepLib_MakeEdge.hxx> #include <CSLib.hxx> #include <CSLib_DerivativeStatus.hxx> #include <CSLib_NormalStatus.hxx> #include <Geom_RectangularTrimmedSurface.hxx> #include <Geom_Surface.hxx> #include <gp.hxx> #include <HLRAlgo_BiPoint.hxx> #include <HLRAlgo_EdgeStatus.hxx> #include <HLRAlgo_ListIteratorOfListOfBPoint.hxx> #include <HLRAlgo_PolyAlgo.hxx> #include <HLRAlgo_PolyData.hxx> #include <HLRAlgo_PolyInternalData.hxx> #include <HLRAlgo_PolyShellData.hxx> #include <HLRAlgo_Projector.hxx> #include <HLRBRep_PolyAlgo.hxx> #include <Poly_Polygon3D.hxx> #include <Poly_PolygonOnTriangulation.hxx> #include <Poly_Triangulation.hxx> #include <Precision.hxx> #include <Standard_ErrorHandler.hxx> #include <Standard_OutOfRange.hxx> #include <Standard_Stream.hxx> #include <Standard_Type.hxx> #include <TColStd_HArray1OfInteger.hxx> #include <TColStd_HArray1OfTransient.hxx> #include <TopExp.hxx> #include <TopExp_Explorer.hxx> #include <TopoDS.hxx> #include <TopoDS_Edge.hxx> #include <TopoDS_Shape.hxx> #include <TopTools_Array1OfShape.hxx> #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx> #include <TopTools_ListIteratorOfListOfShape.hxx> #define EMskOutLin1 ((Standard_Boolean) 1) #define EMskOutLin2 ((Standard_Boolean) 2) #define EMskOutLin3 ((Standard_Boolean) 4) #define EMskGrALin1 ((Standard_Boolean) 8) #define EMskGrALin2 ((Standard_Boolean) 16) #define EMskGrALin3 ((Standard_Boolean) 32) #define FMskBack ((Standard_Boolean) 64) #define FMskSide ((Standard_Boolean) 128) #define FMskHiding ((Standard_Boolean) 256) #define FMskFlat ((Standard_Boolean) 512) #define FMskOnOutL ((Standard_Boolean)1024) #define FMskOrBack ((Standard_Boolean)2048) #define FMskFrBack ((Standard_Boolean)4096) #define NMskVert ((Standard_Boolean) 1) #define NMskOutL ((Standard_Boolean) 2) #define NMskNorm ((Standard_Boolean) 4) #define NMskFuck ((Standard_Boolean) 8) #define NMskEdge ((Standard_Boolean)16) #define NMskMove ((Standard_Boolean)32) #define PntXTI1 ((Standard_Real*)Coordinates)[ 0] #define PntYTI1 ((Standard_Real*)Coordinates)[ 1] #define PntZTI1 ((Standard_Real*)Coordinates)[ 2] #define PntXTI2 ((Standard_Real*)Coordinates)[ 3] #define PntYTI2 ((Standard_Real*)Coordinates)[ 4] #define PntZTI2 ((Standard_Real*)Coordinates)[ 5] #define PntX1 ((Standard_Real*)Coordinates)[ 6] #define PntY1 ((Standard_Real*)Coordinates)[ 7] #define PntZ1 ((Standard_Real*)Coordinates)[ 8] #define PntX2 ((Standard_Real*)Coordinates)[ 9] #define PntY2 ((Standard_Real*)Coordinates)[10] #define PntZ2 ((Standard_Real*)Coordinates)[11] #define Pn2XTI1 ((Standard_Real*)Coordinate2)[ 0] #define Pn2YTI1 ((Standard_Real*)Coordinate2)[ 1] #define Pn2ZTI1 ((Standard_Real*)Coordinate2)[ 2] #define Pn2XTI2 ((Standard_Real*)Coordinate2)[ 3] #define Pn2YTI2 ((Standard_Real*)Coordinate2)[ 4] #define Pn2ZTI2 ((Standard_Real*)Coordinate2)[ 5] #define Pn2X1 ((Standard_Real*)Coordinate2)[ 6] #define Pn2Y1 ((Standard_Real*)Coordinate2)[ 7] #define Pn2Z1 ((Standard_Real*)Coordinate2)[ 8] #define Pn2X2 ((Standard_Real*)Coordinate2)[ 9] #define Pn2Y2 ((Standard_Real*)Coordinate2)[10] #define Pn2Z2 ((Standard_Real*)Coordinate2)[11] #define Tri1Node1 ((Standard_Integer*)Tri1Indices)[0] #define Tri1Node2 ((Standard_Integer*)Tri1Indices)[1] #define Tri1Node3 ((Standard_Integer*)Tri1Indices)[2] #define Tri1Flags ((Standard_Boolean*)Tri1Indices)[3] #define Tri2Node1 ((Standard_Integer*)Tri2Indices)[0] #define Tri2Node2 ((Standard_Integer*)Tri2Indices)[1] #define Tri2Node3 ((Standard_Integer*)Tri2Indices)[2] #define Tri2Flags ((Standard_Boolean*)Tri2Indices)[3] #define Tri3Node1 ((Standard_Integer*)Tri3Indices)[0] #define Tri3Node2 ((Standard_Integer*)Tri3Indices)[1] #define Tri3Node3 ((Standard_Integer*)Tri3Indices)[2] #define Tri3Flags ((Standard_Boolean*)Tri3Indices)[3] #define Seg1LstSg1 ((Standard_Integer*)Seg1Indices)[0] #define Seg1LstSg2 ((Standard_Integer*)Seg1Indices)[1] #define Seg1NxtSg1 ((Standard_Integer*)Seg1Indices)[2] #define Seg1NxtSg2 ((Standard_Integer*)Seg1Indices)[3] #define Seg1Conex1 ((Standard_Integer*)Seg1Indices)[4] #define Seg1Conex2 ((Standard_Integer*)Seg1Indices)[5] #define Seg2LstSg1 ((Standard_Integer*)Seg2Indices)[0] #define Seg2LstSg2 ((Standard_Integer*)Seg2Indices)[1] #define Seg2NxtSg1 ((Standard_Integer*)Seg2Indices)[2] #define Seg2NxtSg2 ((Standard_Integer*)Seg2Indices)[3] #define Seg2Conex1 ((Standard_Integer*)Seg2Indices)[4] #define Seg2Conex2 ((Standard_Integer*)Seg2Indices)[5] #define Nod1NdSg ((Standard_Integer*)Nod1Indices)[0] #define Nod1Flag ((Standard_Boolean*)Nod1Indices)[1] #define Nod1Edg1 ((Standard_Boolean*)Nod1Indices)[2] #define Nod1Edg2 ((Standard_Boolean*)Nod1Indices)[3] #define Nod1PntX ((Standard_Real*)Nod1RValues)[ 0] #define Nod1PntY ((Standard_Real*)Nod1RValues)[ 1] #define Nod1PntZ ((Standard_Real*)Nod1RValues)[ 2] #define Nod1PntU ((Standard_Real*)Nod1RValues)[ 3] #define Nod1PntV ((Standard_Real*)Nod1RValues)[ 4] #define Nod1NrmX ((Standard_Real*)Nod1RValues)[ 5] #define Nod1NrmY ((Standard_Real*)Nod1RValues)[ 6] #define Nod1NrmZ ((Standard_Real*)Nod1RValues)[ 7] #define Nod1PCu1 ((Standard_Real*)Nod1RValues)[ 8] #define Nod1PCu2 ((Standard_Real*)Nod1RValues)[ 9] #define Nod1Scal ((Standard_Real*)Nod1RValues)[10] #define NodANdSg ((Standard_Integer*)NodAIndices)[0] #define NodAFlag ((Standard_Boolean*)NodAIndices)[1] #define NodAEdg1 ((Standard_Boolean*)NodAIndices)[2] #define NodAEdg2 ((Standard_Boolean*)NodAIndices)[3] #define NodAPntX ((Standard_Real*)NodARValues)[ 0] #define NodAPntY ((Standard_Real*)NodARValues)[ 1] #define NodAPntZ ((Standard_Real*)NodARValues)[ 2] #define NodAPntU ((Standard_Real*)NodARValues)[ 3] #define NodAPntV ((Standard_Real*)NodARValues)[ 4] #define NodANrmX ((Standard_Real*)NodARValues)[ 5] #define NodANrmY ((Standard_Real*)NodARValues)[ 6] #define NodANrmZ ((Standard_Real*)NodARValues)[ 7] #define NodAPCu1 ((Standard_Real*)NodARValues)[ 8] #define NodAPCu2 ((Standard_Real*)NodARValues)[ 9] #define NodAScal ((Standard_Real*)NodARValues)[10] #define NodBNdSg ((Standard_Integer*)NodBIndices)[0] #define NodBFlag ((Standard_Boolean*)NodBIndices)[1] #define NodBEdg1 ((Standard_Boolean*)NodBIndices)[2] #define NodBEdg2 ((Standard_Boolean*)NodBIndices)[3] #define NodBPntX ((Standard_Real*)NodBRValues)[ 0] #define NodBPntY ((Standard_Real*)NodBRValues)[ 1] #define NodBPntZ ((Standard_Real*)NodBRValues)[ 2] #define NodBPntU ((Standard_Real*)NodBRValues)[ 3] #define NodBPntV ((Standard_Real*)NodBRValues)[ 4] #define NodBNrmX ((Standard_Real*)NodBRValues)[ 5] #define NodBNrmY ((Standard_Real*)NodBRValues)[ 6] #define NodBNrmZ ((Standard_Real*)NodBRValues)[ 7] #define NodBPCu1 ((Standard_Real*)NodBRValues)[ 8] #define NodBPCu2 ((Standard_Real*)NodBRValues)[ 9] #define NodBScal ((Standard_Real*)NodBRValues)[10] #define Nod2NdSg ((Standard_Integer*)Nod2Indices)[0] #define Nod2Flag ((Standard_Boolean*)Nod2Indices)[1] #define Nod2Edg1 ((Standard_Boolean*)Nod2Indices)[2] #define Nod2Edg2 ((Standard_Boolean*)Nod2Indices)[3] #define Nod2PntX ((Standard_Real*)Nod2RValues)[ 0] #define Nod2PntY ((Standard_Real*)Nod2RValues)[ 1] #define Nod2PntZ ((Standard_Real*)Nod2RValues)[ 2] #define Nod2PntU ((Standard_Real*)Nod2RValues)[ 3] #define Nod2PntV ((Standard_Real*)Nod2RValues)[ 4] #define Nod2NrmX ((Standard_Real*)Nod2RValues)[ 5] #define Nod2NrmY ((Standard_Real*)Nod2RValues)[ 6] #define Nod2NrmZ ((Standard_Real*)Nod2RValues)[ 7] #define Nod2PCu1 ((Standard_Real*)Nod2RValues)[ 8] #define Nod2PCu2 ((Standard_Real*)Nod2RValues)[ 9] #define Nod2Scal ((Standard_Real*)Nod2RValues)[10] #define Nod3NdSg ((Standard_Integer*)Nod3Indices)[0] #define Nod3Flag ((Standard_Boolean*)Nod3Indices)[1] #define Nod3Edg1 ((Standard_Boolean*)Nod3Indices)[2] #define Nod3Edg2 ((Standard_Boolean*)Nod3Indices)[3] #define Nod3PntX ((Standard_Real*)Nod3RValues)[ 0] #define Nod3PntY ((Standard_Real*)Nod3RValues)[ 1] #define Nod3PntZ ((Standard_Real*)Nod3RValues)[ 2] #define Nod3PntU ((Standard_Real*)Nod3RValues)[ 3] #define Nod3PntV ((Standard_Real*)Nod3RValues)[ 4] #define Nod3NrmX ((Standard_Real*)Nod3RValues)[ 5] #define Nod3NrmY ((Standard_Real*)Nod3RValues)[ 6] #define Nod3NrmZ ((Standard_Real*)Nod3RValues)[ 7] #define Nod3PCu1 ((Standard_Real*)Nod3RValues)[ 8] #define Nod3PCu2 ((Standard_Real*)Nod3RValues)[ 9] #define Nod3Scal ((Standard_Real*)Nod3RValues)[10] #define Nod4NdSg ((Standard_Integer*)Nod4Indices)[0] #define Nod4Flag ((Standard_Boolean*)Nod4Indices)[1] #define Nod4Edg1 ((Standard_Boolean*)Nod4Indices)[2] #define Nod4Edg2 ((Standard_Boolean*)Nod4Indices)[3] #define Nod4PntX ((Standard_Real*)Nod4RValues)[ 0] #define Nod4PntY ((Standard_Real*)Nod4RValues)[ 1] #define Nod4PntZ ((Standard_Real*)Nod4RValues)[ 2] #define Nod4PntU ((Standard_Real*)Nod4RValues)[ 3] #define Nod4PntV ((Standard_Real*)Nod4RValues)[ 4] #define Nod4NrmX ((Standard_Real*)Nod4RValues)[ 5] #define Nod4NrmY ((Standard_Real*)Nod4RValues)[ 6] #define Nod4NrmZ ((Standard_Real*)Nod4RValues)[ 7] #define Nod4PCu1 ((Standard_Real*)Nod4RValues)[ 8] #define Nod4PCu2 ((Standard_Real*)Nod4RValues)[ 9] #define Nod4Scal ((Standard_Real*)Nod4RValues)[10] #define Nod11NdSg ((Standard_Integer*)Nod11Indices)[0] #define Nod11Flag ((Standard_Boolean*)Nod11Indices)[1] #define Nod11Edg1 ((Standard_Boolean*)Nod11Indices)[2] #define Nod11Edg2 ((Standard_Boolean*)Nod11Indices)[3] #define Nod11PntX ((Standard_Real*)Nod11RValues)[ 0] #define Nod11PntY ((Standard_Real*)Nod11RValues)[ 1] #define Nod11PntZ ((Standard_Real*)Nod11RValues)[ 2] #define Nod11PntU ((Standard_Real*)Nod11RValues)[ 3] #define Nod11PntV ((Standard_Real*)Nod11RValues)[ 4] #define Nod11NrmX ((Standard_Real*)Nod11RValues)[ 5] #define Nod11NrmY ((Standard_Real*)Nod11RValues)[ 6] #define Nod11NrmZ ((Standard_Real*)Nod11RValues)[ 7] #define Nod11PCu1 ((Standard_Real*)Nod11RValues)[ 8] #define Nod11PCu2 ((Standard_Real*)Nod11RValues)[ 9] #define Nod11Scal ((Standard_Real*)Nod11RValues)[10] #define Nod1ANdSg ((Standard_Integer*)Nod1AIndices)[0] #define Nod1AFlag ((Standard_Boolean*)Nod1AIndices)[1] #define Nod1AEdg1 ((Standard_Boolean*)Nod1AIndices)[2] #define Nod1AEdg2 ((Standard_Boolean*)Nod1AIndices)[3] #define Nod1APntX ((Standard_Real*)Nod1ARValues)[ 0] #define Nod1APntY ((Standard_Real*)Nod1ARValues)[ 1] #define Nod1APntZ ((Standard_Real*)Nod1ARValues)[ 2] #define Nod1APntU ((Standard_Real*)Nod1ARValues)[ 3] #define Nod1APntV ((Standard_Real*)Nod1ARValues)[ 4] #define Nod1ANrmX ((Standard_Real*)Nod1ARValues)[ 5] #define Nod1ANrmY ((Standard_Real*)Nod1ARValues)[ 6] #define Nod1ANrmZ ((Standard_Real*)Nod1ARValues)[ 7] #define Nod1APCu1 ((Standard_Real*)Nod1ARValues)[ 8] #define Nod1APCu2 ((Standard_Real*)Nod1ARValues)[ 9] #define Nod1AScal ((Standard_Real*)Nod1ARValues)[10] #define Nod1BNdSg ((Standard_Integer*)Nod1BIndices)[0] #define Nod1BFlag ((Standard_Boolean*)Nod1BIndices)[1] #define Nod1BEdg1 ((Standard_Boolean*)Nod1BIndices)[2] #define Nod1BEdg2 ((Standard_Boolean*)Nod1BIndices)[3] #define Nod1BPntX ((Standard_Real*)Nod1BRValues)[ 0] #define Nod1BPntY ((Standard_Real*)Nod1BRValues)[ 1] #define Nod1BPntZ ((Standard_Real*)Nod1BRValues)[ 2] #define Nod1BPntU ((Standard_Real*)Nod1BRValues)[ 3] #define Nod1BPntV ((Standard_Real*)Nod1BRValues)[ 4] #define Nod1BNrmX ((Standard_Real*)Nod1BRValues)[ 5] #define Nod1BNrmY ((Standard_Real*)Nod1BRValues)[ 6] #define Nod1BNrmZ ((Standard_Real*)Nod1BRValues)[ 7] #define Nod1BPCu1 ((Standard_Real*)Nod1BRValues)[ 8] #define Nod1BPCu2 ((Standard_Real*)Nod1BRValues)[ 9] #define Nod1BScal ((Standard_Real*)Nod1BRValues)[10] #define Nod12NdSg ((Standard_Integer*)Nod12Indices)[0] #define Nod12Flag ((Standard_Boolean*)Nod12Indices)[1] #define Nod12Edg1 ((Standard_Boolean*)Nod12Indices)[2] #define Nod12Edg2 ((Standard_Boolean*)Nod12Indices)[3] #define Nod12PntX ((Standard_Real*)Nod12RValues)[ 0] #define Nod12PntY ((Standard_Real*)Nod12RValues)[ 1] #define Nod12PntZ ((Standard_Real*)Nod12RValues)[ 2] #define Nod12PntU ((Standard_Real*)Nod12RValues)[ 3] #define Nod12PntV ((Standard_Real*)Nod12RValues)[ 4] #define Nod12NrmX ((Standard_Real*)Nod12RValues)[ 5] #define Nod12NrmY ((Standard_Real*)Nod12RValues)[ 6] #define Nod12NrmZ ((Standard_Real*)Nod12RValues)[ 7] #define Nod12PCu1 ((Standard_Real*)Nod12RValues)[ 8] #define Nod12PCu2 ((Standard_Real*)Nod12RValues)[ 9] #define Nod12Scal ((Standard_Real*)Nod12RValues)[10] #define Nod13NdSg ((Standard_Integer*)Nod13Indices)[0] #define Nod13Flag ((Standard_Boolean*)Nod13Indices)[1] #define Nod13Edg1 ((Standard_Boolean*)Nod13Indices)[2] #define Nod13Edg2 ((Standard_Boolean*)Nod13Indices)[3] #define Nod13PntX ((Standard_Real*)Nod13RValues)[ 0] #define Nod13PntY ((Standard_Real*)Nod13RValues)[ 1] #define Nod13PntZ ((Standard_Real*)Nod13RValues)[ 2] #define Nod13PntU ((Standard_Real*)Nod13RValues)[ 3] #define Nod13PntV ((Standard_Real*)Nod13RValues)[ 4] #define Nod13NrmX ((Standard_Real*)Nod13RValues)[ 5] #define Nod13NrmY ((Standard_Real*)Nod13RValues)[ 6] #define Nod13NrmZ ((Standard_Real*)Nod13RValues)[ 7] #define Nod13PCu1 ((Standard_Real*)Nod13RValues)[ 8] #define Nod13PCu2 ((Standard_Real*)Nod13RValues)[ 9] #define Nod13Scal ((Standard_Real*)Nod13RValues)[10] #define Nod14NdSg ((Standard_Integer*)Nod14Indices)[0] #define Nod14Flag ((Standard_Boolean*)Nod14Indices)[1] #define Nod14Edg1 ((Standard_Boolean*)Nod14Indices)[2] #define Nod14Edg2 ((Standard_Boolean*)Nod14Indices)[3] #define Nod14PntX ((Standard_Real*)Nod14RValues)[ 0] #define Nod14PntY ((Standard_Real*)Nod14RValues)[ 1] #define Nod14PntZ ((Standard_Real*)Nod14RValues)[ 2] #define Nod14PntU ((Standard_Real*)Nod14RValues)[ 3] #define Nod14PntV ((Standard_Real*)Nod14RValues)[ 4] #define Nod14NrmX ((Standard_Real*)Nod14RValues)[ 5] #define Nod14NrmY ((Standard_Real*)Nod14RValues)[ 6] #define Nod14NrmZ ((Standard_Real*)Nod14RValues)[ 7] #define Nod14PCu1 ((Standard_Real*)Nod14RValues)[ 8] #define Nod14PCu2 ((Standard_Real*)Nod14RValues)[ 9] #define Nod14Scal ((Standard_Real*)Nod14RValues)[10] #define Nod21NdSg ((Standard_Integer*)Nod21Indices)[0] #define Nod21Flag ((Standard_Boolean*)Nod21Indices)[1] #define Nod21Edg1 ((Standard_Boolean*)Nod21Indices)[2] #define Nod21Edg2 ((Standard_Boolean*)Nod21Indices)[3] #define Nod21PntX ((Standard_Real*)Nod21RValues)[ 0] #define Nod21PntY ((Standard_Real*)Nod21RValues)[ 1] #define Nod21PntZ ((Standard_Real*)Nod21RValues)[ 2] #define Nod21PntU ((Standard_Real*)Nod21RValues)[ 3] #define Nod21PntV ((Standard_Real*)Nod21RValues)[ 4] #define Nod21NrmX ((Standard_Real*)Nod21RValues)[ 5] #define Nod21NrmY ((Standard_Real*)Nod21RValues)[ 6] #define Nod21NrmZ ((Standard_Real*)Nod21RValues)[ 7] #define Nod21PCu1 ((Standard_Real*)Nod21RValues)[ 8] #define Nod21PCu2 ((Standard_Real*)Nod21RValues)[ 9] #define Nod21Scal ((Standard_Real*)Nod21RValues)[10] #define Nod2ANdSg ((Standard_Integer*)Nod2AIndices)[0] #define Nod2AFlag ((Standard_Boolean*)Nod2AIndices)[1] #define Nod2AEdg1 ((Standard_Boolean*)Nod2AIndices)[2] #define Nod2AEdg2 ((Standard_Boolean*)Nod2AIndices)[3] #define Nod2APntX ((Standard_Real*)Nod2ARValues)[ 0] #define Nod2APntY ((Standard_Real*)Nod2ARValues)[ 1] #define Nod2APntZ ((Standard_Real*)Nod2ARValues)[ 2] #define Nod2APntU ((Standard_Real*)Nod2ARValues)[ 3] #define Nod2APntV ((Standard_Real*)Nod2ARValues)[ 4] #define Nod2ANrmX ((Standard_Real*)Nod2ARValues)[ 5] #define Nod2ANrmY ((Standard_Real*)Nod2ARValues)[ 6] #define Nod2ANrmZ ((Standard_Real*)Nod2ARValues)[ 7] #define Nod2APCu1 ((Standard_Real*)Nod2ARValues)[ 8] #define Nod2APCu2 ((Standard_Real*)Nod2ARValues)[ 9] #define Nod2AScal ((Standard_Real*)Nod2ARValues)[10] #define Nod2BNdSg ((Standard_Integer*)Nod2BIndices)[0] #define Nod2BFlag ((Standard_Boolean*)Nod2BIndices)[1] #define Nod2BEdg1 ((Standard_Boolean*)Nod2BIndices)[2] #define Nod2BEdg2 ((Standard_Boolean*)Nod2BIndices)[3] #define Nod2BPntX ((Standard_Real*)Nod2BRValues)[ 0] #define Nod2BPntY ((Standard_Real*)Nod2BRValues)[ 1] #define Nod2BPntZ ((Standard_Real*)Nod2BRValues)[ 2] #define Nod2BPntU ((Standard_Real*)Nod2BRValues)[ 3] #define Nod2BPntV ((Standard_Real*)Nod2BRValues)[ 4] #define Nod2BNrmX ((Standard_Real*)Nod2BRValues)[ 5] #define Nod2BNrmY ((Standard_Real*)Nod2BRValues)[ 6] #define Nod2BNrmZ ((Standard_Real*)Nod2BRValues)[ 7] #define Nod2BPCu1 ((Standard_Real*)Nod2BRValues)[ 8] #define Nod2BPCu2 ((Standard_Real*)Nod2BRValues)[ 9] #define Nod2BScal ((Standard_Real*)Nod2BRValues)[10] #define Nod22NdSg ((Standard_Integer*)Nod22Indices)[0] #define Nod22Flag ((Standard_Boolean*)Nod22Indices)[1] #define Nod22Edg1 ((Standard_Boolean*)Nod22Indices)[2] #define Nod22Edg2 ((Standard_Boolean*)Nod22Indices)[3] #define Nod22PntX ((Standard_Real*)Nod22RValues)[ 0] #define Nod22PntY ((Standard_Real*)Nod22RValues)[ 1] #define Nod22PntZ ((Standard_Real*)Nod22RValues)[ 2] #define Nod22PntU ((Standard_Real*)Nod22RValues)[ 3] #define Nod22PntV ((Standard_Real*)Nod22RValues)[ 4] #define Nod22NrmX ((Standard_Real*)Nod22RValues)[ 5] #define Nod22NrmY ((Standard_Real*)Nod22RValues)[ 6] #define Nod22NrmZ ((Standard_Real*)Nod22RValues)[ 7] #define Nod22PCu1 ((Standard_Real*)Nod22RValues)[ 8] #define Nod22PCu2 ((Standard_Real*)Nod22RValues)[ 9] #define Nod22Scal ((Standard_Real*)Nod22RValues)[10] #define Nod23NdSg ((Standard_Integer*)Nod23Indices)[0] #define Nod23Flag ((Standard_Boolean*)Nod23Indices)[1] #define Nod23Edg1 ((Standard_Boolean*)Nod23Indices)[2] #define Nod23Edg2 ((Standard_Boolean*)Nod23Indices)[3] #define Nod23PntX ((Standard_Real*)Nod23RValues)[ 0] #define Nod23PntY ((Standard_Real*)Nod23RValues)[ 1] #define Nod23PntZ ((Standard_Real*)Nod23RValues)[ 2] #define Nod23PntU ((Standard_Real*)Nod23RValues)[ 3] #define Nod23PntV ((Standard_Real*)Nod23RValues)[ 4] #define Nod23NrmX ((Standard_Real*)Nod23RValues)[ 5] #define Nod23NrmY ((Standard_Real*)Nod23RValues)[ 6] #define Nod23NrmZ ((Standard_Real*)Nod23RValues)[ 7] #define Nod23PCu1 ((Standard_Real*)Nod23RValues)[ 8] #define Nod23PCu2 ((Standard_Real*)Nod23RValues)[ 9] #define Nod23Scal ((Standard_Real*)Nod23RValues)[10] #define Nod24NdSg ((Standard_Integer*)Nod24Indices)[0] #define Nod24Flag ((Standard_Boolean*)Nod24Indices)[1] #define Nod24Edg1 ((Standard_Boolean*)Nod24Indices)[2] #define Nod24Edg2 ((Standard_Boolean*)Nod24Indices)[3] #define Nod24PntX ((Standard_Real*)Nod24RValues)[ 0] #define Nod24PntY ((Standard_Real*)Nod24RValues)[ 1] #define Nod24PntZ ((Standard_Real*)Nod24RValues)[ 2] #define Nod24PntU ((Standard_Real*)Nod24RValues)[ 3] #define Nod24PntV ((Standard_Real*)Nod24RValues)[ 4] #define Nod24NrmX ((Standard_Real*)Nod24RValues)[ 5] #define Nod24NrmY ((Standard_Real*)Nod24RValues)[ 6] #define Nod24NrmZ ((Standard_Real*)Nod24RValues)[ 7] #define Nod24PCu1 ((Standard_Real*)Nod24RValues)[ 8] #define Nod24PCu2 ((Standard_Real*)Nod24RValues)[ 9] #define Nod24Scal ((Standard_Real*)Nod24RValues)[10] #define ShapeIndex ((Standard_Integer*)IndexPtr)[0] #define F1Index ((Standard_Integer*)IndexPtr)[1] #define F1Pt1Index ((Standard_Integer*)IndexPtr)[2] #define F1Pt2Index ((Standard_Integer*)IndexPtr)[3] #define F2Index ((Standard_Integer*)IndexPtr)[4] #define F2Pt1Index ((Standard_Integer*)IndexPtr)[5] #define F2Pt2Index ((Standard_Integer*)IndexPtr)[6] #define MinSeg ((Standard_Integer*)IndexPtr)[7] #define MaxSeg ((Standard_Integer*)IndexPtr)[8] #define SegFlags ((Standard_Integer*)IndexPtr)[9] #ifdef OCCT_DEBUG static Standard_Integer DoTrace = Standard_False; static Standard_Integer DoError = Standard_False; #endif //======================================================================= //function : HLRBRep_PolyAlgo //purpose : //======================================================================= HLRBRep_PolyAlgo::HLRBRep_PolyAlgo () : myDebug (Standard_False), myAngle (5 * M_PI / 180.), myTolSta (0.1), myTolEnd (0.9), myTolAngular(0.001) { myAlgo = new HLRAlgo_PolyAlgo(); } //======================================================================= //function : HLRBRep_PolyAlgo //purpose : //======================================================================= HLRBRep_PolyAlgo::HLRBRep_PolyAlgo (const Handle(HLRBRep_PolyAlgo)& A) { myDebug = A->Debug(); myAngle = A->Angle(); myTolAngular = A->TolAngular(); myTolSta = A->TolCoef(); myTolEnd = 1 - myTolSta; myAlgo = A->Algo(); myProj = A->Projector(); Standard_Integer n = A->NbShapes(); for (Standard_Integer i = 1; i <= n; i++) Load(A->Shape(i)); } //======================================================================= //function : HLRBRep_PolyAlgo //purpose : //======================================================================= HLRBRep_PolyAlgo::HLRBRep_PolyAlgo (const TopoDS_Shape& S) : myDebug (Standard_False), myAngle (5 * M_PI / 180.), myTolSta (0.1), myTolEnd (0.9), myTolAngular(0.001) { myShapes.Append(S); myAlgo = new HLRAlgo_PolyAlgo(); } //======================================================================= //function : Shape //purpose : //======================================================================= TopoDS_Shape & HLRBRep_PolyAlgo::Shape (const Standard_Integer I) { Standard_OutOfRange_Raise_if (I == 0 || I > myShapes.Length(), "HLRBRep_PolyAlgo::Shape : unknown Shape"); return myShapes(I); } //======================================================================= //function : Remove //purpose : //======================================================================= void HLRBRep_PolyAlgo::Remove (const Standard_Integer I) { Standard_OutOfRange_Raise_if (I == 0 || I > myShapes.Length(), "HLRBRep_PolyAlgo::Remove : unknown Shape"); myShapes.Remove(I); myAlgo->Clear(); myEMap.Clear(); myFMap.Clear(); } //======================================================================= //function : Index //purpose : //======================================================================= Standard_Integer HLRBRep_PolyAlgo::Index (const TopoDS_Shape& S) const { Standard_Integer n = myShapes.Length(); for (Standard_Integer i = 1; i <= n; i++) if (myShapes(i) == S) return i; return 0; } //======================================================================= //function : Algo //purpose : //======================================================================= Handle(HLRAlgo_PolyAlgo) HLRBRep_PolyAlgo::Algo () const { return myAlgo; } //======================================================================= //function : Update //purpose : //======================================================================= void HLRBRep_PolyAlgo::Update () { myAlgo->Clear(); myEMap.Clear(); myFMap.Clear(); TopoDS_Shape Shape = MakeShape(); if (!Shape.IsNull()) { TopExp_Explorer exshell; Standard_Boolean IsoledF,IsoledE;//,closed; TopLoc_Location L; TopTools_MapOfShape ShapeMap1,ShapeMap2; TopExp::MapShapes(Shape,TopAbs_EDGE,myEMap); TopExp::MapShapes(Shape,TopAbs_FACE,myFMap); Standard_Integer nbEdge = myEMap.Extent(); Standard_Integer nbFace = myFMap.Extent(); TColStd_Array1OfInteger ES (0,nbEdge); // index of the Shell TColStd_Array1OfTransient PD (0,nbFace); // HLRAlgo_PolyData TColStd_Array1OfTransient PID(0,nbFace); // PolyInternalData Standard_Integer nbShell = InitShape(Shape,IsoledF,IsoledE); if (nbShell > 0) { TColStd_Array1OfTransient& Shell = myAlgo->PolyShell(); Standard_Integer iShell = 0; for (exshell.Init(Shape, TopAbs_SHELL); exshell.More(); exshell.Next()) StoreShell(exshell.Current(),iShell,Shell, Standard_False,Standard_False, ES,PD,PID,ShapeMap1,ShapeMap2); if (IsoledF) StoreShell(Shape,iShell,Shell,IsoledF,Standard_False, ES,PD,PID,ShapeMap1,ShapeMap2); if (IsoledE) StoreShell(Shape,iShell,Shell,Standard_False,IsoledE, ES,PD,PID,ShapeMap1,ShapeMap2); myAlgo->Update(); } } } //======================================================================= //function : MakeShape //purpose : //======================================================================= TopoDS_Shape HLRBRep_PolyAlgo::MakeShape () const { Standard_Integer n = myShapes.Length(); Standard_Boolean FirstTime = Standard_True; BRep_Builder B; TopoDS_Shape Shape; for (Standard_Integer i = 1; i <= n; i++) { if (FirstTime) { FirstTime = Standard_False; B.MakeCompound(TopoDS::Compound(Shape)); } B.Add(Shape,myShapes(i)); } return Shape; } //======================================================================= //function : InitShape //purpose : //======================================================================= Standard_Integer HLRBRep_PolyAlgo::InitShape (const TopoDS_Shape& Shape, Standard_Boolean& IsoledF, Standard_Boolean& IsoledE) { TopTools_MapOfShape ShapeMap0; Standard_Integer nbShell = 0; IsoledF = Standard_False; IsoledE = Standard_False; TopExp_Explorer exshell,exface,exedge; TopLoc_Location L; for (exshell.Init(Shape, TopAbs_SHELL); exshell.More(); exshell.Next()) { Standard_Boolean withTrian = Standard_False; for (exface.Init(exshell.Current(), TopAbs_FACE); exface.More(); exface.Next()) { const TopoDS_Face& F = TopoDS::Face(exface.Current()); if (!BRep_Tool::Triangulation(F,L).IsNull()) { if (ShapeMap0.Add(F)) withTrian = Standard_True; } } if (withTrian) nbShell++; } for (exface.Init(Shape, TopAbs_FACE, TopAbs_SHELL); exface.More() && !IsoledF; exface.Next()) { const TopoDS_Face& F = TopoDS::Face(exface.Current()); if (!BRep_Tool::Triangulation(F,L).IsNull()) { if (ShapeMap0.Add(F)) IsoledF = Standard_True; } } if (IsoledF) nbShell++; for (exedge.Init(Shape, TopAbs_EDGE, TopAbs_FACE); exedge.More() && !IsoledE; exedge.Next()) IsoledE = Standard_True; if (IsoledE) nbShell++; if (nbShell > 0) myAlgo->Init(new TColStd_HArray1OfTransient(1,nbShell)); return nbShell; } //======================================================================= //function : StoreShell //purpose : //======================================================================= void HLRBRep_PolyAlgo::StoreShell (const TopoDS_Shape& Shape, Standard_Integer& iShell, TColStd_Array1OfTransient& Shell, const Standard_Boolean IsoledF, const Standard_Boolean IsoledE, TColStd_Array1OfInteger& ES, TColStd_Array1OfTransient& PD, TColStd_Array1OfTransient& PID, TopTools_MapOfShape& ShapeMap1, TopTools_MapOfShape& ShapeMap2) { TopLoc_Location L; TopExp_Explorer exface,exedge; Standard_Integer f = 0,i,j; Standard_Integer nbFaceShell = 0; Standard_Boolean reversed; Standard_Boolean closed = Standard_False; const gp_Trsf& T = myProj.Transformation(); const gp_Trsf& TI = myProj.InvertedTransformation(); const gp_XYZ& tloc = T.TranslationPart(); TLoc[0] = tloc.X(); TLoc[1] = tloc.Y(); TLoc[2] = tloc.Z(); const gp_Mat& tmat = T.VectorialPart(); TMat[0][0] = tmat.Value(1,1); TMat[0][1] = tmat.Value(1,2); TMat[0][2] = tmat.Value(1,3); TMat[1][0] = tmat.Value(2,1); TMat[1][1] = tmat.Value(2,2); TMat[1][2] = tmat.Value(2,3); TMat[2][0] = tmat.Value(3,1); TMat[2][1] = tmat.Value(3,2); TMat[2][2] = tmat.Value(3,3); const gp_XYZ& tilo = TI.TranslationPart(); TILo[0] = tilo.X(); TILo[1] = tilo.Y(); TILo[2] = tilo.Z(); const gp_Mat& tima = TI.VectorialPart(); TIMa[0][0] = tima.Value(1,1); TIMa[0][1] = tima.Value(1,2); TIMa[0][2] = tima.Value(1,3); TIMa[1][0] = tima.Value(2,1); TIMa[1][1] = tima.Value(2,2); TIMa[1][2] = tima.Value(2,3); TIMa[2][0] = tima.Value(3,1); TIMa[2][1] = tima.Value(3,2); TIMa[2][2] = tima.Value(3,3); if (!IsoledE) { if (!IsoledF) { closed = Shape.Closed(); if (!closed) { TopTools_IndexedMapOfShape EM; TopExp::MapShapes(Shape,TopAbs_EDGE,EM); Standard_Integer ie; Standard_Integer nbEdge = EM.Extent (); Standard_Integer *flag = new Standard_Integer[nbEdge + 1]; for (ie = 1; ie <= nbEdge; ie++) flag[ie] = 0; for (exedge.Init(Shape, TopAbs_EDGE); exedge.More(); exedge.Next()) { const TopoDS_Edge& E = TopoDS::Edge(exedge.Current()); ie = EM.FindIndex(E); TopAbs_Orientation orient = E.Orientation(); if (!BRep_Tool::Degenerated(E)) { if (orient == TopAbs_FORWARD ) flag[ie] += 1; else if (orient == TopAbs_REVERSED) flag[ie] -= 1; } } closed = Standard_True; for (ie = 1; ie <= nbEdge && closed; ie++) closed = (flag[ie] == 0); delete [] flag; flag = NULL; } exface.Init(Shape, TopAbs_FACE); } else exface.Init(Shape, TopAbs_FACE, TopAbs_SHELL); for (; exface.More(); exface.Next()) { const TopoDS_Face& F = TopoDS::Face(exface.Current()); if (!BRep_Tool::Triangulation(F,L).IsNull()) { if (ShapeMap1.Add(F)) nbFaceShell++; } } } if (nbFaceShell > 0 || IsoledE) { iShell++; Shell(iShell) = new HLRAlgo_PolyShellData(nbFaceShell); } if (nbFaceShell > 0) { const Handle(HLRAlgo_PolyShellData)& psd = *(Handle(HLRAlgo_PolyShellData)*)&(Shell(iShell)); Standard_Integer iFace = 0; if (!IsoledF) exface.Init(Shape, TopAbs_FACE); else exface.Init(Shape, TopAbs_FACE, TopAbs_SHELL); TopTools_MapOfShape ShapeMapBis; for (; exface.More(); exface.Next()) { const TopoDS_Face& F = TopoDS::Face(exface.Current()); const Handle(Poly_Triangulation)& Tr = BRep_Tool::Triangulation(F,L); if (!Tr.IsNull()) { if (ShapeMap2.Add(F)) { iFace++; f = myFMap.FindIndex(F); reversed = F.Orientation() == TopAbs_REVERSED; gp_Trsf TT = L.Transformation(); TT.PreMultiply(T); const gp_XYZ& ttlo = TT.TranslationPart(); TTLo[0] = ttlo.X(); TTLo[1] = ttlo.Y(); TTLo[2] = ttlo.Z(); const gp_Mat& ttma = TT.VectorialPart(); TTMa[0][0] = ttma.Value(1,1); TTMa[0][1] = ttma.Value(1,2); TTMa[0][2] = ttma.Value(1,3); TTMa[1][0] = ttma.Value(2,1); TTMa[1][1] = ttma.Value(2,2); TTMa[1][2] = ttma.Value(2,3); TTMa[2][0] = ttma.Value(3,1); TTMa[2][1] = ttma.Value(3,2); TTMa[2][2] = ttma.Value(3,3); Poly_Array1OfTriangle & Tri = Tr->ChangeTriangles(); TColgp_Array1OfPnt & Nod = Tr->ChangeNodes(); Standard_Integer nbN = Nod.Upper(); Standard_Integer nbT = Tri.Upper(); PD (f) = new HLRAlgo_PolyData(); psd->PolyData().ChangeValue(iFace) = PD(f); PID(f) = new HLRAlgo_PolyInternalData(nbN,nbT); Handle(HLRAlgo_PolyInternalData)& pid = *(Handle(HLRAlgo_PolyInternalData)*)&(PID(f)); Handle(Geom_Surface) S = BRep_Tool::Surface(F); if (S->DynamicType() == STANDARD_TYPE(Geom_RectangularTrimmedSurface)) S = Handle(Geom_RectangularTrimmedSurface)::DownCast(S)->BasisSurface(); GeomAdaptor_Surface AS(S); pid->Planar(AS.GetType() == GeomAbs_Plane); Standard_Address TData = &pid->TData(); Standard_Address PISeg = &pid->PISeg(); Standard_Address PINod = &pid->PINod(); Poly_Triangle * OT = &(Tri.ChangeValue(1)); HLRAlgo_TriangleData* NT = &(((HLRAlgo_Array1OfTData*)TData)->ChangeValue(1)); for (i = 1; i <= nbT; i++) { Standard_Address Tri2Indices = NT->Indices(); OT->Get(Tri2Node1,Tri2Node2,Tri2Node3); Tri2Flags = 0; if (reversed) { j = Tri2Node1; Tri2Node1 = Tri2Node3; Tri2Node3 = j; } OT++; NT++; } gp_Pnt * ON = &(Nod.ChangeValue(1)); Handle(HLRAlgo_PolyInternalNode)* NN = &(((HLRAlgo_Array1OfPINod*)PINod)->ChangeValue(1)); for (i = 1; i <= nbN; i++) { const Standard_Address Nod1RValues = (*NN)->RValues(); const Standard_Address Nod1Indices = (*NN)->Indices(); Nod1NdSg = 0; Nod1Flag = 0; Nod1PntX = ON->X(); Nod1PntY = ON->Y(); Nod1PntZ = ON->Z(); TTMultiply(Nod1PntX,Nod1PntY,Nod1PntZ); ON++; NN++; } pid->UpdateLinks(TData,PISeg,PINod); if (Tr->HasUVNodes()) { myBSurf.Initialize(F,Standard_False); TColgp_Array1OfPnt2d & UVN = Tr->ChangeUVNodes(); gp_Pnt2d* OUVN = &(UVN.ChangeValue(1)); NN = &(((HLRAlgo_Array1OfPINod*)PINod)-> ChangeValue(1)); for (i = 1; i <= nbN; i++) { const Standard_Address Nod1Indices = (*NN)->Indices(); const Standard_Address Nod1RValues = (*NN)->RValues(); Nod1PntU = OUVN->X(); Nod1PntV = OUVN->Y(); if (Normal(i,Nod1Indices,Nod1RValues, TData,PISeg,PINod,Standard_False)) Nod1Flag |= NMskNorm; else { Nod1Flag &= ~NMskNorm; Nod1Scal = 0; } OUVN++; NN++; } } #ifdef OCCT_DEBUG else if (DoError) { cout << " HLRBRep_PolyAlgo::StoreShell : Face "; cout << f << " non triangulated" << endl; } #endif NT = &(((HLRAlgo_Array1OfTData*)TData)->ChangeValue(1)); for (i = 1; i <= nbT; i++) { const Standard_Address Tri1Indices = NT->Indices(); const Handle(HLRAlgo_PolyInternalNode)* PN1 = &(((HLRAlgo_Array1OfPINod*)PINod)->ChangeValue(Tri1Node1)); const Handle(HLRAlgo_PolyInternalNode)* PN2 = &(((HLRAlgo_Array1OfPINod*)PINod)->ChangeValue(Tri1Node2)); const Handle(HLRAlgo_PolyInternalNode)* PN3 = &(((HLRAlgo_Array1OfPINod*)PINod)->ChangeValue(Tri1Node3)); const Standard_Address Nod1Indices = (*PN1)->Indices(); const Standard_Address Nod2Indices = (*PN2)->Indices(); const Standard_Address Nod3Indices = (*PN3)->Indices(); const Standard_Address Nod1RValues = (*PN1)->RValues(); const Standard_Address Nod2RValues = (*PN2)->RValues(); const Standard_Address Nod3RValues = (*PN3)->RValues(); OrientTriangle(i,Tri1Indices, Nod1Indices,Nod1RValues, Nod2Indices,Nod2RValues, Nod3Indices,Nod3RValues); NT++; } } } #ifdef OCCT_DEBUG else if (DoError) { cout << "HLRBRep_PolyAlgo::StoreShell : Face "; cout << f << " deja stockee" << endl; } #endif } Standard_Integer nbFace = myFMap.Extent(); HLRAlgo_ListOfBPoint& List = psd->Edges(); TopTools_IndexedDataMapOfShapeListOfShape EF; TopExp::MapShapesAndAncestors(Shape,TopAbs_EDGE,TopAbs_FACE,EF); Handle(HLRAlgo_PolyInternalData)* pid = (Handle(HLRAlgo_PolyInternalData)*)&(PID.ChangeValue(1)); for (f = 1; f <= nbFace; f++) { if (!(*pid).IsNull()) { for (exedge.Init(myFMap(f),TopAbs_EDGE); exedge.More(); exedge.Next()) { TopoDS_Edge E = TopoDS::Edge(exedge.Current()); if (ShapeMap1.Add(E)) { Standard_Integer e = myEMap.FindIndex(E); ES(e) = iShell; Standard_Integer anIndexE = EF.FindIndex(E); if (anIndexE > 0) { TopTools_ListOfShape& LS = EF(anIndexE); InitBiPointsWithConnexity(e,E,List,PID,LS,Standard_True); } else { TopTools_ListOfShape LS; InitBiPointsWithConnexity(e,E,List,PID,LS,Standard_False); } } } } pid++; } InsertOnOutLine(PID); CheckFrBackTriangles(List,PID); UpdateOutLines(List,PID); UpdateEdgesBiPoints(List,PID,closed); UpdatePolyData(PD,PID,closed); pid = (Handle(HLRAlgo_PolyInternalData)*)&(PID.ChangeValue(1)); for (f = 1; f <= nbFace; f++) { (*pid).Nullify(); pid++; } } else if (IsoledE) { const Handle(HLRAlgo_PolyShellData)& psd = *(Handle(HLRAlgo_PolyShellData)*)&(Shell(iShell)); HLRAlgo_ListOfBPoint& List = psd->Edges(); for (exedge.Init(Shape, TopAbs_EDGE, TopAbs_FACE); exedge.More(); exedge.Next()) { TopoDS_Edge E = TopoDS::Edge(exedge.Current()); if (ShapeMap1.Add(E)) { Standard_Integer e = myEMap.FindIndex(E); ES(e) = iShell; TopTools_ListOfShape LS; InitBiPointsWithConnexity(e,E,List,PID,LS,Standard_False); } } } } //======================================================================= //function : Normal //purpose : //======================================================================= Standard_Boolean HLRBRep_PolyAlgo:: Normal (const Standard_Integer iNode, const Standard_Address Nod1Indices, const Standard_Address Nod1RValues, Standard_Address& TData, Standard_Address& PISeg, Standard_Address& PINod, const Standard_Boolean orient) const { gp_Vec D1U,D1V,D2U,D2V,D2UV; gp_Pnt P; gp_Dir Norma; Standard_Boolean OK; CSLib_DerivativeStatus Status; CSLib_NormalStatus NStat; myBSurf.D1(Nod1PntU,Nod1PntV,P,D1U,D1V); CSLib::Normal(D1U,D1V,Standard_Real(Precision::Angular()), Status,Norma); if (Status != CSLib_Done) { myBSurf.D2(Nod1PntU,Nod1PntV,P,D1U,D1V,D2U,D2V,D2UV); CSLib::Normal(D1U,D1V,D2U,D2V,D2UV, Precision::Angular(),OK,NStat,Norma); if (!OK) return Standard_False; } Standard_Real EyeX = 0; Standard_Real EyeY = 0; Standard_Real EyeZ = -1; if (myProj.Perspective()) { EyeX = Nod1PntX; EyeY = Nod1PntY; EyeZ = Nod1PntZ - myProj.Focus(); Standard_Real d = sqrt(EyeX * EyeX + EyeY * EyeY + EyeZ * EyeZ); if (d > 0) { EyeX /= d; EyeY /= d; EyeZ /= d; } } Nod1NrmX = Norma.X(); Nod1NrmY = Norma.Y(); Nod1NrmZ = Norma.Z(); // TMultiply(Nod1NrmX,Nod1NrmY,Nod1NrmZ); TMultiply(Nod1NrmX,Nod1NrmY,Nod1NrmZ,myProj.Perspective()); //OCC349 Standard_Real NormX,NormY,NormZ; if (AverageNormal(iNode,Nod1Indices,TData,PISeg,PINod, NormX,NormY,NormZ)) { if (Nod1NrmX * NormX + Nod1NrmY * NormY + Nod1NrmZ * NormZ < 0) { Nod1NrmX = -Nod1NrmX; Nod1NrmY = -Nod1NrmY; Nod1NrmZ = -Nod1NrmZ; } Nod1Scal = (Nod1NrmX * EyeX + Nod1NrmY * EyeY + Nod1NrmZ * EyeZ); } else { Nod1Scal = 0; Nod1NrmX = 1; Nod1NrmY = 0; Nod1NrmZ = 0; #ifdef OCCT_DEBUG if (DoError) { cout << "HLRBRep_PolyAlgo::Normal : AverageNormal error"; cout << endl; } #endif } if (Nod1Scal > 0) { if ( Nod1Scal < myTolAngular) { Nod1Scal = 0; Nod1Flag |= NMskOutL; } } else { if (-Nod1Scal < myTolAngular) { Nod1Scal = 0; Nod1Flag |= NMskOutL; } } if (orient) UpdateAroundNode(iNode,Nod1Indices, TData,PISeg,PINod); return Standard_True; } //======================================================================= //function : AverageNormal //purpose : //======================================================================= Standard_Boolean HLRBRep_PolyAlgo::AverageNormal(const Standard_Integer iNode, const Standard_Address Nod1Indices, Standard_Address& TData, Standard_Address& PISeg, Standard_Address& PINod, Standard_Real& X, Standard_Real& Y, Standard_Real& Z) const { Standard_Boolean OK = Standard_False; Standard_Integer jNode = 0,kNode,iiii,iTri1,iTri2; X = 0; Y = 0; Z = 0; iiii = Nod1NdSg; while (iiii != 0 && !OK) { const Standard_Address Seg2Indices = ((HLRAlgo_Array1OfPISeg*)PISeg)->ChangeValue(iiii).Indices(); iTri1 = Seg2Conex1; iTri2 = Seg2Conex2; if ( iTri1 != 0) AddNormalOnTriangle (iTri1,iNode,jNode,TData,PINod,X,Y,Z,OK); if ( iTri2 != 0) AddNormalOnTriangle (iTri2,iNode,jNode,TData,PINod,X,Y,Z,OK); if (Seg2LstSg1 == iNode) iiii = Seg2NxtSg1; else iiii = Seg2NxtSg2; } if (jNode != 0) { const Standard_Address Nod2Indices = ((HLRAlgo_Array1OfPINod*)PINod)->ChangeValue(jNode)->Indices(); iiii = Nod2NdSg; while (iiii != 0 && !OK) { const Standard_Address Seg2Indices = ((HLRAlgo_Array1OfPISeg*)PISeg)->ChangeValue(iiii).Indices(); iTri1 = Seg2Conex1; iTri2 = Seg2Conex2; if ( iTri1 != 0) AddNormalOnTriangle (iTri1,jNode,kNode,TData,PINod,X,Y,Z,OK); if ( iTri2 != 0) AddNormalOnTriangle (iTri2,jNode,kNode,TData,PINod,X,Y,Z,OK); if (Seg2LstSg1 == jNode) iiii = Seg2NxtSg1; else iiii = Seg2NxtSg2; } } Standard_Real d = sqrt (X * X + Y * Y + Z * Z); if (OK && d < 1.e-10) { OK = Standard_False; #ifdef OCCT_DEBUG if (DoError) { cout << "HLRAlgo_PolyInternalData:: inverted normals on "; cout << "node " << iNode << endl; } #endif } return OK; } //======================================================================= //function : AddNormalOnTriangle //purpose : //======================================================================= void HLRBRep_PolyAlgo:: AddNormalOnTriangle(const Standard_Integer iTri, const Standard_Integer iNode, Standard_Integer& jNode, Standard_Address& TData, Standard_Address& PINod, Standard_Real& X, Standard_Real& Y, Standard_Real& Z, Standard_Boolean& OK) const { Standard_Real dn,dnx,dny,dnz; Standard_Real d1,dx1,dy1,dz1; Standard_Real d2,dx2,dy2,dz2; Standard_Real d3,dx3,dy3,dz3; const Standard_Address Tri2Indices = ((HLRAlgo_Array1OfTData*)TData)->ChangeValue(iTri).Indices(); const Standard_Address Nod1RValues = ((HLRAlgo_Array1OfPINod*)PINod)->ChangeValue(Tri2Node1)->RValues(); const Standard_Address Nod2RValues = ((HLRAlgo_Array1OfPINod*)PINod)->ChangeValue(Tri2Node2)->RValues(); const Standard_Address Nod3RValues = ((HLRAlgo_Array1OfPINod*)PINod)->ChangeValue(Tri2Node3)->RValues(); dx1 = Nod2PntX - Nod1PntX; dy1 = Nod2PntY - Nod1PntY; dz1 = Nod2PntZ - Nod1PntZ; d1 = sqrt(dx1 * dx1 + dy1 * dy1 + dz1 * dz1); if (d1 < 1.e-10) { if (Tri2Node1 == iNode) jNode = Tri2Node2; else if (Tri2Node2 == iNode) jNode = Tri2Node1; } else { dx2 = Nod3PntX - Nod2PntX; dy2 = Nod3PntY - Nod2PntY; dz2 = Nod3PntZ - Nod2PntZ; d2 = sqrt(dx2 * dx2 + dy2 * dy2 + dz2 * dz2); if (d2 < 1.e-10) { if (Tri2Node2 == iNode) jNode = Tri2Node3; else if (Tri2Node3 == iNode) jNode = Tri2Node2; } else { dx3 = Nod1PntX - Nod3PntX; dy3 = Nod1PntY - Nod3PntY; dz3 = Nod1PntZ - Nod3PntZ; d3 = sqrt(dx3 * dx3 + dy3 * dy3 + dz3 * dz3); if (d3 < 1.e-10) { if (Tri2Node3 == iNode) jNode = Tri2Node1; else if (Tri2Node1 == iNode) jNode = Tri2Node3; } else { dn = 1 / (d1 * d2); dnx = (dy1 * dz2 - dy2 * dz1) * dn; dny = (dz1 * dx2 - dz2 * dx1) * dn; dnz = (dx1 * dy2 - dx2 * dy1) * dn; dn = sqrt(dnx * dnx + dny * dny + dnz * dnz); if (dn > 1.e-10) { OK = Standard_True; X += dnx; Y += dny; Z += dnz; } } } } } //======================================================================= //function : InitBiPointsWithConnexity //purpose : //======================================================================= void HLRBRep_PolyAlgo:: InitBiPointsWithConnexity (const Standard_Integer e, TopoDS_Edge& E, HLRAlgo_ListOfBPoint& List, TColStd_Array1OfTransient& PID, TopTools_ListOfShape& LS, const Standard_Boolean connex) { Standard_Integer iPol,nbPol,i1,i1p1,i1p2,i2,i2p1,i2p2; Standard_Real X1 ,Y1 ,Z1 ,X2 ,Y2 ,Z2 ; Standard_Real XTI1,YTI1,ZTI1,XTI2,YTI2,ZTI2; Standard_Real U1,U2 = 0.; Handle(Poly_PolygonOnTriangulation) HPol[2]; TopLoc_Location L; myBCurv.Initialize(E); if (connex) { Standard_Integer nbConnex = LS.Extent(); if (nbConnex == 1) { TopTools_ListIteratorOfListOfShape itn(LS); const TopoDS_Face& F1 = TopoDS::Face(itn.Value()); i1 = myFMap.FindIndex(F1); const Handle(Poly_Triangulation)& Tr1 = BRep_Tool::Triangulation(F1,L); HPol[0] = BRep_Tool::PolygonOnTriangulation(E,Tr1,L); const Handle(HLRAlgo_PolyInternalData)& pid1 = *(Handle(HLRAlgo_PolyInternalData)*)&(PID(i1)); if (!HPol[0].IsNull()) { myPC.Initialize(E,F1); const Handle(TColStd_HArray1OfReal)& par = HPol[0]->Parameters(); const TColStd_Array1OfInteger& Pol1 = HPol[0]->Nodes(); nbPol = Pol1.Upper(); Standard_Address TData1 = &pid1->TData(); Standard_Address PISeg1 = &pid1->PISeg(); Standard_Address PINod1 = &pid1->PINod(); Standard_Address Nod11Indices,Nod12Indices; Standard_Address Nod11RValues,Nod12RValues; const Handle(HLRAlgo_PolyInternalNode)* pi1p1 = &(((HLRAlgo_Array1OfPINod*)PINod1)->ChangeValue(Pol1(1 ))); Nod11Indices = (*pi1p1)->Indices(); Nod11RValues = (*pi1p1)->RValues(); const Handle(HLRAlgo_PolyInternalNode)* pi1p2 = &(((HLRAlgo_Array1OfPINod*)PINod1)->ChangeValue(Pol1(nbPol))); Nod12Indices = (*pi1p2)->Indices(); Nod12RValues = (*pi1p2)->RValues(); Nod11Flag |= NMskVert; Nod12Flag |= NMskVert; for (iPol = 1; iPol <= nbPol; iPol++) { const Handle(HLRAlgo_PolyInternalNode)* pi1pA = &(((HLRAlgo_Array1OfPINod*)PINod1)->ChangeValue(Pol1(iPol))); Standard_Address Nod1AIndices = (*pi1pA)->Indices(); Standard_Address Nod1ARValues = (*pi1pA)->RValues(); if (Nod1AEdg1 == 0 || Nod1AEdg1 == (Standard_Boolean) e) { Nod1AEdg1 = e; Nod1APCu1 = par->Value(iPol); } else { Nod1AEdg2 = e; Nod1APCu2 = par->Value(iPol); } } i1p2 = Pol1(1); Nod12Indices = Nod11Indices; Nod12RValues = Nod11RValues; XTI2 = X2 = Nod12PntX; YTI2 = Y2 = Nod12PntY; ZTI2 = Z2 = Nod12PntZ; if (Nod12Edg1 == (Standard_Boolean) e) U2 = Nod12PCu1; else if (Nod12Edg2 == (Standard_Boolean) e) U2 = Nod12PCu2; #ifdef OCCT_DEBUG else { cout << " HLRBRep_PolyAlgo::InitBiPointsWithConnexity : "; cout << "Parameter error on Node " << i1p2 << endl; } #endif Nod12Flag |= NMskEdge; TIMultiply(XTI2,YTI2,ZTI2); if (Pol1(1) == Pol1(nbPol) && myPC.IsPeriodic()) U2 = U2 - myPC.Period(); if (nbPol == 2 && BRep_Tool::Degenerated(E)) { CheckDegeneratedSegment(Nod11Indices,Nod11RValues, Nod12Indices,Nod12RValues); UpdateAroundNode(Pol1(1 ),Nod11Indices,TData1,PISeg1,PINod1); UpdateAroundNode(Pol1(nbPol),Nod12Indices,TData1,PISeg1,PINod1); } else { for (iPol = 2; iPol <= nbPol; iPol++) { i1p1 = i1p2; Nod11Indices = Nod12Indices; Nod11RValues = Nod12RValues; i1p2 = Pol1(iPol); const Handle(HLRAlgo_PolyInternalNode)* pi1p2iPol = &(((HLRAlgo_Array1OfPINod*)PINod1)->ChangeValue(Pol1(iPol))); Nod12Indices = (*pi1p2iPol)->Indices(); Nod12RValues = (*pi1p2iPol)->RValues(); #ifdef OCCT_DEBUG if (DoError) { if (Nod11NrmX*Nod12NrmX + Nod11NrmY*Nod12NrmY + Nod11NrmZ*Nod12NrmZ < 0) { cout << " HLRBRep_PolyAlgo::InitBiPointsWithConnexity : "; cout << "Too big angle between " << i1p1 << setw(6); cout << " and " << i1p2 << setw(6); cout << " in face " << i1 << endl; } } #endif X1 = X2; Y1 = Y2; Z1 = Z2; XTI1 = XTI2; YTI1 = YTI2; ZTI1 = ZTI2; U1 = U2; XTI2 = X2 = Nod12PntX; YTI2 = Y2 = Nod12PntY; ZTI2 = Z2 = Nod12PntZ; if (Nod12Edg1 == (Standard_Boolean) e) U2 = Nod12PCu1; else if (Nod12Edg2 == (Standard_Boolean) e) U2 = Nod12PCu2; #ifdef OCCT_DEBUG else { cout << " HLRBRep_PolyAlgo::InitBiPointsWithConnexity : "; cout << "Parameter error on Node " << i1p2 << endl; } #endif Nod12Flag |= NMskEdge; TIMultiply(XTI2,YTI2,ZTI2); Interpolation(List, X1 ,Y1 ,Z1 ,X2 ,Y2 ,Z2 , XTI1,YTI1,ZTI1,XTI2,YTI2,ZTI2, e,U1,U2, Nod11Indices,Nod11RValues, Nod12Indices,Nod12RValues, i1p1,i1p2,i1,pid1,TData1,PISeg1,PINod1); } } } #ifdef OCCT_DEBUG else if (DoError) { cout << "HLRBRep_PolyAlgo::InitBiPointsWithConnexity : Edge "; cout << e << " connex 1 sans PolygonOnTriangulation" << endl; } #endif } else if (nbConnex == 2) { TopTools_ListIteratorOfListOfShape itn(LS); const TopoDS_Face& F1 = TopoDS::Face(itn.Value()); i1 = myFMap.FindIndex(F1); const Handle(Poly_Triangulation)& Tr1 = BRep_Tool::Triangulation(F1,L); HPol[0] = BRep_Tool::PolygonOnTriangulation(E,Tr1,L); itn.Next(); const TopoDS_Face& F2 = TopoDS::Face(itn.Value()); i2 = myFMap.FindIndex(F2); if (i1 == i2) E.Reverse(); const Handle(Poly_Triangulation)& Tr2 = BRep_Tool::Triangulation(F2,L); HPol[1] = BRep_Tool::PolygonOnTriangulation(E,Tr2,L); GeomAbs_Shape rg = BRep_Tool::Continuity(E,F1,F2); const Handle(HLRAlgo_PolyInternalData)& pid1 = *(Handle(HLRAlgo_PolyInternalData)*)&(PID(i1)); const Handle(HLRAlgo_PolyInternalData)& pid2 = *(Handle(HLRAlgo_PolyInternalData)*)&(PID(i2)); if (!HPol[0].IsNull() && !HPol[1].IsNull()) { myPC.Initialize(E,F1); const TColStd_Array1OfInteger& Pol1 = HPol[0]->Nodes(); const TColStd_Array1OfInteger& Pol2 = HPol[1]->Nodes(); const Handle(TColStd_HArray1OfReal)& par = HPol[0]->Parameters(); Standard_Integer nbPol1 = Pol1.Upper(); Standard_Address TData1 = &pid1->TData(); Standard_Address PISeg1 = &pid1->PISeg(); Standard_Address PINod1 = &pid1->PINod(); Standard_Address TData2 = &pid2->TData(); Standard_Address PISeg2 = &pid2->PISeg(); Standard_Address PINod2 = &pid2->PINod(); Standard_Address Nod11Indices,Nod11RValues; Standard_Address Nod12Indices,Nod12RValues; Standard_Address Nod21Indices,Nod21RValues; Standard_Address Nod22Indices,Nod22RValues; const Handle(HLRAlgo_PolyInternalNode)* pi1p1 = &(((HLRAlgo_Array1OfPINod*)PINod1)->ChangeValue(Pol1(1 ))); Nod11Indices = (*pi1p1)->Indices(); Nod11RValues = (*pi1p1)->RValues(); const Handle(HLRAlgo_PolyInternalNode)* pi1p2nbPol1 = &(((HLRAlgo_Array1OfPINod*)PINod1)->ChangeValue(Pol1(nbPol1))); Nod12Indices = (*pi1p2nbPol1)->Indices(); Nod12RValues = (*pi1p2nbPol1)->RValues(); const Handle(HLRAlgo_PolyInternalNode)* pi2p1 = &(((HLRAlgo_Array1OfPINod*)PINod2)->ChangeValue(Pol2(1 ))); Nod21Indices = (*pi2p1)->Indices(); Nod21RValues = (*pi2p1)->RValues(); const Handle(HLRAlgo_PolyInternalNode)* pi2p2 = &(((HLRAlgo_Array1OfPINod*)PINod2)->ChangeValue(Pol2(nbPol1))); Nod22Indices = (*pi2p2)->Indices(); Nod22RValues = (*pi2p2)->RValues(); Nod11Flag |= NMskVert; Nod12Flag |= NMskVert; Nod21Flag |= NMskVert; Nod22Flag |= NMskVert; for (iPol = 1; iPol <= nbPol1; iPol++) { const Handle(HLRAlgo_PolyInternalNode)* pi1pA = &(((HLRAlgo_Array1OfPINod*)PINod1)->ChangeValue(Pol1(iPol))); Standard_Address Nod1AIndices = (*pi1pA)->Indices(); Standard_Address Nod1ARValues = (*pi1pA)->RValues(); const Handle(HLRAlgo_PolyInternalNode)* pi2pA = &(((HLRAlgo_Array1OfPINod*)PINod2)->ChangeValue(Pol2(iPol))); Standard_Address Nod2AIndices = (*pi2pA)->Indices(); Standard_Address Nod2ARValues = (*pi2pA)->RValues(); Standard_Real PCu = par->Value(iPol); if (Nod1AEdg1 == 0 || Nod1AEdg1 == (Standard_Boolean) e) { Nod1AEdg1 = e; Nod1APCu1 = PCu; } else { Nod1AEdg2 = e; Nod1APCu2 = PCu; } if (Nod2AEdg1 == 0 || Nod2AEdg1 == (Standard_Boolean) e) { Nod2AEdg1 = e; Nod2APCu1 = PCu; } else { Nod2AEdg2 = e; Nod2APCu2 = PCu; } } i1p2 = Pol1(1); Nod12Indices = Nod11Indices; Nod12RValues = Nod11RValues; i2p2 = Pol2(1); Nod22Indices = Nod21Indices; Nod22RValues = Nod21RValues; XTI2 = X2 = Nod12PntX; YTI2 = Y2 = Nod12PntY; ZTI2 = Z2 = Nod12PntZ; if (Nod12Edg1 == (Standard_Boolean) e) U2 = Nod12PCu1; else if (Nod12Edg2 == (Standard_Boolean) e) U2 = Nod12PCu2; #ifdef OCCT_DEBUG else { cout << " HLRBRep_PolyAlgo::InitBiPointsWithConnexity : "; cout << "Parameter error on Node " << i1p2 << endl; } #endif Nod12Flag |= NMskEdge; Nod22Flag |= NMskEdge; TIMultiply(XTI2,YTI2,ZTI2); if (Pol1(1) == Pol1(nbPol1) && myPC.IsPeriodic()) U2 = U2 - myPC.Period(); if (nbPol1 == 2 && BRep_Tool::Degenerated(E)) { CheckDegeneratedSegment(Nod11Indices,Nod11RValues, Nod12Indices,Nod12RValues); CheckDegeneratedSegment(Nod21Indices,Nod21RValues, Nod22Indices,Nod22RValues); UpdateAroundNode(Pol1(1 ),Nod11Indices,TData1,PISeg1,PINod1); UpdateAroundNode(Pol1(nbPol1),Nod12Indices,TData1,PISeg1,PINod1); UpdateAroundNode(Pol2(1 ),Nod21Indices,TData2,PISeg2,PINod2); UpdateAroundNode(Pol2(nbPol1),Nod22Indices,TData2,PISeg2,PINod2); } else { for (iPol = 2; iPol <= nbPol1; iPol++) { i1p1 = i1p2; Nod11Indices = Nod12Indices; Nod11RValues = Nod12RValues; i2p1 = i2p2; Nod21Indices = Nod22Indices; Nod21RValues = Nod22RValues; i1p2 = Pol1(iPol); const Handle(HLRAlgo_PolyInternalNode)* pi1p2iPol = &(((HLRAlgo_Array1OfPINod*)PINod1)->ChangeValue(Pol1(iPol))); Nod12Indices = (*pi1p2iPol)->Indices(); Nod12RValues = (*pi1p2iPol)->RValues(); i2p2 = Pol2(iPol); const Handle(HLRAlgo_PolyInternalNode)* pi2p2iPol = &(((HLRAlgo_Array1OfPINod*)PINod2)->ChangeValue(Pol2(iPol))); Nod22Indices = (*pi2p2iPol)->Indices(); Nod22RValues = (*pi2p2iPol)->RValues(); #ifdef OCCT_DEBUG if (DoError) { if (Nod11NrmX*Nod12NrmX + Nod11NrmY*Nod12NrmY + Nod11NrmZ*Nod12NrmZ < 0) { cout << " HLRBRep_PolyAlgo::InitBiPointsWithConnexity : "; cout << "To big angle between " << i1p1 << setw(6); cout << " and " << i1p2 << setw(6); cout << " in face " << i1 << endl; } if (Nod21NrmX*Nod22NrmX + Nod21NrmY*Nod22NrmY + Nod21NrmZ*Nod22NrmZ < 0) { cout << " HLRBRep_PolyAlgo::InitBiPointsWithConnexity : "; cout << "To big angle between " << i2p1 << setw(6); cout << " and " << i2p2 << setw(6); cout<< " in face " << i2 << endl; } } #endif X1 = X2; Y1 = Y2; Z1 = Z2; XTI1 = XTI2; YTI1 = YTI2; ZTI1 = ZTI2; U1 = U2; XTI2 = X2 = Nod12PntX; YTI2 = Y2 = Nod12PntY; ZTI2 = Z2 = Nod12PntZ; if (Nod12Edg1 == (Standard_Boolean) e) U2 = Nod12PCu1; else if (Nod12Edg2 == (Standard_Boolean) e) U2 = Nod12PCu2; #ifdef OCCT_DEBUG else { cout << " HLRBRep_PolyAlgo::InitBiPointsWithConnexity : "; cout << "Parameter error on Node " << i1p2 << endl; } #endif Nod12Flag |= NMskEdge; Nod22Flag |= NMskEdge; TIMultiply(XTI2,YTI2,ZTI2); Interpolation(List, X1 ,Y1 ,Z1 ,X2 ,Y2 ,Z2 , XTI1,YTI1,ZTI1,XTI2,YTI2,ZTI2, e,U1,U2,rg, Nod11Indices,Nod11RValues, Nod12Indices,Nod12RValues, i1p1,i1p2,i1,pid1,TData1,PISeg1,PINod1, Nod21Indices,Nod21RValues, Nod22Indices,Nod22RValues, i2p1,i2p2,i2,pid2,TData2,PISeg2,PINod2); } } } #ifdef OCCT_DEBUG else if (DoError) { cout << "HLRBRep_PolyAlgo::InitBiPointsWithConnexity : Edge "; cout << e << " connect 2 without PolygonOnTriangulation" << endl; } #endif } } else { // no connexity const Handle(Poly_Polygon3D)& Polyg = BRep_Tool::Polygon3D(E,L); if (!Polyg.IsNull()) { const TColgp_Array1OfPnt& Pol = Polyg->Nodes(); gp_Trsf TT = L.Transformation(); const gp_Trsf& T = myProj.Transformation(); TT.PreMultiply(T); const gp_XYZ& ttlo = TT.TranslationPart(); TTLo[0] = ttlo.X(); TTLo[1] = ttlo.Y(); TTLo[2] = ttlo.Z(); const gp_Mat& ttma = TT.VectorialPart(); TTMa[0][0] = ttma.Value(1,1); TTMa[0][1] = ttma.Value(1,2); TTMa[0][2] = ttma.Value(1,3); TTMa[1][0] = ttma.Value(2,1); TTMa[1][1] = ttma.Value(2,2); TTMa[1][2] = ttma.Value(2,3); TTMa[2][0] = ttma.Value(3,1); TTMa[2][1] = ttma.Value(3,2); TTMa[2][2] = ttma.Value(3,3); Standard_Integer nbPol1 = Pol.Upper(); const gp_XYZ& P1 = Pol(1).XYZ(); X2 = P1.X(); Y2 = P1.Y(); Z2 = P1.Z(); TTMultiply(X2,Y2,Z2); XTI2 = X2; YTI2 = Y2; ZTI2 = Z2; TIMultiply(XTI2,YTI2,ZTI2); for (Standard_Integer jPol = 2; jPol <= nbPol1; jPol++) { X1 = X2; Y1 = Y2; Z1 = Z2; XTI1 = XTI2; YTI1 = YTI2; ZTI1 = ZTI2; const gp_XYZ& P2 = Pol(jPol).XYZ(); X2 = P2.X(); Y2 = P2.Y(); Z2 = P2.Z(); TTMultiply(X2,Y2,Z2); XTI2 = X2; YTI2 = Y2; ZTI2 = Z2; TIMultiply(XTI2,YTI2,ZTI2); List.Prepend(HLRAlgo_BiPoint (XTI1,YTI1,ZTI1,XTI2,YTI2,ZTI2, X1 ,Y1 ,Z1 ,X2 ,Y2 ,Z2 , e, 0)); } } #ifdef OCCT_DEBUG else if (DoError) { cout << "HLRBRep_PolyAlgo::InitBiPointsWithConnexity : Edge "; cout << e << " Isolated, without Polygone 3D" << endl; } #endif } } //======================================================================= //function : Interpolation //purpose : //======================================================================= void HLRBRep_PolyAlgo:: Interpolation (HLRAlgo_ListOfBPoint& List, Standard_Real& X1, Standard_Real& Y1, Standard_Real& Z1, Standard_Real& X2, Standard_Real& Y2, Standard_Real& Z2, Standard_Real& XTI1, Standard_Real& YTI1, Standard_Real& ZTI1, Standard_Real& XTI2, Standard_Real& YTI2, Standard_Real& ZTI2, const Standard_Integer e, Standard_Real& U1, Standard_Real& U2, Standard_Address& Nod11Indices, Standard_Address& Nod11RValues, Standard_Address& Nod12Indices, Standard_Address& Nod12RValues, const Standard_Integer i1p1, const Standard_Integer i1p2, const Standard_Integer i1, const Handle(HLRAlgo_PolyInternalData)& pid1, Standard_Address& TData1, Standard_Address& PISeg1, Standard_Address& PINod1) const { Standard_Boolean insP3,mP3P1; Standard_Real X3,Y3,Z3,XTI3,YTI3,ZTI3,coef3,U3; // gp_Pnt P3,PT3; insP3 = Interpolation(U1,U2,Nod11RValues,Nod12RValues, X3,Y3,Z3,XTI3,YTI3,ZTI3,coef3,U3,mP3P1); MoveOrInsertPoint(List, X1 ,Y1 ,Z1 ,X2 ,Y2 ,Z2 , XTI1,YTI1,ZTI1,XTI2,YTI2,ZTI2, e,U1,U2, Nod11Indices,Nod11RValues, Nod12Indices,Nod12RValues, i1p1,i1p2,i1,pid1,TData1,PISeg1,PINod1, X3,Y3,Z3,XTI3,YTI3,ZTI3,coef3,U3,insP3,mP3P1,0); } //======================================================================= //function : Interpolation //purpose : //======================================================================= void HLRBRep_PolyAlgo:: Interpolation (HLRAlgo_ListOfBPoint& List, Standard_Real& X1, Standard_Real& Y1, Standard_Real& Z1, Standard_Real& X2, Standard_Real& Y2, Standard_Real& Z2, Standard_Real& XTI1, Standard_Real& YTI1, Standard_Real& ZTI1, Standard_Real& XTI2, Standard_Real& YTI2, Standard_Real& ZTI2, const Standard_Integer e, Standard_Real& U1, Standard_Real& U2, const GeomAbs_Shape rg, Standard_Address& Nod11Indices, Standard_Address& Nod11RValues, Standard_Address& Nod12Indices, Standard_Address& Nod12RValues, const Standard_Integer i1p1, const Standard_Integer i1p2, const Standard_Integer i1, const Handle(HLRAlgo_PolyInternalData)& pid1, Standard_Address& TData1, Standard_Address& PISeg1, Standard_Address& PINod1, Standard_Address& Nod21Indices, Standard_Address& Nod21RValues, Standard_Address& Nod22Indices, Standard_Address& Nod22RValues, const Standard_Integer i2p1, const Standard_Integer i2p2, const Standard_Integer i2, const Handle(HLRAlgo_PolyInternalData)& pid2, Standard_Address& TData2, Standard_Address& PISeg2, Standard_Address& PINod2) const { Standard_Boolean insP3,mP3P1,insP4,mP4P1; Standard_Real X3,Y3,Z3,XTI3,YTI3,ZTI3,coef3,U3; Standard_Real X4,Y4,Z4,XTI4,YTI4,ZTI4,coef4,U4; // gp_Pnt P3,PT3,P4,PT4; Standard_Boolean flag = 0; if (rg >= GeomAbs_G1) flag += 1; if (rg >= GeomAbs_G2) flag += 2; insP3 = Interpolation(U1,U2,Nod11RValues,Nod12RValues, X3,Y3,Z3,XTI3,YTI3,ZTI3,coef3,U3,mP3P1); insP4 = Interpolation(U1,U2,Nod21RValues,Nod22RValues, X4,Y4,Z4,XTI4,YTI4,ZTI4,coef4,U4,mP4P1); Standard_Boolean OK = insP3 || insP4; if (OK) { if (!insP4) // p1 i1p3 p2 MoveOrInsertPoint(List, X1 ,Y1 ,Z1 ,X2 ,Y2 ,Z2 , XTI1,YTI1,ZTI1,XTI2,YTI2,ZTI2, e,U1,U2, Nod11Indices,Nod11RValues, Nod12Indices,Nod12RValues, i1p1,i1p2,i1,pid1,TData1,PISeg1,PINod1, Nod21Indices,Nod21RValues, Nod22Indices,Nod22RValues, i2p1,i2p2,i2,pid2,TData2,PISeg2,PINod2, X3,Y3,Z3,XTI3,YTI3,ZTI3,coef3,U3,insP3,mP3P1,flag); else if (!insP3) // p1 i2p4 p2 MoveOrInsertPoint(List, X1 ,Y1 ,Z1 ,X2 ,Y2 ,Z2 , XTI1,YTI1,ZTI1,XTI2,YTI2,ZTI2, e,U1,U2, Nod21Indices,Nod21RValues, Nod22Indices,Nod22RValues, i2p1,i2p2,i2,pid2,TData2,PISeg2,PINod2, Nod11Indices,Nod11RValues, Nod12Indices,Nod12RValues, i1p1,i1p2,i1,pid1,TData1,PISeg1,PINod1, X4,Y4,Z4,XTI4,YTI4,ZTI4,coef4,U4,insP4,mP4P1,flag); else if (Abs(coef4 - coef3) < myTolSta) // p1 i1p3-i2p4 p2 MoveOrInsertPoint(List, X1 ,Y1 ,Z1 ,X2 ,Y2 ,Z2 , XTI1,YTI1,ZTI1,XTI2,YTI2,ZTI2, e,U1,U2, Nod21Indices,Nod21RValues, Nod22Indices,Nod22RValues, i2p1,i2p2,i2,pid2,TData2,PISeg2,PINod2, Nod11Indices,Nod11RValues, Nod12Indices,Nod12RValues, i1p1,i1p2,i1,pid1,TData1,PISeg1,PINod1, X4,Y4,Z4,XTI4,YTI4,ZTI4,coef4,U4,insP4,mP4P1,flag); else if (coef4 < coef3) // p1 i2p4 i1p3 p2 MoveOrInsertPoint(List, X1 ,Y1 ,Z1 ,X2 ,Y2 ,Z2 , XTI1,YTI1,ZTI1,XTI2,YTI2,ZTI2, e,U1,U2, Nod21Indices,Nod21RValues, Nod22Indices,Nod22RValues, i2p1,i2p2,i2,pid2,TData2,PISeg2,PINod2, Nod11Indices,Nod11RValues, Nod12Indices,Nod12RValues, i1p1,i1p2,i1,pid1,TData1,PISeg1,PINod1, X4,Y4,Z4,XTI4,YTI4,ZTI4,coef4,U4,insP4,mP4P1, X3,Y3,Z3,XTI3,YTI3,ZTI3,coef3,U3,insP3,mP3P1,flag); else // p1 i1p3 i2p4 p2 MoveOrInsertPoint(List, X1 ,Y1 ,Z1 ,X2 ,Y2 ,Z2 , XTI1,YTI1,ZTI1,XTI2,YTI2,ZTI2, e,U1,U2, Nod11Indices,Nod11RValues, Nod12Indices,Nod12RValues, i1p1,i1p2,i1,pid1,TData1,PISeg1,PINod1, Nod21Indices,Nod21RValues, Nod22Indices,Nod22RValues, i2p1,i2p2,i2,pid2,TData2,PISeg2,PINod2, X3,Y3,Z3,XTI3,YTI3,ZTI3,coef3,U3,insP3,mP3P1, X4,Y4,Z4,XTI4,YTI4,ZTI4,coef4,U4,insP4,mP4P1,flag); } else // p1 p2 List.Prepend(HLRAlgo_BiPoint (XTI1,YTI1,ZTI1,XTI2,YTI2,ZTI2, X1 ,Y1 ,Z1 ,X2 ,Y2 ,Z2 , e, i1 ,i1p1,i1p2,i2 ,i2p1,i2p2,flag)); } //======================================================================= //function : Interpolation //purpose : //======================================================================= Standard_Boolean HLRBRep_PolyAlgo:: Interpolation (const Standard_Real U1, const Standard_Real U2, const Standard_Address Nod1RValues, const Standard_Address Nod2RValues, Standard_Real& X3, Standard_Real& Y3, Standard_Real& Z3, Standard_Real& XTI3, Standard_Real& YTI3, Standard_Real& ZTI3, Standard_Real& coef3, Standard_Real& U3, Standard_Boolean& mP3P1) const { if (NewNode(Nod1RValues,Nod2RValues,coef3,mP3P1)) { U3 = U1 + (U2 - U1) * coef3; const gp_Pnt& P3 = myBCurv.Value(U3); XTI3 = X3 = P3.X(); YTI3 = Y3 = P3.Y(); ZTI3 = Z3 = P3.Z(); TMultiply(X3,Y3,Z3); return Standard_True; } return Standard_False; } //======================================================================= //function : MoveOrInsertPoint //purpose : //======================================================================= void HLRBRep_PolyAlgo:: MoveOrInsertPoint (HLRAlgo_ListOfBPoint& List, Standard_Real& X1, Standard_Real& Y1, Standard_Real& Z1, Standard_Real& X2, Standard_Real& Y2, Standard_Real& Z2, Standard_Real& XTI1, Standard_Real& YTI1, Standard_Real& ZTI1, Standard_Real& XTI2, Standard_Real& YTI2, Standard_Real& ZTI2, const Standard_Integer e, Standard_Real& U1, Standard_Real& U2, Standard_Address& Nod11Indices, Standard_Address& Nod11RValues, Standard_Address& Nod12Indices, Standard_Address& Nod12RValues, const Standard_Integer i1p1, const Standard_Integer i1p2, const Standard_Integer i1, const Handle(HLRAlgo_PolyInternalData)& pid1, Standard_Address& TData1, Standard_Address& PISeg1, Standard_Address& PINod1, const Standard_Real X3, const Standard_Real Y3, const Standard_Real Z3, const Standard_Real XTI3, const Standard_Real YTI3, const Standard_Real ZTI3, const Standard_Real coef3, const Standard_Real U3, const Standard_Boolean insP3, const Standard_Boolean mP3P1, const Standard_Boolean flag) const { Standard_Address TData2 = 0; Standard_Address PISeg2 = 0; Standard_Address PINod2 = 0; Standard_Boolean ins3 = insP3; if (ins3 && mP3P1) { // P1 ---> P3 if (!(Nod11Flag & NMskVert) && coef3 < myTolSta) { ins3 = Standard_False; ChangeNode(i1p1,i1p2, Nod11Indices,Nod11RValues, Nod12Indices,Nod12RValues, coef3,X3,Y3,Z3,Standard_True, TData1,PISeg1,PINod1); X1 = X3; Y1 = Y3; Z1 = Z3; XTI1 = XTI3; YTI1 = YTI3; ZTI1 = ZTI3; U1 = U3; Nod11PntX = X3; Nod11PntY = Y3; Nod11PntZ = Z3; if (Nod11Edg1 == (Standard_Boolean) e) Nod11PCu1 = U3; else if (Nod11Edg2 == (Standard_Boolean) e) Nod11PCu2 = U3; #ifdef OCCT_DEBUG else { cout << " HLRBRep_PolyAlgo::MoveOrInsertPoint : "; cout << "Parameter error on Node " << i1p1 << endl; } #endif Nod11Scal = 0; Nod11Flag |= NMskOutL; UpdateAroundNode(i1p1,Nod11Indices,TData1,PISeg1,PINod1); Standard_Address Coordinates = List.First().Coordinates(); PntX2 = X3; PntY2 = Y3; PntZ2 = Z3; PntXTI2 = XTI3; PntYTI2 = YTI3; PntZTI2 = ZTI3; } } if (ins3 && !mP3P1) { // P2 ---> P3 if (!(Nod12Flag & NMskVert) && coef3 > myTolEnd) { ins3 = Standard_False; ChangeNode(i1p1,i1p2, Nod11Indices,Nod11RValues, Nod12Indices,Nod12RValues, coef3,X3,Y3,Z3,Standard_False, TData1,PISeg1,PINod1); X2 = X3; Y2 = Y3; Z2 = Z3; XTI2 = XTI3; YTI2 = YTI3; ZTI2 = ZTI3; U2 = U3; Nod12PntX = X3; Nod12PntY = Y3; Nod12PntZ = Z3; if (Nod12Edg1 == (Standard_Boolean) e) Nod12PCu1 = U3; else if (Nod12Edg2 == (Standard_Boolean) e) Nod12PCu2 = U3; #ifdef OCCT_DEBUG else { cout << " HLRBRep_PolyAlgo::MoveOrInsertPoint : "; cout << "Parameter error on Node " << i1p2 << endl; } #endif Nod12Scal = 0; Nod12Flag |= NMskOutL; UpdateAroundNode(i1p2,Nod12Indices,TData1,PISeg1,PINod1); } } if (ins3) { // p1 i1p3 p2 Standard_Integer i1p3 = pid1->AddNode (Nod11RValues,Nod12RValues,PINod1,PINod2,coef3,X3,Y3,Z3); const Handle(HLRAlgo_PolyInternalNode)* pi1p3 = &(((HLRAlgo_Array1OfPINod*)PINod1)->ChangeValue(i1p3)); const Standard_Address Nod13Indices = (*pi1p3)->Indices(); const Standard_Address Nod13RValues = (*pi1p3)->RValues(); Nod13Edg1 = e; Nod13PCu1 = U3; Nod13Scal = 0; Nod13Flag |= NMskOutL; Nod13Flag |= NMskEdge; pid1->UpdateLinks(i1p1,i1p2,i1p3, TData1,TData2,PISeg1,PISeg2,PINod1,PINod2); UpdateAroundNode(i1p3,Nod13Indices,TData1,PISeg1,PINod1); List.Prepend(HLRAlgo_BiPoint (XTI1,YTI1,ZTI1,XTI3,YTI3,ZTI3, X1 ,Y1 ,Z1 ,X3 ,Y3 ,Z3 , e, i1 ,i1p1,i1p3,flag)); List.Prepend(HLRAlgo_BiPoint (XTI3,YTI3,ZTI3,XTI2,YTI2,ZTI2, X3 ,Y3 ,Z3 ,X2 ,Y2 ,Z2 , e, i1 ,i1p3,i1p2,flag)); } else // p1 p2 List.Prepend(HLRAlgo_BiPoint (XTI1,YTI1,ZTI1,XTI2,YTI2,ZTI2, X1 ,Y1 ,Z1 ,X2 ,Y2 ,Z2 , e, i1 ,i1p1,i1p2,flag)); } //======================================================================= //function : MoveOrInsertPoint //purpose : //======================================================================= void HLRBRep_PolyAlgo:: MoveOrInsertPoint (HLRAlgo_ListOfBPoint& List, Standard_Real& X1, Standard_Real& Y1, Standard_Real& Z1, Standard_Real& X2, Standard_Real& Y2, Standard_Real& Z2, Standard_Real& XTI1, Standard_Real& YTI1, Standard_Real& ZTI1, Standard_Real& XTI2, Standard_Real& YTI2, Standard_Real& ZTI2, const Standard_Integer e, Standard_Real& U1, Standard_Real& U2, Standard_Address& Nod11Indices, Standard_Address& Nod11RValues, Standard_Address& Nod12Indices, Standard_Address& Nod12RValues, const Standard_Integer i1p1, const Standard_Integer i1p2, const Standard_Integer i1, const Handle(HLRAlgo_PolyInternalData)& pid1, Standard_Address& TData1, Standard_Address& PISeg1, Standard_Address& PINod1, Standard_Address& Nod21Indices, Standard_Address& Nod21RValues, Standard_Address& Nod22Indices, Standard_Address& Nod22RValues, const Standard_Integer i2p1, const Standard_Integer i2p2, const Standard_Integer i2, const Handle(HLRAlgo_PolyInternalData)& pid2, Standard_Address& TData2, Standard_Address& PISeg2, Standard_Address& PINod2, const Standard_Real X3, const Standard_Real Y3, const Standard_Real Z3, const Standard_Real XTI3, const Standard_Real YTI3, const Standard_Real ZTI3, const Standard_Real coef3, const Standard_Real U3, const Standard_Boolean insP3, const Standard_Boolean mP3P1, const Standard_Boolean flag) const { Standard_Boolean ins3 = insP3; if (ins3 && mP3P1) { // P1 ---> P3 if (!(Nod11Flag & NMskVert) && coef3 < myTolSta) { ins3 = Standard_False; ChangeNode(i1p1,i1p2, Nod11Indices,Nod11RValues, Nod12Indices,Nod12RValues, coef3,X3,Y3,Z3,Standard_True, TData1,PISeg1,PINod1); ChangeNode(i2p1,i2p2, Nod21Indices,Nod21RValues, Nod22Indices,Nod22RValues, coef3,X3,Y3,Z3,Standard_True, TData2,PISeg2,PINod2); X1 = X3; Y1 = Y3; Z1 = Z3; XTI1 = XTI3; YTI1 = YTI3; ZTI1 = ZTI3; U1 = U3; Nod11PntX = X3; Nod11PntY = Y3; Nod11PntZ = Z3; if (Nod11Edg1 == (Standard_Boolean) e) Nod11PCu1 = U3; else if (Nod11Edg2 == (Standard_Boolean) e) Nod11PCu2 = U3; #ifdef OCCT_DEBUG else { cout << " HLRBRep_PolyAlgo::MoveOrInsertPoint : "; cout << "Parameter error on Node " << i1p1 << endl; } #endif Nod11Scal = 0; Nod11Flag |= NMskOutL; UpdateAroundNode(i1p1,Nod11Indices,TData1,PISeg1,PINod1); Nod21PntX = X3; Nod21PntY = Y3; Nod21PntZ = Z3; if (Nod21Edg1 == (Standard_Boolean) e) Nod21PCu1 = U3; else if (Nod21Edg2 == (Standard_Boolean) e) Nod21PCu2 = U3; #ifdef OCCT_DEBUG else { cout << " HLRBRep_PolyAlgo::MoveOrInsertPoint : "; cout << "Parameter error on Node " << i2p1 << endl; } #endif Nod21Scal = 0; Nod21Flag |= NMskOutL; UpdateAroundNode(i2p1,Nod21Indices,TData2,PISeg2,PINod2); Standard_Address Coordinates = List.First().Coordinates(); PntX2 = X3; PntY2 = Y3; PntZ2 = Z3; PntXTI2 = XTI3; PntYTI2 = YTI3; PntZTI2 = ZTI3; } } if (ins3 && !mP3P1) { // P2 ---> P3 if (!(Nod12Flag & NMskVert) && coef3 > myTolEnd) { ins3 = Standard_False; ChangeNode(i1p1,i1p2, Nod11Indices,Nod11RValues, Nod12Indices,Nod12RValues, coef3,X3,Y3,Z3,Standard_False, TData1,PISeg1,PINod1); ChangeNode(i2p1,i2p2, Nod21Indices,Nod21RValues, Nod22Indices,Nod22RValues, coef3,X3,Y3,Z3,Standard_False, TData2,PISeg2,PINod2); X2 = X3; Y2 = Y3; Z2 = Z3; XTI2 = XTI3; YTI2 = YTI3; ZTI2 = ZTI3; U2 = U3; Nod12PntX = X3; Nod12PntY = Y3; Nod12PntZ = Z3; if (Nod12Edg1 == (Standard_Boolean) e) Nod12PCu1 = U3; else if (Nod12Edg2 == (Standard_Boolean) e) Nod12PCu2 = U3; #ifdef OCCT_DEBUG else { cout << " HLRBRep_PolyAlgo::MoveOrInsertPoint : "; cout << "Parameter error on Node " << i1p2 << endl; } #endif Nod12Scal = 0; Nod12Flag |= NMskOutL; UpdateAroundNode(i1p2,Nod12Indices,TData1,PISeg1,PINod1); Nod22PntX = X3; Nod22PntY = Y3; Nod22PntZ = Z3; if (Nod22Edg1 == (Standard_Boolean) e) Nod22PCu1 = U3; else if (Nod22Edg2 == (Standard_Boolean) e) Nod22PCu2 = U3; #ifdef OCCT_DEBUG else { cout << " HLRBRep_PolyAlgo::MoveOrInsertPoint : "; cout << "Parameter error on Node " << i2p2 << endl; } #endif Nod22Scal = 0; Nod22Flag |= NMskOutL; UpdateAroundNode(i2p2,Nod22Indices,TData2,PISeg2,PINod2); } } if (ins3) { // p1 i1p3 p2 Standard_Integer i1p3 = pid1->AddNode (Nod11RValues,Nod12RValues,PINod1,PINod2,coef3,X3,Y3,Z3); Standard_Integer i2p3 = pid2->AddNode (Nod21RValues,Nod22RValues,PINod2,PINod1,coef3,X3,Y3,Z3); const Handle(HLRAlgo_PolyInternalNode)* pi1p3 = &(((HLRAlgo_Array1OfPINod*)PINod1)->ChangeValue(i1p3)); const Standard_Address Nod13Indices = (*pi1p3)->Indices(); const Standard_Address Nod13RValues = (*pi1p3)->RValues(); const Handle(HLRAlgo_PolyInternalNode)* pi2p3 = &(((HLRAlgo_Array1OfPINod*)PINod2)->ChangeValue(i2p3)); const Standard_Address Nod23Indices = (*pi2p3)->Indices(); const Standard_Address Nod23RValues = (*pi2p3)->RValues(); Nod13Edg1 = e; Nod13PCu1 = U3; Nod13Scal = 0; Nod13Flag |= NMskOutL; Nod13Flag |= NMskEdge; Nod23Edg1 = e; Nod23PCu1 = U3; Nod23Scal = 0; Nod23Flag |= NMskOutL; Nod23Flag |= NMskEdge; pid1->UpdateLinks(i1p1,i1p2,i1p3, TData1,TData2,PISeg1,PISeg2,PINod1,PINod2); pid2->UpdateLinks(i2p1,i2p2,i2p3, TData2,TData1,PISeg2,PISeg1,PINod2,PINod1); UpdateAroundNode(i1p3,Nod13Indices,TData1,PISeg1,PINod1); UpdateAroundNode(i2p3,Nod23Indices,TData2,PISeg2,PINod2); List.Prepend(HLRAlgo_BiPoint (XTI1,YTI1,ZTI1,XTI3,YTI3,ZTI3, X1 ,Y1 ,Z1 ,X3 ,Y3 ,Z3 , e, i1 ,i1p1,i1p3,i2 ,i2p1,i2p3,flag)); List.Prepend(HLRAlgo_BiPoint (XTI3,YTI3,ZTI3,XTI2,YTI2,ZTI2, X3 ,Y3 ,Z3 ,X2 ,Y2 ,Z2 , e, i1 ,i1p3,i1p2,i2 ,i2p3,i2p2,flag)); } else // p1 p2 List.Prepend(HLRAlgo_BiPoint (XTI1,YTI1,ZTI1,XTI2,YTI2,ZTI2, X1 ,Y1 ,Z1 ,X2 ,Y2 ,Z2 , e, i1 ,i1p1,i1p2,i2 ,i2p1,i2p2,flag)); } //======================================================================= //function : MoveOrInsertPoint //purpose : //======================================================================= void HLRBRep_PolyAlgo:: MoveOrInsertPoint (HLRAlgo_ListOfBPoint& List, Standard_Real& X1, Standard_Real& Y1, Standard_Real& Z1, Standard_Real& X2, Standard_Real& Y2, Standard_Real& Z2, Standard_Real& XTI1, Standard_Real& YTI1, Standard_Real& ZTI1, Standard_Real& XTI2, Standard_Real& YTI2, Standard_Real& ZTI2, const Standard_Integer e, Standard_Real& U1, Standard_Real& U2, Standard_Address& Nod11Indices, Standard_Address& Nod11RValues, Standard_Address& Nod12Indices, Standard_Address& Nod12RValues, const Standard_Integer i1p1, const Standard_Integer i1p2, const Standard_Integer i1, const Handle(HLRAlgo_PolyInternalData)& pid1, Standard_Address& TData1, Standard_Address& PISeg1, Standard_Address& PINod1, Standard_Address& Nod21Indices, Standard_Address& Nod21RValues, Standard_Address& Nod22Indices, Standard_Address& Nod22RValues, const Standard_Integer i2p1, const Standard_Integer i2p2, const Standard_Integer i2, const Handle(HLRAlgo_PolyInternalData)& pid2, Standard_Address& TData2, Standard_Address& PISeg2, Standard_Address& PINod2, const Standard_Real X3, const Standard_Real Y3, const Standard_Real Z3, const Standard_Real XTI3, const Standard_Real YTI3, const Standard_Real ZTI3, const Standard_Real coef3, const Standard_Real U3, const Standard_Boolean insP3, const Standard_Boolean mP3P1, const Standard_Real X4, const Standard_Real Y4, const Standard_Real Z4, const Standard_Real XTI4, const Standard_Real YTI4, const Standard_Real ZTI4, const Standard_Real coef4, const Standard_Real U4, const Standard_Boolean insP4, const Standard_Boolean mP4P1, const Standard_Boolean flag) const { Standard_Boolean ins3 = insP3; Standard_Boolean ins4 = insP4; if (ins3 && mP3P1) { // P1 ---> P3 if (!(Nod11Flag & NMskVert) && coef3 < myTolSta) { ins3 = Standard_False; ChangeNode(i1p1,i1p2, Nod11Indices,Nod11RValues, Nod12Indices,Nod12RValues, coef3,X3,Y3,Z3,Standard_True, TData1,PISeg1,PINod1); ChangeNode(i2p1,i2p2, Nod21Indices,Nod21RValues, Nod22Indices,Nod22RValues, coef3,X3,Y3,Z3,Standard_True, TData2,PISeg2,PINod2); X1 = X3; Y1 = Y3; Z1 = Z3; XTI1 = XTI3; YTI1 = YTI3; ZTI1 = ZTI3; U1 = U3; Nod11PntX = X3; Nod11PntY = Y3; Nod11PntZ = Z3; if (Nod11Edg1 == (Standard_Boolean) e) Nod11PCu1 = U3; else if (Nod11Edg2 == (Standard_Boolean) e) Nod11PCu2 = U3; #ifdef OCCT_DEBUG else { cout << " HLRBRep_PolyAlgo::MoveOrInsertPoint : "; cout << "Parameter error on Node " << i1p1 << endl; } #endif Nod11Scal = 0; Nod11Flag |= NMskOutL; UpdateAroundNode(i1p1,Nod11Indices,TData1,PISeg1,PINod1); Nod21PntX = X3; Nod21PntY = Y3; Nod21PntZ = Z3; if (Nod21Edg1 == (Standard_Boolean) e) Nod21PCu1 = U3; else if (Nod21Edg2 == (Standard_Boolean) e) Nod21PCu2 = U3; #ifdef OCCT_DEBUG else { cout << " HLRBRep_PolyAlgo::MoveOrInsertPoint : "; cout << "Parameter error on Node " << i2p1 << endl; } #endif Nod21Scal = 0; Nod21Flag |= NMskOutL; UpdateAroundNode(i2p1,Nod21Indices,TData2,PISeg2,PINod2); Standard_Address Coordinates = List.First().Coordinates(); PntX2 = X3; PntY2 = Y3; PntZ2 = Z3; PntXTI2 = XTI3; PntYTI2 = YTI3; PntZTI2 = ZTI3; } } if (ins4 && !mP4P1) { // P2 ---> P4 if (!(Nod12Flag & NMskVert) && coef4 > myTolEnd) { ins4 = Standard_False; ChangeNode(i2p1,i2p2, Nod21Indices,Nod21RValues, Nod22Indices,Nod22RValues, coef4,X4,Y4,Z4,Standard_False, TData2,PISeg2,PINod2); ChangeNode(i1p1,i1p2, Nod11Indices,Nod11RValues, Nod12Indices,Nod12RValues, coef4,X4,Y4,Z4,Standard_False, TData1,PISeg1,PINod1); X2 = X4; Y2 = Y4; Z2 = Z4; XTI2 = XTI4; YTI2 = YTI4; ZTI2 = ZTI4; U2 = U4; Nod12PntX = X4; Nod12PntY = Y4; Nod12PntZ = Z4; if (Nod12Edg1 == (Standard_Boolean) e) Nod12PCu1 = U4; else if (Nod12Edg2 == (Standard_Boolean) e) Nod12PCu2 = U4; #ifdef OCCT_DEBUG else { cout << " HLRBRep_PolyAlgo::MoveOrInsertPoint : "; cout << "Parameter error on Node " << i1p2 << endl; } #endif Nod12Scal = 0; Nod12Flag |= NMskOutL; UpdateAroundNode(i1p2,Nod12Indices,TData1,PISeg1,PINod1); Nod22PntX = X4; Nod22PntY = Y4; Nod22PntZ = Z4; if (Nod22Edg1 == (Standard_Boolean) e) Nod22PCu1 = U4; else if (Nod22Edg2 == (Standard_Boolean) e) Nod22PCu2 = U4; #ifdef OCCT_DEBUG else { cout << " HLRBRep_PolyAlgo::MoveOrInsertPoint : "; cout << "Parameter error on Node " << i2p2 << endl; } #endif Nod22Scal = 0; Nod22Flag |= NMskOutL; UpdateAroundNode(i2p2,Nod22Indices,TData2,PISeg2,PINod2); } } if (ins3 || ins4) { if (!ins4) // p1 i1p3 p2 MoveOrInsertPoint(List, X1 ,Y1 ,Z1 ,X2 ,Y2 ,Z2 , XTI1,YTI1,ZTI1,XTI2,YTI2,ZTI2, e,U1,U2, Nod11Indices,Nod11RValues, Nod12Indices,Nod12RValues, i1p1,i1p2,i1,pid1,TData1,PISeg1,PINod1, Nod21Indices,Nod21RValues, Nod22Indices,Nod22RValues, i2p1,i2p2,i2,pid2,TData2,PISeg2,PINod2, X3,Y3,Z3,XTI3,YTI3,ZTI3,coef3,U3,insP3,mP3P1,flag); else if (!ins3) // p1 i2p4 p2 MoveOrInsertPoint(List, X1 ,Y1 ,Z1 ,X2 ,Y2 ,Z2 , XTI1,YTI1,ZTI1,XTI2,YTI2,ZTI2, e,U1,U2, Nod21Indices,Nod21RValues, Nod22Indices,Nod22RValues, i2p1,i2p2,i2,pid2,TData2,PISeg2,PINod2, Nod11Indices,Nod11RValues, Nod12Indices,Nod12RValues, i1p1,i1p2,i1,pid1,TData1,PISeg1,PINod1, X4,Y4,Z4,XTI4,YTI4,ZTI4,coef4,U4,insP4,mP4P1,flag); else { // p1 i1p3 i2p4 p2 Standard_Integer i1p3 = pid1->AddNode (Nod11RValues,Nod12RValues,PINod1,PINod2,coef3,X3,Y3,Z3); Standard_Integer i2p3 = pid2->AddNode (Nod21RValues,Nod22RValues,PINod2,PINod1,coef3,X3,Y3,Z3); Standard_Integer i1p4 = pid1->AddNode (Nod11RValues,Nod12RValues,PINod1,PINod2,coef4,X4,Y4,Z4); Standard_Integer i2p4 = pid2->AddNode (Nod21RValues,Nod22RValues,PINod2,PINod1,coef4,X4,Y4,Z4); const Handle(HLRAlgo_PolyInternalNode)* pi1p3 = &(((HLRAlgo_Array1OfPINod*)PINod1)->ChangeValue(i1p3)); const Standard_Address Nod13Indices = (*pi1p3)->Indices(); const Standard_Address Nod13RValues = (*pi1p3)->RValues(); const Handle(HLRAlgo_PolyInternalNode)* pi1p4 = &(((HLRAlgo_Array1OfPINod*)PINod1)->ChangeValue(i1p4)); const Standard_Address Nod14Indices = (*pi1p4)->Indices(); const Standard_Address Nod14RValues = (*pi1p4)->RValues(); const Handle(HLRAlgo_PolyInternalNode)* pi2p3 = &(((HLRAlgo_Array1OfPINod*)PINod2)->ChangeValue(i2p3)); const Standard_Address Nod23Indices = (*pi2p3)->Indices(); const Standard_Address Nod23RValues = (*pi2p3)->RValues(); const Handle(HLRAlgo_PolyInternalNode)* pi2p4 = &(((HLRAlgo_Array1OfPINod*)PINod2)->ChangeValue(i2p4)); const Standard_Address Nod24Indices = (*pi2p4)->Indices(); const Standard_Address Nod24RValues = (*pi2p4)->RValues(); Nod13Edg1 = e; Nod13PCu1 = U3; Nod13Scal = 0; Nod13Flag |= NMskOutL; Nod13Flag |= NMskEdge; Nod23Edg1 = e; Nod23PCu1 = U3; Nod23Scal = 0; Nod23Flag |= NMskOutL; Nod23Flag |= NMskEdge; Nod14Edg1 = e; Nod14PCu1 = U4; Nod14Scal = 0; Nod14Flag |= NMskOutL; Nod14Flag |= NMskEdge; Nod24Edg1 = e; Nod24PCu1 = U4; Nod24Scal = 0; Nod24Flag |= NMskOutL; Nod24Flag |= NMskEdge; pid1->UpdateLinks(i1p1,i1p2,i1p3, TData1,TData2,PISeg1,PISeg2,PINod1,PINod2); pid2->UpdateLinks(i2p1,i2p2,i2p3, TData2,TData1,PISeg2,PISeg1,PINod2,PINod1); pid2->UpdateLinks(i2p3,i2p2,i2p4, TData2,TData1,PISeg2,PISeg1,PINod2,PINod1); pid1->UpdateLinks(i1p3,i1p2,i1p4, TData1,TData2,PISeg1,PISeg2,PINod1,PINod2); UpdateAroundNode(i1p3,Nod13Indices,TData1,PISeg1,PINod1); UpdateAroundNode(i2p3,Nod23Indices,TData2,PISeg2,PINod2); UpdateAroundNode(i1p4,Nod14Indices,TData1,PISeg1,PINod1); UpdateAroundNode(i2p4,Nod24Indices,TData2,PISeg2,PINod2); List.Prepend(HLRAlgo_BiPoint (XTI1,YTI1,ZTI1,XTI3,YTI3,ZTI3, X1 ,Y1 ,Z1 ,X3 ,Y3 ,Z3 , e, i1 ,i1p1,i1p3,i2 ,i2p1,i2p3,flag)); List.Prepend(HLRAlgo_BiPoint (XTI3,YTI3,ZTI3,XTI4,YTI4,ZTI4, X3 ,Y3 ,Z3 ,X4 ,Y4 ,Z4 , e, i1 ,i1p3,i1p4,i2 ,i2p3,i2p4,flag)); List.Prepend(HLRAlgo_BiPoint (XTI4,YTI4,ZTI4,XTI2,YTI2,ZTI2, X4 ,Y4 ,Z4 ,X2 ,Y2 ,Z2 , e, i1 ,i1p4,i1p2,i2 ,i2p4,i2p2,flag)); } } else // p1 p2 List.Prepend(HLRAlgo_BiPoint (XTI1,YTI1,ZTI1,XTI2,YTI2,ZTI2, X1 ,Y1 ,Z1 ,X2 ,Y2 ,Z2 , e, i1 ,i1p1,i1p2,i2 ,i2p1,i2p2,flag)); } //======================================================================= //function : InsertOnOutLine //purpose : //======================================================================= void HLRBRep_PolyAlgo::InsertOnOutLine (TColStd_Array1OfTransient& PID) { Standard_Address TData2 = 0; Standard_Address PISeg2 = 0; Standard_Address PINod2 = 0; Standard_Address Seg1Indices; Standard_Address Nod1Indices,Nod1RValues; Standard_Address Nod2Indices,Nod2RValues; Handle(HLRAlgo_PolyInternalData)* pid = (Handle(HLRAlgo_PolyInternalData)*) (&(PID.ChangeValue(1))); TopLoc_Location L; Standard_Boolean insP3,mP3P1,IntOutL; Standard_Integer f,ip1,ip2,ip3;//, i; Standard_Real U3,V3,coef3,X3 = 0.,Y3 = 0.,Z3 = 0.; const gp_Trsf& T = myProj.Transformation(); Standard_Integer nbFace = myFMap.Extent(); for (f = 1; f <= nbFace; f++) { if (!((*pid).IsNull())) { IntOutL = Standard_False; Standard_Address TData1= &((*pid)->TData()); Standard_Address PISeg1= &((*pid)->PISeg()); Standard_Address PINod1= &((*pid)->PINod()); TopoDS_Shape LocalShape = myFMap(f); const TopoDS_Face& F = TopoDS::Face(LocalShape); myBSurf.Initialize(F,Standard_False); myGSurf = BRep_Tool::Surface(F,L); gp_Trsf TT = L.Transformation(); TT.PreMultiply(T); const gp_XYZ& ttlo = TT.TranslationPart(); TTLo[0] = ttlo.X(); TTLo[1] = ttlo.Y(); TTLo[2] = ttlo.Z(); const gp_Mat& ttma = TT.VectorialPart(); TTMa[0][0] = ttma.Value(1,1); TTMa[0][1] = ttma.Value(1,2); TTMa[0][2] = ttma.Value(1,3); TTMa[1][0] = ttma.Value(2,1); TTMa[1][1] = ttma.Value(2,2); TTMa[1][2] = ttma.Value(2,3); TTMa[2][0] = ttma.Value(3,1); TTMa[2][1] = ttma.Value(3,2); TTMa[2][2] = ttma.Value(3,3); #ifdef OCCT_DEBUG if (DoTrace) { cout << " InsertOnOutLine : NbTData " << (*pid)->NbTData() << endl; cout << " InsertOnOutLine : NbPISeg " << (*pid)->NbPISeg() << endl; cout << " InsertOnOutLine : NbPINod " << (*pid)->NbPINod() << endl; } #endif Standard_Integer iseg,nbS; nbS = (*pid)->NbPISeg(); for (iseg = 1; iseg <= nbS; iseg++) { Seg1Indices = ((HLRAlgo_Array1OfPISeg*)PISeg1)->ChangeValue(iseg).Indices(); // Standard_Boolean Cutted = Standard_False; if (Seg1Conex1 != 0 && Seg1Conex2 != 0) { ip1 = Seg1LstSg1; ip2 = Seg1LstSg2; const Handle(HLRAlgo_PolyInternalNode)* pip1 = &(((HLRAlgo_Array1OfPINod*)PINod1)->ChangeValue(ip1)); Nod1Indices = (*pip1)->Indices(); Nod1RValues = (*pip1)->RValues(); const Handle(HLRAlgo_PolyInternalNode)* pip2 = &(((HLRAlgo_Array1OfPINod*)PINod1)->ChangeValue(ip2)); Nod2Indices = (*pip2)->Indices(); Nod2RValues = (*pip2)->RValues(); if (Nod1Flag & NMskOutL && Nod2Flag & NMskOutL) IntOutL = Standard_True; else if ((Nod1Scal >= myTolAngular && Nod2Scal <= -myTolAngular) || (Nod2Scal >= myTolAngular && Nod1Scal <= -myTolAngular)) { IntOutL = Standard_True; insP3 = NewNode(Nod1RValues,Nod2RValues,coef3,mP3P1); if (insP3) { UVNode(Nod1RValues,Nod2RValues,coef3,U3,V3); const gp_Pnt& PT3 = myGSurf->Value(U3,V3); X3 = PT3.X(); Y3 = PT3.Y(); Z3 = PT3.Z(); TTMultiply(X3,Y3,Z3); } if (insP3 && mP3P1) { // P1 ---> P3 if ((Nod1Flag & NMskEdge) == 0 && coef3 < myTolSta) { insP3 = Standard_False; ChangeNode(ip1,ip2, Nod1Indices,Nod1RValues, Nod2Indices,Nod2RValues, coef3,X3,Y3,Z3,Standard_True, TData1,PISeg1,PINod1); Nod1Scal = 0; Nod1Flag |= NMskOutL; } } if (insP3 && !mP3P1) { // P2 ---> P3 if ((Nod2Flag & NMskEdge) == 0 && coef3 > myTolEnd) { insP3 = Standard_False; ChangeNode(ip1,ip2, Nod1Indices,Nod1RValues, Nod2Indices,Nod2RValues, coef3,X3,Y3,Z3,Standard_False, TData1,PISeg1,PINod1); Nod2Scal = 0; Nod2Flag |= NMskOutL; } } if (insP3) { // p1 ip3 p2 ip3 = (*pid)->AddNode(Nod1RValues,Nod2RValues,PINod1,PINod2, coef3,X3,Y3,Z3); const Handle(HLRAlgo_PolyInternalNode)* pip3 = (&((HLRAlgo_Array1OfPINod*)PINod1)->ChangeValue(ip3)); const Standard_Address Nod3Indices = (*pip3)->Indices(); const Standard_Address Nod3RValues = (*pip3)->RValues(); (*pid)->UpdateLinks(ip1,ip2,ip3, TData1,TData2,PISeg1,PISeg2,PINod1,PINod2); UpdateAroundNode(ip3,Nod3Indices,TData1,PISeg1,PINod1); Nod3Scal = 0; Nod3Flag |= NMskOutL; } } } } if (IntOutL) (*pid)->IntOutL(Standard_True); nbS = (*pid)->NbPISeg(); #ifdef OCCT_DEBUG if (DoTrace) { cout << " InsertOnOutLine : NbTData " << (*pid)->NbTData() << endl; cout << " InsertOnOutLine : NbPISeg " << (*pid)->NbPISeg() << endl; cout << " InsertOnOutLine : NbPINod " << (*pid)->NbPINod() << endl; } #endif } pid++; } } //======================================================================= //function : CheckFrBackTriangles //purpose : //======================================================================= void HLRBRep_PolyAlgo::CheckFrBackTriangles (HLRAlgo_ListOfBPoint& List, TColStd_Array1OfTransient& PID) { Standard_Integer f,i,nbN,nbT,nbFace; Standard_Real X1 =0.,Y1 =0.,X2 =0.,Y2 =0.,X3 =0.,Y3 =0.; Standard_Real D1,D2,D3; Standard_Real dd,dX,dY,nX,nY; Standard_Boolean FrBackInList; Standard_Address TData ,PISeg ,PINod ; /* Standard_Address IndexPtr = NULL; const Handle(HLRAlgo_PolyInternalData)& pid1 = *(Handle(HLRAlgo_PolyInternalData)*)&(PID(F1Index)); Standard_Address TData1 = &pid1->TData(), PISeg1 = &pid1->PISeg(), PINod1 = &pid1->PINod(); const Handle(HLRAlgo_PolyInternalData)& pid2 = *(Handle(HLRAlgo_PolyInternalData)*)&(PID(F2Index)); Standard_Address TData2 = &pid2->TData(), PISeg2 = &pid2->PISeg(), PINod2 = &pid2->PISeg();*/ Standard_Address TData1 = NULL,PISeg1 = NULL,PINod1 = NULL; Standard_Address TData2 = NULL,PISeg2 = NULL,PINod2 = NULL; Standard_Address Nod11Indices,Nod12Indices,Nod13Indices; Standard_Address Nod11RValues,Nod12RValues,Nod13RValues; Standard_Address Tri1Indices; Handle(HLRAlgo_PolyInternalData)* pid; nbFace = myFMap.Extent(); Standard_Boolean Modif = Standard_True; Standard_Integer iLoop = 0; while (Modif && iLoop < 4) { iLoop++; Modif = Standard_False; FrBackInList = Standard_False; pid = (Handle(HLRAlgo_PolyInternalData)*)&(PID.ChangeValue(1)); for (f = 1; f <= nbFace; f++) { if (!(*pid).IsNull()) { nbT = (*pid)->NbTData(); TData = &(*pid)->TData(); PISeg = &(*pid)->PISeg(); PINod = &(*pid)->PINod(); HLRAlgo_TriangleData* tdata = &(((HLRAlgo_Array1OfTData*)TData)->ChangeValue(1)); for (i = 1; i <= nbT; i++) { Tri1Indices = tdata->Indices(); if ((Tri1Flags & FMskSide) == 0 && (Tri1Flags & FMskFrBack)) { #ifdef OCCT_DEBUG if (DoTrace) cout << " face : " << f << " , triangle " << i << endl; #endif Modif = Standard_True; const Handle(HLRAlgo_PolyInternalNode)* pi1p1 = &(((HLRAlgo_Array1OfPINod*)PINod)->ChangeValue(Tri1Node1)); Nod11Indices = (*pi1p1)->Indices(); Nod11RValues = (*pi1p1)->RValues(); const Handle(HLRAlgo_PolyInternalNode)* pi1p2 = &(((HLRAlgo_Array1OfPINod*)PINod)->ChangeValue(Tri1Node2)); Nod12Indices = (*pi1p2)->Indices(); Nod12RValues = (*pi1p2)->RValues(); const Handle(HLRAlgo_PolyInternalNode)* pi1p3 = &(((HLRAlgo_Array1OfPINod*)PINod)->ChangeValue(Tri1Node3)); Nod13Indices = (*pi1p3)->Indices(); Nod13RValues = (*pi1p3)->RValues(); D1 = 0.; D2 = 0.; D3 = 0.; if (((Nod11Flag & NMskEdge) == 0 || iLoop > 1) && ((Nod11Flag & NMskOutL) == 0 || iLoop > 1) && ((Nod11Flag & NMskVert) == 0)) { dX = Nod13PntX - Nod12PntX; dY = Nod13PntY - Nod12PntY; D1 = dX * dX + dY * dY; D1 = sqrt(D1); nX = - dY / D1; nY = dX / D1; dX = Nod11PntX - Nod12PntX; dY = Nod11PntY - Nod12PntY; dd = - (dX * nX + dY * nY); if (dd < 0) dd -= D1 * 0.01; else dd += D1 * 0.01; X1 = nX * dd; Y1 = nY * dd; } if (((Nod12Flag & NMskEdge) == 0 || iLoop > 1) && ((Nod12Flag & NMskOutL) == 0 || iLoop > 1) && ((Nod12Flag & NMskVert) == 0)) { dX = Nod11PntX - Nod13PntX; dY = Nod11PntY - Nod13PntY; D2 = dX * dX + dY * dY; D2 = sqrt(D2); nX = - dY / D2; nY = dX / D2; dX = Nod12PntX - Nod13PntX; dY = Nod12PntY - Nod13PntY; dd = - (dX * nX + dY * nY); if (dd < 0) dd -= D2 * 0.01; else dd += D2 * 0.01; X2 = nX * dd; Y2 = nY * dd; } if (((Nod13Flag & NMskEdge) == 0 || iLoop > 1) && ((Nod13Flag & NMskOutL) == 0 || iLoop > 1) && ((Nod13Flag & NMskVert) == 0)) { dX = Nod12PntX - Nod11PntX; dY = Nod12PntY - Nod11PntY; D3 = dX * dX + dY * dY; D3 = sqrt(D3); nX = - dY / D3; nY = dX / D3; dX = Nod13PntX - Nod11PntX; dY = Nod13PntY - Nod11PntY; dd = - (dX * nX + dY * nY); if (dd < 0) dd -= D3 * 0.01; else dd += D3 * 0.01; X3 = nX * dd; Y3 = nY * dd; } if (D1 > D2 && D1 > D3) { Nod11PntX += X1; Nod11PntY += Y1; Nod11Flag |= NMskMove; UpdateAroundNode(Tri1Node1,Nod11Indices,TData,PISeg,PINod); FrBackInList = Standard_True; #ifdef OCCT_DEBUG if (DoTrace) { cout << Tri1Node1 << " modifies : DX,DY "; cout << X1 << " , " << Y1 << endl; } #endif } else if (D2 > D3 && D2 > D1) { Nod12PntX += X2; Nod12PntY += Y2; Nod12Flag |= NMskMove; UpdateAroundNode(Tri1Node2,Nod12Indices,TData,PISeg,PINod); FrBackInList = Standard_True; #ifdef OCCT_DEBUG if (DoTrace) { cout << Tri1Node2 << " modifies : DX,DY "; cout << X2 << " , " << Y2 << endl; } #endif } else if (D3 > D1 && D3 > D2) { Nod13PntX += X3; Nod13PntY += Y3; Nod13Flag |= NMskMove; UpdateAroundNode(Tri1Node3,Nod13Indices,TData,PISeg,PINod); FrBackInList = Standard_True; #ifdef OCCT_DEBUG if (DoTrace) { cout << Tri1Node3 << " modifies : DX,DY "; cout << X3 << " , " << Y3 << endl; } #endif } #ifdef OCCT_DEBUG else if (DoTrace) cout << "modification error" << endl; #endif } tdata++; } } pid++; } if (FrBackInList) { Standard_Address IndexPtr,Coordinates; HLRAlgo_ListIteratorOfListOfBPoint it; for (it.Initialize(List); it.More(); it.Next()) { HLRAlgo_BiPoint& BP = it.Value(); IndexPtr = BP.Indices(); if (F1Index != 0) { const Handle(HLRAlgo_PolyInternalData)& pid1 = *(Handle(HLRAlgo_PolyInternalData)*)&(PID(F1Index)); TData1 = &pid1->TData(); PISeg1 = &pid1->PISeg(); PINod1 = &pid1->PINod(); } if (F2Index != 0) { if (F1Index == F2Index) { TData2 = TData1; PISeg2 = PISeg1; PINod2 = PINod1; } else { const Handle(HLRAlgo_PolyInternalData)& pid2 = *(Handle(HLRAlgo_PolyInternalData)*)&(PID(F2Index)); TData2 = &pid2->TData(); PISeg2 = &pid2->PISeg(); PINod2 = &pid2->PINod(); } } if (F1Index != 0) { Nod11Indices = (((HLRAlgo_Array1OfPINod*)PINod1)-> ChangeValue(F1Pt1Index))->Indices(); if (Nod11Flag & NMskMove) { #ifdef OCCT_DEBUG if (DoTrace) cout << F1Pt1Index << " modifies 11" << endl; #endif Nod11RValues = (((HLRAlgo_Array1OfPINod*)PINod1)-> ChangeValue(F1Pt1Index))->RValues(); Coordinates = BP.Coordinates(); PntXTI1 = PntX1 = Nod11PntX; PntYTI1 = PntY1 = Nod11PntY; PntZTI1 = PntZ1 = Nod11PntZ; TIMultiply(PntXTI1,PntYTI1,PntZTI1); if (F2Index != 0) { Nod12Indices = (((HLRAlgo_Array1OfPINod*)PINod2)-> ChangeValue(F2Pt1Index))->Indices(); Nod12RValues = (((HLRAlgo_Array1OfPINod*)PINod2)-> ChangeValue(F2Pt1Index))->RValues(); Nod12PntX = Nod11PntX; Nod12PntY = Nod11PntY; UpdateAroundNode(F2Pt1Index,Nod12Indices, TData2,PISeg2,PINod2); } } Nod11Indices = (((HLRAlgo_Array1OfPINod*)PINod1)-> ChangeValue(F1Pt2Index))->Indices(); if (Nod11Flag & NMskMove) { #ifdef OCCT_DEBUG if (DoTrace) cout << F1Pt2Index << " modifies 12" << endl; #endif Nod11RValues = (((HLRAlgo_Array1OfPINod*)PINod1)-> ChangeValue(F1Pt2Index))->RValues(); Coordinates = BP.Coordinates(); PntXTI2 = PntX2 = Nod11PntX; PntYTI2 = PntY2 = Nod11PntY; PntZTI2 = PntZ2 = Nod11PntZ; TIMultiply(PntXTI2,PntYTI2,PntZTI2); if (F2Index != 0) { Nod12Indices = (((HLRAlgo_Array1OfPINod*)PINod2)-> ChangeValue(F2Pt2Index))->Indices(); Nod12RValues = (((HLRAlgo_Array1OfPINod*)PINod2)-> ChangeValue(F2Pt2Index))->RValues(); Nod12PntX = Nod11PntX; Nod12PntY = Nod11PntY; UpdateAroundNode(F2Pt2Index,Nod12Indices, TData2,PISeg2,PINod2); } } } if (F2Index != 0) { const Handle(HLRAlgo_PolyInternalData)& pid2 = *(Handle(HLRAlgo_PolyInternalData)*)&(PID(F2Index)); PINod2 = &pid2->PINod(); Nod11Indices = (((HLRAlgo_Array1OfPINod*)PINod2)-> ChangeValue(F2Pt1Index))->Indices(); if (Nod11Flag & NMskMove) { #ifdef OCCT_DEBUG if (DoTrace) cout << F2Pt1Index << " modifies 21" << endl; #endif Nod11RValues = (((HLRAlgo_Array1OfPINod*)PINod2)-> ChangeValue(F2Pt1Index))->RValues(); Coordinates = BP.Coordinates(); PntXTI1 = PntX1 = Nod11PntX; PntYTI1 = PntY1 = Nod11PntY; PntZTI1 = PntZ1 = Nod11PntZ; TIMultiply(PntXTI1,PntYTI1,PntZTI1); if (F1Index != 0) { Nod12Indices = (((HLRAlgo_Array1OfPINod*)PINod1)-> ChangeValue(F1Pt1Index))->Indices(); Nod12RValues = (((HLRAlgo_Array1OfPINod*)PINod1)-> ChangeValue(F1Pt1Index))->RValues(); Nod12PntX = Nod11PntX; Nod12PntY = Nod11PntY; UpdateAroundNode(F1Pt1Index,Nod12Indices, TData1,PISeg1,PINod1); } } Nod11Indices = (((HLRAlgo_Array1OfPINod*)PINod2)-> ChangeValue(F2Pt2Index))->Indices(); if (Nod11Flag & NMskMove) { #ifdef OCCT_DEBUG if (DoTrace) cout << F2Pt2Index << " modifies 22" << endl; #endif Nod11RValues = (((HLRAlgo_Array1OfPINod*)PINod2)-> ChangeValue(F2Pt2Index))->RValues(); Coordinates = BP.Coordinates(); PntXTI2 = PntX2 = Nod11PntX; PntYTI2 = PntY2 = Nod11PntY; PntZTI2 = PntZ2 = Nod11PntZ; TIMultiply(PntXTI2,PntYTI2,PntZTI2); if (F1Index != 0) { Nod12Indices = (((HLRAlgo_Array1OfPINod*)PINod1)-> ChangeValue(F1Pt2Index))->Indices(); Nod12RValues = (((HLRAlgo_Array1OfPINod*)PINod1)-> ChangeValue(F1Pt2Index))->RValues(); Nod12PntX = Nod11PntX; Nod12PntY = Nod11PntY; UpdateAroundNode(F1Pt2Index,Nod12Indices, TData1,PISeg1,PINod1); } } } } pid = (Handle(HLRAlgo_PolyInternalData)*)&(PID.ChangeValue(1)); for (f = 1; f <= nbFace; f++) { if (!(*pid).IsNull()) { nbN = (*pid)->NbPINod(); PINod = &(*pid)->PINod(); Handle(HLRAlgo_PolyInternalNode)* NN = &(((HLRAlgo_Array1OfPINod*)PINod)->ChangeValue(1)); for (i = 1; i <= nbN; i++) { Nod11Indices = (*NN)->Indices(); Nod11Flag &= ~NMskMove; NN++; } } pid++; } } } } //======================================================================= //function : FindEdgeOnTriangle //purpose : //======================================================================= void HLRBRep_PolyAlgo:: FindEdgeOnTriangle (const Standard_Address Tri1Indices, const Standard_Integer ip1, const Standard_Integer ip2, Standard_Integer& jtrouv, Standard_Boolean& isDirect) const { Standard_Integer n1 = Tri1Node1; Standard_Integer n2 = Tri1Node2; Standard_Integer n3 = Tri1Node3; if (ip1 == n1 && ip2 == n2) { jtrouv = 0; isDirect = Standard_True; return; } else if (ip2 == n1 && ip1 == n2) { jtrouv = 0; isDirect = Standard_False; return; } else if (ip1 == n2 && ip2 == n3) { jtrouv = 1; isDirect = Standard_True; return; } else if (ip2 == n2 && ip1 == n3) { jtrouv = 1; isDirect = Standard_False; return; } else if (ip1 == n3 && ip2 == n1) { jtrouv = 2; isDirect = Standard_True; return; } else if (ip2 == n3 && ip1 == n1) { jtrouv = 2; isDirect = Standard_False; return; } } //======================================================================= //function : ChangeNode //purpose : //======================================================================= void HLRBRep_PolyAlgo::ChangeNode (const Standard_Integer ip1, const Standard_Integer ip2, const Standard_Address Nod1Indices, const Standard_Address Nod1RValues, const Standard_Address Nod2Indices, const Standard_Address Nod2RValues, const Standard_Real coef1, const Standard_Real X3, const Standard_Real Y3, const Standard_Real Z3, const Standard_Boolean first, Standard_Address& TData, Standard_Address& PISeg, Standard_Address& PINod) const { Standard_Real coef2 = 1 - coef1; if (first) { Nod1PntX = X3; Nod1PntY = Y3; Nod1PntZ = Z3; Nod1PntU = Nod1PntU * coef2 + Nod2PntU * coef1; Nod1PntV = Nod1PntV * coef2 + Nod2PntV * coef1; Nod1Scal = Nod1Scal * coef2 + Nod2Scal * coef1; Standard_Real x = Nod1NrmX * coef2 + Nod2NrmX * coef1; Standard_Real y = Nod1NrmY * coef2 + Nod2NrmY * coef1; Standard_Real z = Nod1NrmZ * coef2 + Nod2NrmZ * coef1; Standard_Real D = sqrt (x * x + y * y + z * z); if (D > 0) { Nod1NrmX = x / D; Nod1NrmY = y / D; Nod1NrmZ = z / D; } else { Nod1NrmX = 1; Nod1NrmY = 0; Nod1NrmZ = 0; #ifdef OCCT_DEBUG if (DoError) { cout << "HLRBRep_PolyAlgo::ChangeNode between " << ip1; cout << " and " << ip2 << endl; } #endif } UpdateAroundNode(ip1,Nod1Indices,TData,PISeg,PINod); } else { Nod2PntX = X3; Nod2PntY = Y3; Nod2PntZ = Z3; Nod2PntU = Nod1PntU * coef2 + Nod2PntU * coef1; Nod2PntV = Nod1PntV * coef2 + Nod2PntV * coef1; Nod2Scal = Nod1Scal * coef2 + Nod2Scal * coef1; Standard_Real x = Nod1NrmX * coef2 + Nod2NrmX * coef1; Standard_Real y = Nod1NrmY * coef2 + Nod2NrmY * coef1; Standard_Real z = Nod1NrmZ * coef2 + Nod2NrmZ * coef1; Standard_Real D = sqrt (x * x + y * y + z * z); if (D > 0) { D = 1 / D; Nod2NrmX = x * D; Nod2NrmY = y * D; Nod2NrmZ = z * D; } else { Nod2NrmX = 1; Nod2NrmY = 0; Nod2NrmZ = 0; #ifdef OCCT_DEBUG if (DoError) { cout << "HLRBRep_PolyAlgo::ChangeNode between " << ip2; cout << " and " << ip1 << endl; } #endif } UpdateAroundNode(ip2,Nod2Indices,TData,PISeg,PINod); } } //======================================================================= //function : UpdateAroundNode //purpose : //======================================================================= void HLRBRep_PolyAlgo:: UpdateAroundNode (const Standard_Integer iNode, const Standard_Address Nod1Indices, const Standard_Address TData, const Standard_Address PISeg, const Standard_Address PINod) const { Standard_Integer iiii,iTri1,iTri2; iiii = Nod1NdSg; while (iiii != 0) { const Standard_Address Seg1Indices = ((HLRAlgo_Array1OfPISeg*)PISeg)->ChangeValue(iiii).Indices(); iTri1 = Seg1Conex1; iTri2 = Seg1Conex2; if ( iTri1 != 0) { const Standard_Address Tri1Indices = ((HLRAlgo_Array1OfTData*)TData)->ChangeValue(iTri1).Indices(); const Handle(HLRAlgo_PolyInternalNode)* PN1 = &(((HLRAlgo_Array1OfPINod*)PINod)->ChangeValue(Tri1Node1)); const Handle(HLRAlgo_PolyInternalNode)* PN2 = &(((HLRAlgo_Array1OfPINod*)PINod)->ChangeValue(Tri1Node2)); const Handle(HLRAlgo_PolyInternalNode)* PN3 = &(((HLRAlgo_Array1OfPINod*)PINod)->ChangeValue(Tri1Node3)); const Standard_Address aNod1Indices = (*PN1)->Indices(); const Standard_Address aNod2Indices = (*PN2)->Indices(); const Standard_Address aNod3Indices = (*PN3)->Indices(); const Standard_Address aNod1RValues = (*PN1)->RValues(); const Standard_Address aNod2RValues = (*PN2)->RValues(); const Standard_Address aNod3RValues = (*PN3)->RValues(); OrientTriangle(iTri1,Tri1Indices, aNod1Indices,aNod1RValues, aNod2Indices,aNod2RValues, aNod3Indices,aNod3RValues); } if ( iTri2 != 0) { const Standard_Address Tri2Indices = ((HLRAlgo_Array1OfTData*)TData)->ChangeValue(iTri2).Indices(); const Handle(HLRAlgo_PolyInternalNode)* PN1 = &(((HLRAlgo_Array1OfPINod*)PINod)->ChangeValue(Tri2Node1)); const Handle(HLRAlgo_PolyInternalNode)* PN2 = &(((HLRAlgo_Array1OfPINod*)PINod)->ChangeValue(Tri2Node2)); const Handle(HLRAlgo_PolyInternalNode)* PN3 = &(((HLRAlgo_Array1OfPINod*)PINod)->ChangeValue(Tri2Node3)); const Standard_Address aNod1Indices = (*PN1)->Indices(); const Standard_Address aNod2Indices = (*PN2)->Indices(); const Standard_Address aNod3Indices = (*PN3)->Indices(); const Standard_Address aNod1RValues = (*PN1)->RValues(); const Standard_Address aNod2RValues = (*PN2)->RValues(); const Standard_Address aNod3RValues = (*PN3)->RValues(); OrientTriangle(iTri2,Tri2Indices, aNod1Indices,aNod1RValues, aNod2Indices,aNod2RValues, aNod3Indices,aNod3RValues); } if (Seg1LstSg1 == iNode) iiii = Seg1NxtSg1; else iiii = Seg1NxtSg2; } } //======================================================================= //function : OrientTriangle //purpose : //======================================================================= void #ifdef OCCT_DEBUG HLRBRep_PolyAlgo::OrientTriangle(const Standard_Integer iTri, #else HLRBRep_PolyAlgo::OrientTriangle(const Standard_Integer, #endif const Standard_Address Tri1Indices, const Standard_Address Nod1Indices, const Standard_Address Nod1RValues, const Standard_Address Nod2Indices, const Standard_Address Nod2RValues, const Standard_Address Nod3Indices, const Standard_Address Nod3RValues) const { Standard_Boolean o1 = Nod1Flag & NMskOutL; Standard_Boolean o2 = Nod2Flag & NMskOutL; Standard_Boolean o3 = Nod3Flag & NMskOutL; Tri1Flags &= ~FMskFlat; Tri1Flags &= ~FMskOnOutL; if (o1 && o2 && o3) { Tri1Flags |= FMskSide; Tri1Flags &= ~FMskBack; Tri1Flags |= FMskOnOutL; #ifdef OCCT_DEBUG if (DoTrace) { cout << "HLRBRep_PolyAlgo::OrientTriangle : OnOutL"; cout << " triangle " << iTri << endl; } #endif } else { Standard_Real s1 = Nod1Scal; Standard_Real s2 = Nod2Scal; Standard_Real s3 = Nod3Scal; Standard_Real as1 = s1; Standard_Real as2 = s2; Standard_Real as3 = s3; if (s1 < 0) as1 = -s1; if (s2 < 0) as2 = -s2; if (s3 < 0) as3 = -s3; Standard_Real s = 0; Standard_Real as = 0; if (!o1 ) {s = s1; as = as1;} if (!o2 && as < as2) {s = s2; as = as2;} if (!o3 && as < as3) {s = s3; as = as3;} if (s > 0) { Tri1Flags &= ~FMskSide; Tri1Flags |= FMskBack; } else { Tri1Flags &= ~FMskSide; Tri1Flags &= ~FMskBack; } Standard_Real dx12 = Nod2PntX - Nod1PntX; Standard_Real dy12 = Nod2PntY - Nod1PntY; Standard_Real dz12 = Nod2PntZ - Nod1PntZ; Standard_Real d12 = sqrt(dx12 * dx12 + dy12 * dy12 + dz12 * dz12); if (d12 <= 1.e-10) { #ifdef OCCT_DEBUG if (DoTrace) { cout << "HLRBRep_PolyAlgo::OrientTriangle : Flat"; cout << " triangle " << iTri << endl; } #endif Tri1Flags |= FMskFlat; Tri1Flags |= FMskSide; Tri1Flags &= ~FMskBack; } else { Standard_Real dx23 = Nod3PntX - Nod2PntX; Standard_Real dy23 = Nod3PntY - Nod2PntY; Standard_Real dz23 = Nod3PntZ - Nod2PntZ; Standard_Real d23 = sqrt(dx23 * dx23 + dy23 * dy23 + dz23 * dz23); if (d23 < 1.e-10) { #ifdef OCCT_DEBUG if (DoTrace) { cout << "HLRBRep_PolyAlgo::OrientTriangle : Flat"; cout << " triangle " << iTri << endl; } #endif Tri1Flags |= FMskFlat; Tri1Flags |= FMskSide; Tri1Flags &= ~FMskBack; } else { Standard_Real dx31 = Nod1PntX - Nod3PntX; Standard_Real dy31 = Nod1PntY - Nod3PntY; Standard_Real dz31 = Nod1PntZ - Nod3PntZ; Standard_Real d31 = sqrt(dx31 * dx31 + dy31 * dy31 + dz31 * dz31); if (d31 < 1.e-10) { #ifdef OCCT_DEBUG if (DoTrace) { cout << "HLRBRep_PolyAlgo::OrientTriangle : Flat"; cout << " triangle " << iTri << endl; } #endif Tri1Flags |= FMskFlat; Tri1Flags |= FMskSide; Tri1Flags &= ~FMskBack; } else { dx12 /= d12; dy12 /= d12; dz12 /= d12; dx23 /= d23; dy23 /= d23; dz23 /= d23; Standard_Real dx = dy12 * dz23 - dz12 * dy23; Standard_Real dy = dz12 * dx23 - dx12 * dz23; Standard_Real dz = dx12 * dy23 - dy12 * dx23; Standard_Real d = sqrt(dx * dx + dy * dy + dz * dz); if (d < 1.e-5) { #ifdef OCCT_DEBUG if (DoTrace) { cout << "HLRBRep_PolyAlgo::OrientTriangle : Flat"; cout << " triangle " << iTri << endl; } #endif Tri1Flags |= FMskFlat; Tri1Flags |= FMskSide; Tri1Flags &= ~FMskBack; } else { Standard_Real o; if (myProj.Perspective()) { dx /= d; dy /= d; dz /= d; o = ( dz * myProj.Focus() - dx * Nod1PntX - dy * Nod1PntY - dz * Nod1PntZ); } else o = dz / d; if (o < 0) { Tri1Flags |= FMskOrBack; o = -o; } else Tri1Flags &= ~FMskOrBack; if (o < 1.e-10) { Tri1Flags |= FMskSide; Tri1Flags &= ~FMskBack; } } } } } } if ((!(Tri1Flags & FMskBack) && (Tri1Flags & FMskOrBack)) || ( (Tri1Flags & FMskBack) && !(Tri1Flags & FMskOrBack))) Tri1Flags |= FMskFrBack; else Tri1Flags &= ~FMskFrBack; } //======================================================================= //function : Triangles //purpose : //======================================================================= Standard_Boolean HLRBRep_PolyAlgo::Triangles(const Standard_Integer ip1, const Standard_Integer ip2, const Standard_Address Nod1Indices, Standard_Address& PISeg, Standard_Integer& iTri1, Standard_Integer& iTri2) const { Standard_Address Seg1Indices; Standard_Integer iiii = Nod1NdSg; while (iiii != 0) { Seg1Indices = ((HLRAlgo_Array1OfPISeg*)PISeg)->ChangeValue(iiii).Indices(); if (Seg1LstSg1 == ip1) { if (Seg1LstSg2 == ip2) { iTri1 = Seg1Conex1; iTri2 = Seg1Conex2; return Standard_True; } else iiii = Seg1NxtSg1; } else { if (Seg1LstSg1 == ip2) { iTri1 = Seg1Conex1; iTri2 = Seg1Conex2; return Standard_True; } else iiii = Seg1NxtSg2; } } iTri1 = 0; iTri2 = 0; #ifdef OCCT_DEBUG if (DoError) { cout << "HLRBRep_PolyAlgo::Triangles : error"; cout << " between " << ip1 << " and " << ip2 << endl; } #endif return Standard_False; } //======================================================================= //function : NewNode //purpose : //======================================================================= Standard_Boolean HLRBRep_PolyAlgo:: NewNode (const Standard_Address Nod1RValues, const Standard_Address Nod2RValues, Standard_Real& coef1, Standard_Boolean& moveP1) const { Standard_Real TolAng = myTolAngular * 0.5; if ((Nod1Scal >= TolAng && Nod2Scal <= -TolAng) || (Nod2Scal >= TolAng && Nod1Scal <= -TolAng)) { coef1 = Nod1Scal / ( Nod2Scal - Nod1Scal ); if (coef1 < 0) coef1 = - coef1; moveP1 = coef1 < 0.5; return Standard_True; } return Standard_False; } //======================================================================= //function : UVNode //purpose : //======================================================================= void HLRBRep_PolyAlgo::UVNode (const Standard_Address Nod1RValues, const Standard_Address Nod2RValues, const Standard_Real coef1, Standard_Real& U3, Standard_Real& V3) const { Standard_Real coef2 = 1 - coef1; U3 = Nod1PntU * coef2 + Nod2PntU * coef1; V3 = Nod1PntV * coef2 + Nod2PntV * coef1; } //======================================================================= //function : CheckDegeneratedSegment //purpose : //======================================================================= void HLRBRep_PolyAlgo:: CheckDegeneratedSegment(const Standard_Address Nod1Indices, const Standard_Address Nod1RValues, const Standard_Address Nod2Indices, const Standard_Address Nod2RValues) const { Nod1Flag |= NMskFuck; Nod2Flag |= NMskFuck; if ((Nod1Scal >= myTolAngular && Nod2Scal <= -myTolAngular) || (Nod2Scal >= myTolAngular && Nod1Scal <= -myTolAngular)) { Nod1Scal = 0.; Nod1Flag |= NMskOutL; Nod2Scal = 0.; Nod2Flag |= NMskOutL; } } //======================================================================= //function : UpdateOutLines //purpose : //======================================================================= void HLRBRep_PolyAlgo::UpdateOutLines (HLRAlgo_ListOfBPoint& List, TColStd_Array1OfTransient& PID) { Standard_Integer f; Standard_Integer nbFace = myFMap.Extent(); Standard_Real X1 ,Y1 ,Z1 ,X2 ,Y2 ,Z2 ; Standard_Real XTI1,YTI1,ZTI1,XTI2,YTI2,ZTI2; Handle(HLRAlgo_PolyInternalData)* pid = (Handle(HLRAlgo_PolyInternalData)*)&(PID.ChangeValue(1)); for (f = 1; f <= nbFace; f++) { if (!(*pid).IsNull()) { if ((*pid)->IntOutL()) { Standard_Address TData = &((*pid)->TData()); Standard_Address PISeg = &((*pid)->PISeg()); Standard_Address PINod = &((*pid)->PINod()); Standard_Integer i,j,it1,it2,tn1,tn2,tn3,pd,pf; Standard_Address Seg2Indices,Tri1Indices,Tri2Indices; Standard_Boolean outl; Standard_Integer nbS = (*pid)->NbPISeg(); HLRAlgo_PolyInternalSegment* psg = &(((HLRAlgo_Array1OfPISeg*)PISeg)->ChangeValue(1)); for (i = 1; i <= nbS; i++) { Seg2Indices = psg->Indices(); it1 = Seg2Conex1; it2 = Seg2Conex2; if (it1 != 0 && it2 != 0 && it1 != it2) { // debile but sure ! Tri1Indices = ((HLRAlgo_Array1OfTData*)TData)-> ChangeValue(it1).Indices(); Tri2Indices = ((HLRAlgo_Array1OfTData*)TData)-> ChangeValue(it2).Indices(); if (!(Tri1Flags & FMskSide) && !(Tri2Flags & FMskSide)) outl = (Tri1Flags & FMskBack) != (Tri2Flags & FMskBack); else if ( (Tri1Flags & FMskSide) && (Tri2Flags & FMskSide)) outl = Standard_False; else if ( Tri1Flags & FMskSide) outl = !(Tri1Flags & FMskFlat) && !(Tri2Flags & FMskBack); else outl = !(Tri2Flags & FMskFlat) && !(Tri1Flags & FMskBack); if (outl) { pd = Seg2LstSg1; pf = Seg2LstSg2; tn1 = Tri1Node1; tn2 = Tri1Node2; tn3 = Tri1Node3; if (!(Tri1Flags & FMskSide) && (Tri1Flags & FMskOrBack)) { j = tn1; tn1 = tn3; tn3 = j; } if ((tn1 == pd && tn2 == pf) || (tn1 == pf && tn2 == pd)) Tri1Flags |= EMskOutLin1; else if ((tn2 == pd && tn3 == pf) || (tn2 == pf && tn3 == pd)) Tri1Flags |= EMskOutLin2; else if ((tn3 == pd && tn1 == pf) || (tn3 == pf && tn1 == pd)) Tri1Flags |= EMskOutLin3; #ifdef OCCT_DEBUG else if (DoError) { cout << "HLRAlgo_PolyInternalData::UpdateOutLines"; cout << " : segment not found" << endl; } #endif tn1 = Tri2Node1; tn2 = Tri2Node2; tn3 = Tri2Node3; if (!(Tri2Flags & FMskSide) && (Tri2Flags & FMskOrBack)) { j = tn1; tn1 = tn3; tn3 = j; } if ((tn1 == pd && tn2 == pf) || (tn1 == pf && tn2 == pd)) Tri2Flags |= EMskOutLin1; else if ((tn2 == pd && tn3 == pf) || (tn2 == pf && tn3 == pd)) Tri2Flags |= EMskOutLin2; else if ((tn3 == pd && tn1 == pf) || (tn3 == pf && tn1 == pd)) Tri2Flags |= EMskOutLin3; #ifdef OCCT_DEBUG else if (DoError) { cout << "HLRAlgo_PolyInternalData::UpdateOutLines"; cout << " : segment not found" << endl; } #endif Standard_Address Nod1RValues = ((HLRAlgo_Array1OfPINod*)PINod)->ChangeValue(pd)->RValues(); Standard_Address Nod2RValues = ((HLRAlgo_Array1OfPINod*)PINod)->ChangeValue(pf)->RValues(); XTI1 = X1 = Nod1PntX; YTI1 = Y1 = Nod1PntY; ZTI1 = Z1 = Nod1PntZ; XTI2 = X2 = Nod2PntX; YTI2 = Y2 = Nod2PntY; ZTI2 = Z2 = Nod2PntZ; TIMultiply(XTI1,YTI1,ZTI1); TIMultiply(XTI2,YTI2,ZTI2); List.Append(HLRAlgo_BiPoint(XTI1,YTI1,ZTI1,XTI2,YTI2,ZTI2, X1 ,Y1 ,Z1 ,X2 ,Y2 ,Z2 , f,f,pd,pf,f,pd,pf,12)); } } psg++; } } } pid++; } } //======================================================================= //function : UpdateEdgesBiPoints //purpose : //======================================================================= void HLRBRep_PolyAlgo:: UpdateEdgesBiPoints (HLRAlgo_ListOfBPoint& List, const TColStd_Array1OfTransient& PID, const Standard_Boolean closed) { Standard_Integer itri1,itri2,tbid; HLRAlgo_ListIteratorOfListOfBPoint it; for (it.Initialize(List); it.More(); it.Next()) { HLRAlgo_BiPoint& BP = it.Value(); // Standard_Integer i[5]; Standard_Address IndexPtr = BP.Indices(); if (F1Index != 0 && F2Index != 0) { const Handle(HLRAlgo_PolyInternalData)& pid1 = *(Handle(HLRAlgo_PolyInternalData)*)&(PID(F1Index)); const Handle(HLRAlgo_PolyInternalData)& pid2 = *(Handle(HLRAlgo_PolyInternalData)*)&(PID(F2Index)); Standard_Address PISeg1 = &pid1->PISeg(); Standard_Address PISeg2 = &pid2->PISeg(); Standard_Address Nod11Indices = pid1->PINod().ChangeValue(F1Pt1Index)->Indices(); Standard_Address Nod21Indices = pid2->PINod().ChangeValue(F2Pt1Index)->Indices(); Triangles(F1Pt1Index,F1Pt2Index,Nod11Indices,PISeg1,itri1,tbid); Triangles(F2Pt1Index,F2Pt2Index,Nod21Indices,PISeg2,itri2,tbid); if (itri1 != 0 && itri2 != 0) { if (F1Index != F2Index || itri1 != itri2) { Standard_Address TData1 = &pid1->TData(); Standard_Address TData2 = &pid2->TData(); Standard_Address Tri1Indices = ((HLRAlgo_Array1OfTData*)TData1)->ChangeValue(itri1).Indices(); Standard_Address Tri2Indices = ((HLRAlgo_Array1OfTData*)TData2)->ChangeValue(itri2).Indices(); if (closed) { if (((Tri1Flags & FMskBack) && (Tri2Flags & FMskBack)) || ((Tri1Flags & FMskSide) && (Tri2Flags & FMskSide)) || ((Tri1Flags & FMskBack) && (Tri2Flags & FMskSide)) || ((Tri1Flags & FMskSide) && (Tri2Flags & FMskBack))) BP.Hidden(Standard_True); } Standard_Boolean outl; if (!(Tri1Flags & FMskSide) && !(Tri2Flags & FMskSide)) outl = (Tri1Flags & FMskBack) != (Tri2Flags & FMskBack); else if ( (Tri1Flags & FMskSide) && (Tri2Flags & FMskSide)) outl = Standard_False; else if ( (Tri1Flags & FMskSide)) outl = !(Tri1Flags & FMskFlat) && !(Tri2Flags & FMskBack); else outl = !(Tri2Flags & FMskFlat) && !(Tri1Flags & FMskBack); BP.OutLine(outl); } } #ifdef OCCT_DEBUG else if (DoError) { cout << "HLRBRep_PolyAlgo::UpdateEdgesBiPoints : error "; cout << " between " << F1Index << setw(6); cout << " and " << F2Index << endl; } #endif } } } //======================================================================= //function : UpdatePolyData //purpose : //======================================================================= void HLRBRep_PolyAlgo::UpdatePolyData (TColStd_Array1OfTransient& PD, TColStd_Array1OfTransient& PID, const Standard_Boolean closed) { Standard_Integer f,i;//,n[3]; Handle(TColgp_HArray1OfXYZ) HNodes; Handle(HLRAlgo_HArray1OfTData) HTData; Handle(HLRAlgo_HArray1OfPHDat) HPHDat; Standard_Integer nbFace = myFMap.Extent(); Handle(HLRAlgo_PolyInternalData)* pid = (Handle(HLRAlgo_PolyInternalData)*)&(PID.ChangeValue(1)); Handle(HLRAlgo_PolyData)* pd = (Handle(HLRAlgo_PolyData)*)&(PD.ChangeValue(1)); for (f = 1; f <= nbFace; f++) { if (!(*pid).IsNull()) { Standard_Integer nbN = (*pid)->NbPINod(); Standard_Integer nbT = (*pid)->NbTData(); HNodes = new TColgp_HArray1OfXYZ (1,nbN); HTData = new HLRAlgo_HArray1OfTData(1,nbT); TColgp_Array1OfXYZ& Nodes = HNodes->ChangeArray1(); HLRAlgo_Array1OfTData& Trian = HTData->ChangeArray1(); Standard_Address TData = &(*pid)->TData(); Standard_Address PINod = &(*pid)->PINod(); Standard_Integer nbHide = 0; Handle(HLRAlgo_PolyInternalNode)* ON = &(((HLRAlgo_Array1OfPINod*)PINod)->ChangeValue(1)); gp_XYZ * NN = &(Nodes.ChangeValue(1)); for (i = 1; i <= nbN; i++) { const Standard_Address Nod1RValues = (*ON)->RValues(); NN->SetCoord(Nod1PntX,Nod1PntY,Nod1PntZ); ON++; NN++; } HLRAlgo_TriangleData* OT = &(((HLRAlgo_Array1OfTData*)TData)->ChangeValue(1)); HLRAlgo_TriangleData* NT = &(Trian.ChangeValue(1)); Standard_Address Tri1Indices,Tri2Indices; for (i = 1; i <= nbT; i++) { Tri1Indices = OT->Indices(); Tri2Indices = NT->Indices(); if (!(Tri1Flags & FMskSide)) { #ifdef OCCT_DEBUG if ((Tri1Flags & FMskFrBack) && DoTrace) { cout << "HLRBRep_PolyAlgo::ReverseBackTriangle :"; cout << " face " << f << setw(6); cout << " triangle " << i << endl; } #endif if (Tri1Flags & FMskOrBack) { Standard_Integer j = Tri1Node1; Tri1Node1 = Tri1Node3; Tri1Node3 = j; Tri1Flags |= FMskBack; } else Tri1Flags &= ~FMskBack; //Tri1Flags |= FMskBack;//OCC349 } Tri2Node1 = Tri1Node1; Tri2Node2 = Tri1Node2; Tri2Node3 = Tri1Node3; Tri2Flags = Tri1Flags; if (!(Tri2Flags & FMskSide) && (!(Tri2Flags & FMskBack) || !closed)) { Tri2Flags |= FMskHiding; nbHide++; } else Tri2Flags &= ~FMskHiding; OT++; NT++; } if (nbHide > 0) HPHDat = new HLRAlgo_HArray1OfPHDat(1,nbHide); else HPHDat.Nullify(); (*pd)->HNodes(HNodes); (*pd)->HTData(HTData); (*pd)->HPHDat(HPHDat); (*pd)->FaceIndex(f); } pid++; pd++; } } //======================================================================= //function : TMultiply //purpose : //======================================================================= void HLRBRep_PolyAlgo::TMultiply (Standard_Real& X, Standard_Real& Y, Standard_Real& Z, const Standard_Boolean VPO) const { Standard_Real Xt = TMat[0][0]*X + TMat[0][1]*Y + TMat[0][2]*Z + (VPO ? 0 : TLoc[0]);//OCC349 Standard_Real Yt = TMat[1][0]*X + TMat[1][1]*Y + TMat[1][2]*Z + (VPO ? 0 : TLoc[1]);//OCC349 Z = TMat[2][0]*X + TMat[2][1]*Y + TMat[2][2]*Z + (VPO ? 0 : TLoc[2]);//OCC349 X = Xt; Y = Yt; } //======================================================================= //function : TTMultiply //purpose : //======================================================================= void HLRBRep_PolyAlgo::TTMultiply (Standard_Real& X, Standard_Real& Y, Standard_Real& Z, const Standard_Boolean VPO) const { Standard_Real Xt = TTMa[0][0]*X + TTMa[0][1]*Y + TTMa[0][2]*Z + (VPO ? 0 : TTLo[0]);//OCC349 Standard_Real Yt = TTMa[1][0]*X + TTMa[1][1]*Y + TTMa[1][2]*Z + (VPO ? 0 : TTLo[1]);//OCC349 Z = TTMa[2][0]*X + TTMa[2][1]*Y + TTMa[2][2]*Z + (VPO ? 0 : TTLo[2]);//OCC349 X = Xt; Y = Yt; } //======================================================================= //function : TIMultiply //purpose : //======================================================================= void HLRBRep_PolyAlgo::TIMultiply (Standard_Real& X, Standard_Real& Y, Standard_Real& Z, const Standard_Boolean VPO) const { Standard_Real Xt = TIMa[0][0]*X + TIMa[0][1]*Y + TIMa[0][2]*Z + (VPO ? 0 : TILo[0]);//OCC349 Standard_Real Yt = TIMa[1][0]*X + TIMa[1][1]*Y + TIMa[1][2]*Z + (VPO ? 0 : TILo[1]);//OCC349 Z = TIMa[2][0]*X + TIMa[2][1]*Y + TIMa[2][2]*Z + (VPO ? 0 : TILo[2]);//OCC349 X = Xt; Y = Yt; } //======================================================================= //function : Hide //purpose : //======================================================================= void HLRBRep_PolyAlgo::Hide (Standard_Address& Coordinates, HLRAlgo_EdgeStatus& status, TopoDS_Shape& S, Standard_Boolean& reg1, Standard_Boolean& regn, Standard_Boolean& outl, Standard_Boolean& intl) { Standard_Integer index; myAlgo->Hide(Coordinates,status,index,reg1,regn,outl,intl); if (intl) S = myFMap(index); else S = myEMap(index); } //======================================================================= //function : Show //purpose : //======================================================================= void HLRBRep_PolyAlgo::Show (Standard_Address& Coordinates, TopoDS_Shape& S, Standard_Boolean& reg1, Standard_Boolean& regn, Standard_Boolean& outl, Standard_Boolean& intl) { Standard_Integer index; myAlgo->Show(Coordinates,index,reg1,regn,outl,intl); if (intl) S = myFMap(index); else S = myEMap(index); } //======================================================================= //function : OutLinedShape //purpose : //======================================================================= TopoDS_Shape HLRBRep_PolyAlgo::OutLinedShape (const TopoDS_Shape& S) const { TopoDS_Shape Result; if (!S.IsNull()) { BRep_Builder B; B.MakeCompound(TopoDS::Compound(Result)); B.Add(Result,S); TopTools_MapOfShape Map; TopExp_Explorer ex; for (ex.Init(S,TopAbs_EDGE); ex.More(); ex.Next()) Map.Add(ex.Current()); for (ex.Init(S,TopAbs_FACE); ex.More(); ex.Next()) Map.Add(ex.Current()); Standard_Integer nbFace = myFMap.Extent(); if (nbFace > 0) { TopTools_Array1OfShape NewF(1,nbFace); TColStd_Array1OfTransient& Shell = myAlgo->PolyShell(); Standard_Integer nbShell = Shell.Upper(); HLRAlgo_ListIteratorOfListOfBPoint it; for (Standard_Integer iShell = 1; iShell <= nbShell; iShell++) { HLRAlgo_ListOfBPoint& List = (*(Handle(HLRAlgo_PolyShellData)*)&(Shell(iShell)))->Edges(); for (it.Initialize(List); it.More(); it.Next()) { HLRAlgo_BiPoint& BP = it.Value(); if (BP.IntLine()) { Standard_Address IndexPtr = BP.Indices(); if (Map.Contains(myFMap(ShapeIndex))) { Standard_Address Coordinates = BP.Coordinates(); B.Add(Result,BRepLib_MakeEdge (gp_Pnt(PntXTI1,PntYTI1,PntZTI1), gp_Pnt(PntXTI2,PntYTI2,PntZTI2))); } } } } } } return Result; }
[ "salvatore.auriemma@opencascade.com" ]
salvatore.auriemma@opencascade.com
f6f4f3bda903bb66787555e151526f551396daf9
6a86028e73553ff5d6eb2c75bcce6114e8d7fd45
/Game3DMath/Game3DMath/Game3DMathView.h
a02d880c0c589c76d1e6b6abe504f788cb5352a6
[]
no_license
smallinsect/MyGraphics
f4a19a740e2d503195506843c81c2e66dcd88293
86c18824f196f669a346fad02294fa4994506104
refs/heads/master
2022-11-10T03:37:08.626717
2020-06-18T15:58:51
2020-06-18T15:58:51
260,980,094
0
0
null
null
null
null
UTF-8
C++
false
false
1,016
h
 // Game3DMathView.h: CGame3DMathView 类的接口 // #pragma once class CGame3DMathView : public CView { protected: // 仅从序列化创建 CGame3DMathView() noexcept; DECLARE_DYNCREATE(CGame3DMathView) // 特性 public: CGame3DMathDoc* GetDocument() const; // 操作 public: // 重写 public: virtual void OnDraw(CDC* pDC); // 重写以绘制该视图 virtual BOOL PreCreateWindow(CREATESTRUCT& cs); protected: virtual BOOL OnPreparePrinting(CPrintInfo* pInfo); virtual void OnBeginPrinting(CDC* pDC, CPrintInfo* pInfo); virtual void OnEndPrinting(CDC* pDC, CPrintInfo* pInfo); // 实现 public: virtual ~CGame3DMathView(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif protected: // 生成的消息映射函数 protected: DECLARE_MESSAGE_MAP() }; #ifndef _DEBUG // Game3DMathView.cpp 中的调试版本 inline CGame3DMathDoc* CGame3DMathView::GetDocument() const { return reinterpret_cast<CGame3DMathDoc*>(m_pDocument); } #endif
[ "513312514@qq.com" ]
513312514@qq.com
f5080f43817cd3a16e32db38c907c1c27ffb3f6c
a6134a7487b6efd81af9979b9c7540b4991fa643
/include/parse/tree/operator.hpp
9e274b0d2970177ad5974226ed6383ff482bfce2
[ "Zlib" ]
permissive
jesmaz/numbat
ea26b5feeb1caf9a76c0f695f38fbe8675d39d3a
1bf166d04c4782c6f80634f8eb0a6be6c4e30ce6
refs/heads/master
2020-04-12T09:42:51.173981
2016-10-03T14:35:32
2016-10-03T14:35:32
15,372,140
1
0
null
2016-10-03T14:35:33
2013-12-22T07:46:50
C++
UTF-8
C++
false
false
1,385
hpp
#pragma once #include <parse/tree/base.hpp> enum class OPERATION {ADD, AND, AS, ASSIGN, BAND, BNOT, BOR, BXOR, CMPEQ, CMPGT, CMPGTE, CMPLT, CMPLTE, CMPNE, CONCAT, DECREMENT, DIV, IN, INCREMENT, LNOT, MUL, NEG, NONE, OR, REM, SUB}; class GenericOperator : public ParseTreeNode { public: virtual bool isAggregate () {return true;} virtual const BasicArray <ParseTreeNode *> & getArgs () const {return args;} virtual const nir::Instruction * build (nir::Scope * scope); GenericOperator (uint32_t line, uint32_t pos) : ParseTreeNode (line, pos) {} GenericOperator (const string & iden, std::initializer_list <PTNode> args) : ParseTreeNode ((*args.begin ())->getLine (), (*args.begin ())->getPos ()), iden (iden), args (args) {} virtual ~GenericOperator () {delAll (args);} protected: virtual const nir::Instruction * defBuild (nir::Scope * scope)=0; string iden; BasicArray <PTNode> args; private: virtual string strDump (text::PrintMode mode); }; template <OPERATION opp> class SpecificOperator : public GenericOperator { public: SpecificOperator (uint32_t line, uint32_t pos) : GenericOperator (line, pos) {} SpecificOperator (const string & iden, std::initializer_list <PTNode> args) : GenericOperator (iden, args) {} protected: virtual const nir::Instruction * defBuild (nir::Scope * scope); private: };
[ "recursiveowl@gmail.com" ]
recursiveowl@gmail.com
819513c5e507afce5acc6d4a1ad46d52f0ccb2f0
e35042d4f2a9840bca02ae8580e7ed74dfa15329
/TicTacToe-Game/GameOverState.hpp
f952559bb7fba0cbba5e640e549c6aa92dee1d3b
[]
no_license
aaronlhh/Tictactoe-Game
e034936ac6afdd6d73bd15207c117ce20f1008dc
703ccebbcbc2cfb85ac21ccd79897a48016e482a
refs/heads/main
2023-04-25T00:14:10.091601
2021-05-07T23:33:48
2021-05-07T23:33:48
362,744,886
0
1
null
2021-05-07T23:33:48
2021-04-29T08:27:58
C++
UTF-8
C++
false
false
537
hpp
// // GameOverState.hpp // TicTacToe-Game // // Created by Aaron Lin on 5/1/21. // #ifndef GameOverState_hpp #define GameOverState_hpp #include "States.hpp" #include "TicTacToeGame.hpp" #include "GameState.hpp" class GameOverState: public States{ public: GameOverState(GameDataRef data); void init(); void handleInput(); void update(float dt); void draw(float dt); private: GameDataRef _data; sf::Sprite _retryButton; sf::Sprite _homeButton; }; #endif /* GameOverState_hpp */
[ "aaron.lhh0401@gmail.com" ]
aaron.lhh0401@gmail.com
198d117c90e7f92498268db9be928980ff7be5f0
fcffe2430120f52b58874daf3eaa9223826834b0
/astar_driver/astar_driver.ino
642fa1ae8e060b01d93b787f15230a4253b5d800
[]
no_license
krame505/feline-telepresence-robot
6b3da66eac183d0786d7ec5eb9d80ad9b8b607f6
d3809b7ac0a11a305034e3ab47ffe4d5b1c277b2
refs/heads/master
2020-11-27T14:50:08.870386
2020-06-25T20:32:35
2020-06-25T20:32:35
229,497,625
1
0
null
null
null
null
UTF-8
C++
false
false
4,422
ino
#include <AStar32U4.h> #include <PololuRPiSlave.h> // Modified servo library // Uses timer3 instead of timer1 to avoid conflict with Pololu motor controller #include <ServoT3.h> struct __attribute__((packed)) Data { bool led; uint16_t batteryMillivolts; bool playNotes; char notes[14]; int16_t leftMotor, rightMotor; int32_t leftEncoder, rightEncoder; int16_t leftSpeed, rightSpeed; bool cameraServoCommand; uint8_t cameraPan, cameraTilt; bool laserServoCommand; uint8_t laserPan, laserTilt; bool laserPower; uint8_t laserPattern; uint8_t dispenseTreatsCode; uint8_t resetCode; }; enum LaserPattern { STEADY, BLINK, RANDOM_WALK }; PololuRPiSlave<struct Data, 5> slave; PololuBuzzer buzzer; AStar32U4Motors motors; #define MIN_VOLTAGE 2500 #define MOTOR_UPDATE_PERIOD 150 #define MOTOR_KP 0.6 #define MOTOR_KI 0.10 #define MOTOR_MAX_I 7500 #define LASER 11 #define LASER_POWER 0.9 #define LASER_BLINK_PERIOD 200 #define LASER_BLINK_DUTY 0.7 #define LASER_WALK_MAX_STEP 1 #define LASER_WALK_PERIOD 10 void setup() { Serial.begin(115200); setup_encoders(); motors.flipM2(true); pinMode(LASER, OUTPUT); // Set up the slave at I2C address 20. slave.init(20); // Play startup sound. buzzer.play("v10>>g16>>>c16"); } void loop() { // Call updateBuffer() before using the buffer, to get the latest // data including recent master writes. slave.updateBuffer(); // Write various values into the data structure. slave.buffer.batteryMillivolts = readBatteryMillivoltsLV(); ledYellow(slave.buffer.led); if (slave.buffer.resetCode == 0xBB) { slave.buffer.resetCode = 0; asm volatile ("jmp 0"); } // Playing music involves both reading and writing, since we only // want to do it once. static bool startedPlaying = false; if (slave.buffer.playNotes && !startedPlaying) { buzzer.play(slave.buffer.notes); startedPlaying = true; } else if (startedPlaying && !buzzer.isPlaying()) { slave.buffer.playNotes = false; startedPlaying = false; } slave.buffer.leftEncoder = getM1Counts(); slave.buffer.rightEncoder = getM2Counts(); static unsigned long nextMotorUpdate = 0; if (millis() > nextMotorUpdate) { nextMotorUpdate += MOTOR_UPDATE_PERIOD; static int32_t lastM1 = getM1Counts(); static int32_t lastM2 = getM2Counts(); int16_t m1Speed = getM1Counts() - lastM1; int16_t m2Speed = getM2Counts() - lastM2; lastM1 = getM1Counts(); lastM2 = getM2Counts(); slave.buffer.leftSpeed = m1Speed; slave.buffer.rightSpeed = m2Speed; int16_t m1TargetSpeed = slave.buffer.leftMotor; int16_t m2TargetSpeed = slave.buffer.rightMotor; static int32_t m1I = 0, m2I = 0; m1I += m1TargetSpeed - m1Speed; m2I += m2TargetSpeed - m2Speed; m1I = max(min(m1I, MOTOR_MAX_I), -MOTOR_MAX_I); m2I = max(min(m2I, MOTOR_MAX_I), -MOTOR_MAX_I); // Reset I if motors are undervolted if (slave.buffer.batteryMillivolts < MIN_VOLTAGE) { m1I = m2I = 0; } int16_t m1Power = MOTOR_KP * m1TargetSpeed + MOTOR_KI * m1I; int16_t m2Power = MOTOR_KP * m2TargetSpeed + MOTOR_KI * m2I; motors.setSpeeds(m2Power, m1Power); } handleCameraServos(slave.buffer.cameraServoCommand); cameraPan(slave.buffer.cameraPan); cameraTilt(slave.buffer.cameraTilt); static unsigned long lastWalkUpdate = millis(); if (slave.buffer.laserPattern == RANDOM_WALK && millis() > lastWalkUpdate + LASER_WALK_PERIOD) { lastWalkUpdate = millis(); slave.buffer.laserServoCommand = true; slave.buffer.laserPan += random(-LASER_WALK_MAX_STEP, LASER_WALK_MAX_STEP + 1); slave.buffer.laserTilt += random(-LASER_WALK_MAX_STEP, LASER_WALK_MAX_STEP + 1); } handleLaserServos(slave.buffer.laserServoCommand); laserPan(slave.buffer.laserPan); laserTilt(slave.buffer.laserTilt); bool blink_on = true; if (slave.buffer.laserPattern == BLINK) { blink_on = millis() % LASER_BLINK_PERIOD > LASER_BLINK_PERIOD * LASER_BLINK_DUTY; } analogWrite(LASER, slave.buffer.laserPower * 255 * LASER_POWER * blink_on); if (slave.buffer.dispenseTreatsCode == 0xAA) { slave.buffer.dispenseTreatsCode = 0; dispenseTreats(); } // When done WRITING, call finalizeWrites() to make modified // data available to I2C master. // READING the buffer is allowed before or after finalizeWrites(). slave.finalizeWrites(); }
[ "krame505@gmail.com" ]
krame505@gmail.com
489fb0c9875c5f84fa3e36a3ca522a2d5808b569
8aea95c114e07d043d217f51a30807b4642d49a7
/languages/languageDesign/make/languages/facet/source_gen.caches/deps.cp
a25c9a3a3ae839393bb749c834af2548b30cb7c7
[ "LicenseRef-scancode-free-unknown", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
JetBrains/MPS
ec03a005e0eda3055c4e4856a28234b563af92c6
0d2aeaf642e57a86b23268fc87740214daa28a67
refs/heads/master
2023-09-03T15:14:10.508189
2023-09-01T13:25:35
2023-09-01T13:30:22
2,209,077
1,242
309
Apache-2.0
2023-07-25T18:10:10
2011-08-15T09:48:06
JetBrains MPS
UTF-8
C++
false
false
6,492
cp
<?xml version="1.0" encoding="UTF-8"?> <dependenciesRoot> <uses language="l:f3061a53-9226-4cc5-a443-f952ceaf5816:jetbrains.mps.baseLanguage" /> <uses language="l:fd392034-7849-419d-9071-12563d152375:jetbrains.mps.baseLanguage.closures" /> <uses language="l:83888646-71ce-4f1c-9c53-c54016f6ad4f:jetbrains.mps.baseLanguage.collections" /> <uses language="l:f2801650-65d5-424e-bb1b-463a8781b786:jetbrains.mps.baseLanguage.javadoc" /> <uses language="l:760a0a8c-eabb-4521-8bfd-65db761a9ba3:jetbrains.mps.baseLanguage.logging" /> <uses language="l:a247e09e-2435-45ba-b8d2-07e93feba96a:jetbrains.mps.baseLanguage.tuples" /> <uses language="l:df345b11-b8c7-4213-ac66-48d2a9b75d88:jetbrains.mps.baseLanguageInternal" /> <uses language="l:aee9cad2-acd4-4608-aef2-0004f6a1cdbd:jetbrains.mps.lang.actions" /> <uses language="l:af65afd8-f0dd-4942-87d9-63a55f2a9db1:jetbrains.mps.lang.behavior" /> <uses language="l:3f4bc5f5-c6c1-4a28-8b10-c83066ffa4a1:jetbrains.mps.lang.constraints" /> <uses language="l:e51810c5-7308-4642-bcb6-469e61b5dd18:jetbrains.mps.lang.constraints.msg.specification" /> <uses language="l:47257bf3-78d3-470b-89d9-8c3261a61d15:jetbrains.mps.lang.constraints.rules" /> <uses language="l:5dae8159-ab99-46bb-a40d-0cee30ee7018:jetbrains.mps.lang.constraints.rules.kinds" /> <uses language="l:134c38d4-e3af-4d9e-b069-1c7df0a4005d:jetbrains.mps.lang.constraints.rules.skeleton" /> <uses language="l:3ad5badc-1d9c-461c-b7b1-fa2fcd0a0ae7:jetbrains.mps.lang.context" /> <uses language="l:ea3159bf-f48e-4720-bde2-86dba75f0d34:jetbrains.mps.lang.context.defs" /> <uses language="l:ceab5195-25ea-4f22-9b92-103b95ca8c0c:jetbrains.mps.lang.core" /> <uses language="l:f4ad079d-bc71-4ffb-9600-9328705cf998:jetbrains.mps.lang.descriptor" /> <uses language="l:18bc6592-03a6-4e29-a83a-7ff23bde13ba:jetbrains.mps.lang.editor" /> <uses language="l:ad93155d-79b2-4759-b10c-55123e763903:jetbrains.mps.lang.messages" /> <uses language="l:446c26eb-2b7b-4bf0-9b35-f83fa582753e:jetbrains.mps.lang.modelapi" /> <uses language="l:d4615e3b-d671-4ba9-af01-2b78369b0ba7:jetbrains.mps.lang.pattern" /> <uses language="l:86ef8290-12bb-4ca7-947f-093788f263a9:jetbrains.mps.lang.project" /> <uses language="l:3a13115c-633c-4c5c-bbcc-75c4219e9555:jetbrains.mps.lang.quotation" /> <uses language="l:982eb8df-2c96-4bd7-9963-11712ea622e5:jetbrains.mps.lang.resources" /> <uses language="l:b3551702-269c-4f05-ba61-58060cef4292:jetbrains.mps.lang.rulesAndMessages" /> <uses language="l:d8f591ec-4d86-4af2-9f92-a9e93c803ffa:jetbrains.mps.lang.scopes" /> <uses language="l:13744753-c81f-424a-9c1b-cf8943bf4e86:jetbrains.mps.lang.sharedConcepts" /> <uses language="l:7866978e-a0f0-4cc7-81bc-4d213d9375e1:jetbrains.mps.lang.smodel" /> <uses language="l:c72da2b9-7cce-4447-8389-f407dc1158b7:jetbrains.mps.lang.structure" /> <uses language="l:c7fb639f-be78-4307-89b0-b5959c3fa8c8:jetbrains.mps.lang.text" /> <uses language="l:7a5dda62-9140-4668-ab76-d5ed1746f2b2:jetbrains.mps.lang.typesystem" /> <uses language="l:696c1165-4a59-463b-bc5d-902caab85dd0:jetbrains.mps.make.facet" /> <uses language="l:95f8a3e6-f994-4ca0-a65e-763c9bae2d3b:jetbrains.mps.make.script" /> <uses module="3f233e7f-b8a6-46d2-a57f-795d56775243(Annotations)" kind="dp" /> <uses module="6354ebe7-c22a-4a0f-ac54-50b52ab9b065(JDK)" kind="rt+dp" /> <uses module="6ed54515-acc8-4d1e-a16c-9fd6cfe951ea(MPS.Core)" kind="rt+dp" /> <uses module="1ed103c3-3aa6-49b7-9c21-6765ee11f224(MPS.Editor)" kind="rt+dp" /> <uses module="498d89d2-c2e9-11e2-ad49-6cf049e62fe5(MPS.IDEA)" kind="dp" /> <uses module="8865b7a8-5271-43d3-884c-6fd1d9cfdd34(MPS.OpenAPI)" kind="dp" /> <uses module="742f6602-5a2f-4313-aa6e-ae1cd4ffdc61(MPS.Platform)" kind="dp" /> <uses module="4c6a28d1-2c60-478d-b36e-db9b3cbb21fb(closures.runtime)" kind="rt+dp" /> <uses module="9b80526e-f0bf-4992-bdf5-cee39c1833f3(collections.runtime)" kind="rt+dp" /> <uses module="f3061a53-9226-4cc5-a443-f952ceaf5816(jetbrains.mps.baseLanguage)" kind="dp" /> <uses module="a3e4657f-a76c-45bb-bbda-c764596ecc65(jetbrains.mps.baseLanguage.logging.runtime)" kind="rt" /> <uses module="52b81ac7-93fd-4e9e-b972-4995882da6d4(jetbrains.mps.baseLanguage.references.runtime)" kind="rt" /> <uses module="e39e4a59-8cb6-498e-860e-8fa8361c0d90(jetbrains.mps.baseLanguage.scopes)" kind="dp" /> <uses module="a247e09e-2435-45ba-b8d2-07e93feba96a(jetbrains.mps.baseLanguage.tuples)" kind="dp" /> <uses module="d44dab97-aaac-44cb-9745-8a14db674c03(jetbrains.mps.baseLanguage.tuples.runtime)" kind="rt+dp" /> <uses module="34e84b8f-afa8-4364-abcd-a279fddddbe7(jetbrains.mps.editor.runtime)" kind="dp" /> <uses module="2e24a298-44d1-4697-baec-5c424fed3a3b(jetbrains.mps.editorlang.runtime)" kind="dp" /> <uses module="2d3c70e9-aab2-4870-8d8d-6036800e4103(jetbrains.mps.kernel)" kind="dp" /> <uses module="d936855b-48da-4812-a8a0-2bfddd633ac5(jetbrains.mps.lang.behavior.api)" kind="rt+dp" /> <uses module="d936855b-48da-4812-a8a0-2bfddd633ac4(jetbrains.mps.lang.behavior.runtime)" kind="rt+dp" /> <uses module="8e98f4e2-decf-4e97-bf80-9109e8b759ee(jetbrains.mps.lang.constraints.rules.runtime)" kind="rt+dp" /> <uses module="ceab5195-25ea-4f22-9b92-103b95ca8c0c(jetbrains.mps.lang.core)" kind="dp" /> <uses module="9e9ef4e2-decf-4e97-bf80-9109e8b759bb(jetbrains.mps.lang.feedback.api)" kind="dp" /> <uses module="9e98f4e2-decf-4e97-bf80-9109e8b759aa(jetbrains.mps.lang.feedback.context)" kind="dp" /> <uses module="3f98f4e2-decf-4e97-bf80-9109e8b759ab(jetbrains.mps.lang.feedback.problem.rt)" kind="dp" /> <uses module="0a98f3e2-decf-4e97-bf80-9109eccc59bb(jetbrains.mps.lang.feedback.problem.rules)" kind="rt" /> <uses module="9abaaae2-decf-4e97-bf80-9109e8b759cc(jetbrains.mps.lang.messages.api)" kind="rt" /> <uses module="d7eb0a2a-bd50-4576-beae-e4a89db35f20(jetbrains.mps.lang.scopes.runtime)" kind="rt+dp" /> <uses module="c72da2b9-7cce-4447-8389-f407dc1158b7(jetbrains.mps.lang.structure)" kind="dp" /> <uses module="9ded098b-ad6a-4657-bfd9-48636cfe8bc3(jetbrains.mps.lang.traceable)" kind="dp" /> <uses module="696c1165-4a59-463b-bc5d-902caab85dd0(jetbrains.mps.make.facet)" kind="dp" /> <uses module="a1250a4d-c090-42c3-ad7c-d298a3357dd4(jetbrains.mps.make.runtime)" kind="rt+dp" /> <uses module="95f8a3e6-f994-4ca0-a65e-763c9bae2d3b(jetbrains.mps.make.script)" kind="dp" /> <uses module="9a4afe51-f114-4595-b5df-048ce3c596be(jetbrains.mps.runtime)" kind="rt+dp" /> </dependenciesRoot>
[ "tikhomirov.artem@gmail.com" ]
tikhomirov.artem@gmail.com
00e51df9c57b45e74ce2ba47718606e9becf1293
a2a7706d59ab0d726f0ef0dd84d44531a8c87256
/tests/madoka_iso-2022-jp/time_tone.cpp
501eddb959717792639140c0f9122c1e766728a6
[ "MIT" ]
permissive
cre-ne-jp/irclog2json
485e21d087be4618ef30c05b724413733492ba59
721f9c6f247ae9d972dff8c1b3befa36bb1e062e
refs/heads/master
2021-11-18T19:16:28.591033
2021-09-19T15:45:24
2021-09-19T15:45:24
204,485,550
0
0
null
2021-09-11T14:45:24
2019-08-26T13:49:23
C++
UTF-8
C++
false
false
1,380
cpp
/** * @file time_tone.cpp * @brief ISO-2022-JPのMadoka形式ログの時報のテスト。SEGV検出のために追加した。 */ #define _XOPEN_SOURCE #include <doctest/doctest.h> #include <ctime> #include <string> #include <picojson.h> #include "message/message_base.h" #include "message/madoka_iso_2022_jp_line_parser.h" #include "message/madoka_line_parser.h" #include "tests/test_helper.h" TEST_CASE("Madoka ISO-2022-JP time tone") { using irclog2json::message::MadokaIso2022JpLineParser; using irclog2json::message::MadokaLineParser; struct tm tm_date {}; strptime("2000-02-27", "%F", &tm_date); const std::string channel{"kataribe"}; auto parser_madoka = std::make_unique<MadokaLineParser>(channel, tm_date); MadokaIso2022JpLineParser parser{std::move(parser_madoka)}; const auto m = parser.ToMessage("2000/02/07 03:00:00"); REQUIRE_FALSE(m); } TEST_CASE("Madoka ISO-2022-JP time tone at EOF") { using irclog2json::message::MadokaIso2022JpLineParser; using irclog2json::message::MadokaLineParser; struct tm tm_date {}; strptime("2000-02-07", "%F", &tm_date); const std::string channel{"kataribe"}; auto parser_madoka = std::make_unique<MadokaLineParser>(channel, tm_date); MadokaIso2022JpLineParser parser{std::move(parser_madoka)}; const auto m = parser.ToMessage("2000/02/08 00:00:00 end"); REQUIRE_FALSE(m); }
[ "ochaochaocha3@gmail.com" ]
ochaochaocha3@gmail.com
feea1d90f4a2f0cb66667ebc833367a1115907e7
88028ec82ceb71ffe274da22cfeff5b529636554
/vtkVofLabelPoints/vtkVofLabelPoints.cxx
d3c9e3124e2c2db07eeabaf9bf5eef3a2d586a64
[]
no_license
grzegorz-k-karch/VofTopo
47d9b112d5c0c39d19598f89c2a7fb93730976a5
36f5676dcdcefd538a3d8cadf531ef9208adf98b
refs/heads/master
2021-01-19T21:59:21.801275
2016-01-11T18:34:55
2016-01-11T18:34:55
37,942,803
0
1
null
null
null
null
UTF-8
C++
false
false
11,394
cxx
#include "vtkObjectFactory.h" //for new() macro #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkRectilinearGrid.h" #include "vtkPolyData.h" #include "vtkMultiBlockDataSet.h" #include "vtkDataArray.h" #include "vtkFloatArray.h" #include "vtkIntArray.h" #include "vtkShortArray.h" #include "vtkCharArray.h" #include "vtkPointData.h" #include "vtkCellData.h" #include "vtkPoints.h" #include "vtkMPIController.h" #include "vtkVofLabelPoints.h" #include <vector> #include <cmath> vtkStandardNewMacro(vtkVofLabelPoints); namespace { // unsafe! does not take cell sizes into account int findClosestCoordinate(vtkDataArray *coords, double p) { const int numCoordinates = coords->GetNumberOfTuples(); int coord = 0; double dist = std::abs(coords->GetComponent(0,0)-p); for (int i = 1; i < numCoordinates; ++i) { double curr_dist = std::abs(coords->GetComponent(i,0)-p); if (curr_dist < dist) { dist = curr_dist; coord = i; } } return coord; } int findCell(vtkDataArray *coords, double p) { const int numCoordinates = coords->GetNumberOfTuples(); int coord = 0; for (int i = 0; i < numCoordinates-1; ++i) { if (p >= coords->GetComponent(i,0) && p <= coords->GetComponent(i+1,0)) { coord = i; break; } } return coord; } typedef struct { int particleId; float label; } i1f1_t; } //----------------------------------------------------------------------------- vtkVofLabelPoints::vtkVofLabelPoints() { this->SetNumberOfInputPorts(3); this->Controller = vtkMPIController::New(); } //----------------------------------------------------------------------------- vtkVofLabelPoints::~vtkVofLabelPoints() { } //---------------------------------------------------------------------------- void vtkVofLabelPoints::AddSourceConnection(vtkAlgorithmOutput* input) { this->AddInputConnection(1, input); } //---------------------------------------------------------------------------- void vtkVofLabelPoints::RemoveAllSources() { this->SetInputConnection(1, 0); } //---------------------------------------------------------------------------- int vtkVofLabelPoints::FillInputPortInformation(int port, vtkInformation* info) { if (!this->Superclass::FillInputPortInformation(port, info)) { return 0; } if (port == 0) { info->Set( vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkRectilinearGrid"); return 1; } if (port == 1) { info->Set( vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkPolyData"); return 1; } if (port == 2) { info->Set( vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkPolyData"); return 1; } return 0; } //---------------------------------------------------------------------------- int vtkVofLabelPoints::RequestData(vtkInformation *request, vtkInformationVector **inputVector, vtkInformationVector *outputVector) { int processId = 0; int numProcesses = Controller->GetNumberOfProcesses(); if (numProcesses > 0) { processId = Controller->GetLocalProcessId(); } // get the info objects vtkInformation *inInfoComponents = inputVector[0]->GetInformationObject(0); vtkInformation *inInfoSeeds = inputVector[1]->GetInformationObject(0); vtkInformation *inInfoAdvectedParticles = inputVector[2]->GetInformationObject(0); vtkInformation *outInfo = outputVector->GetInformationObject(0); // get the input vtkRectilinearGrid *inputComponents = vtkRectilinearGrid:: SafeDownCast(inInfoComponents->Get(vtkDataObject::DATA_OBJECT())); vtkPolyData *inputSeeds = vtkPolyData:: SafeDownCast(inInfoSeeds->Get(vtkDataObject::DATA_OBJECT())); vtkPolyData *inputAdvectedParticles = vtkPolyData:: SafeDownCast(inInfoAdvectedParticles->Get(vtkDataObject::DATA_OBJECT())); if (inputComponents == 0 || inputSeeds == 0 || inputAdvectedParticles == 0) { vtkErrorMacro("One of the inputs is empty"); return 0; } vtkCharArray *ifacePoints = vtkCharArray:: SafeDownCast(inputSeeds->GetPointData()->GetArray("InterfacePoints")); if (ifacePoints != NULL) std::cout << "BANGLA" << std::endl; else std::cout << "NIE BANGLA" << std::endl; // output labels for seed points ------------------------------------------- vtkFloatArray *seedPointLabels; float *seedPointLabels_ptr = 0; int numSeeds = inputSeeds->GetNumberOfPoints(); // if (numSeeds > 0) { seedPointLabels = vtkFloatArray::New(); seedPointLabels->SetName("Labels"); seedPointLabels->SetNumberOfComponents(1); seedPointLabels->SetNumberOfTuples(numSeeds); seedPointLabels_ptr = seedPointLabels->GetPointer(0); for (int i = 0; i < numSeeds; ++i) { seedPointLabels_ptr[i] = -1.0f; } // } // output labels for advected particles ------------------------------------ vtkFloatArray *advectedParticleLabels; float *advectedParticleLabels_ptr = 0; int numAdvectedParticles = inputAdvectedParticles->GetNumberOfPoints(); // if (numAdvectedParticles > 0) { advectedParticleLabels = vtkFloatArray::New(); advectedParticleLabels->SetName("Labels"); advectedParticleLabels->SetNumberOfComponents(1); advectedParticleLabels->SetNumberOfTuples(numAdvectedParticles); advectedParticleLabels_ptr = advectedParticleLabels->GetPointer(0); // } std::vector<std::vector<i1f1_t> > labelsToSend; labelsToSend.resize(numProcesses); for (int i = 0; i < numProcesses; ++i) { labelsToSend[i].resize(0); } if (numAdvectedParticles > 0) { int *particleId_ptr = vtkIntArray:: SafeDownCast(inputAdvectedParticles->GetPointData()->GetArray("ParticleId"))->GetPointer(0); short *particleProcessId_ptr = vtkShortArray:: SafeDownCast(inputAdvectedParticles->GetPointData()->GetArray("ParticleProcessId"))-> GetPointer(0); if (particleId_ptr == 0 || particleProcessId_ptr == 0) { vtkErrorMacro("One fo the Id arrays of advected particles is empty"); return 0; } //------------------------------------------------------------------------ vtkDataArray *pointData = inputComponents->GetPointData()->GetArray("Labels"); vtkDataArray *cellData = inputComponents->GetCellData()->GetArray("Labels"); vtkFloatArray *data; if (pointData == 0 && cellData != 0) { // cell data data = vtkFloatArray::SafeDownCast(cellData); } else if (pointData != 0 && cellData == 0) { // point data data = vtkFloatArray::SafeDownCast(pointData); } else { vtkErrorMacro("Can't determine if data is point-based or cell-based"); return 0; } float *componentLabels_ptr = data->GetPointer(0); if (componentLabels_ptr == 0) { vtkErrorMacro("Component labels array is empty"); return 0; } vtkDataArray *coords[3] = {inputComponents->GetXCoordinates(), inputComponents->GetYCoordinates(), inputComponents->GetZCoordinates()}; int res[3]; inputComponents->GetDimensions(res); if (pointData == 0 && cellData != 0) { // cell data res[0] -= 1; res[1] -= 1; res[2] -= 1; } vtkPoints *advectedPoints = inputAdvectedParticles->GetPoints(); for (int i = 0; i < numAdvectedParticles; ++i) { double p[3]; advectedPoints->GetPoint(i, p); int coord[3]; for (int j = 0; j < 3; ++j) { if (pointData != 0 && cellData == 0) { coord[j] = findClosestCoordinate(coords[j], p[j]); } else if (pointData == 0 && cellData != 0) { coord[j] = findCell(coords[j], p[j]); } } int idx = coord[0] + coord[1]*res[0] + coord[2]*res[0]*res[1]; // component label for the given particle advectedParticleLabels_ptr[i] = componentLabels_ptr[idx]; int particleId = particleId_ptr[i]; if (particleId < 0) { particleId = -1*particleId - 1; } if (numProcesses > 0) { int particleProcId = particleProcessId_ptr[i]; // if the particle was seeded in this process, assign the label to corresponding seed if (particleProcId == processId) { seedPointLabels_ptr[particleId] = componentLabels_ptr[idx]; } else { // if the particle was seeded in other process, store the label i1f1_t labelId = {particleId, componentLabels_ptr[idx]}; labelsToSend[particleProcId].push_back(labelId); } } else { seedPointLabels_ptr[particleId] = componentLabels_ptr[idx]; } } } //-------------------------------------------------------------------------- if (numProcesses > 0) { // send labels to particle seeds std::vector<int> numLabelsToSend(numProcesses); std::vector<int> numLabelsToRecv(numProcesses); std::vector<i1f1_t> allLabelsToSend; allLabelsToSend.resize(0); for (int i = 0; i < numProcesses; ++i) { numLabelsToSend[i] = labelsToSend[i].size(); numLabelsToRecv[i] = 0; for (int j = 0; j < labelsToSend[i].size(); ++j) { allLabelsToSend.push_back(labelsToSend[i][j]); } } std::vector<int> RecvLengths(numProcesses); std::vector<int> RecvOffsets(numProcesses); int numAllLabelsToRecv = 0; for (int i = 0; i < numProcesses; ++i) { Controller->Scatter((int*)&numLabelsToSend[0], (int*)&numLabelsToRecv[i], 1, i); RecvOffsets[i] = numAllLabelsToRecv; RecvLengths[i] = numLabelsToRecv[i]*sizeof(i1f1_t); numAllLabelsToRecv += numLabelsToRecv[i]; } std::vector<i1f1_t> labelsToRecv(numAllLabelsToRecv); std::vector<vtkIdType> SendLengths(numProcesses); std::vector<vtkIdType> SendOffsets(numProcesses); int offset = 0; for (int i = 0; i < numProcesses; ++i) { SendLengths[i] = numLabelsToSend[i]*sizeof(i1f1_t); SendOffsets[i] = offset; offset += numLabelsToSend[i]*sizeof(i1f1_t); } for (int i = 0; i < numProcesses; ++i) { Controller->ScatterV((char*)&allLabelsToSend[0], (char*)&labelsToRecv[RecvOffsets[i]], &SendLengths[0], &SendOffsets[0], RecvLengths[i], i); } for (int i = 0; i < labelsToRecv.size(); ++i) { int particleId = labelsToRecv[i].particleId; float label = labelsToRecv[i].label; seedPointLabels_ptr[particleId] = label; } } //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- vtkMultiBlockDataSet *output = vtkMultiBlockDataSet::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT())); output->SetNumberOfBlocks(2); // set output blocks int output_startParticles_Id = 0; { if (numSeeds > 0) { inputSeeds->GetPointData()->AddArray(seedPointLabels); } output->SetBlock(output_startParticles_Id, inputSeeds); } int output_endParticles_Id = 1; { if (numAdvectedParticles > 0) { inputAdvectedParticles->GetPointData()->AddArray(advectedParticleLabels); } output->SetBlock(output_endParticles_Id, inputAdvectedParticles); } return 1; } ////////// External Operators ///////////// void vtkVofLabelPoints::PrintSelf(ostream &os, vtkIndent indent) { }
[ "grzegorz.karch@gmail.com" ]
grzegorz.karch@gmail.com
e9570885a3292a395a6738a8a29f3384358ee32c
9d4b290a800da7b6c643601ee29802b9e783ac96
/src/OgrianFrameListener.cpp
60d9d350c8d0e05f181e64076ad57a95ef72b3f1
[ "MIT", "BSD-3-Clause" ]
permissive
waveclaw/ogrian-carpet
5155720536255e84b11093cf64797c8a09150ddf
e33798cb2203af30f60cbc46d184d917d04e5918
refs/heads/master
2021-09-04T01:12:01.674567
2018-01-13T21:38:24
2018-01-13T21:38:24
117,375,152
1
0
null
null
null
null
UTF-8
C++
false
false
11,166
cpp
/***************************************************************************** Copyright 2004 Mike Prosser This file is part of Ogrian Carpet. Ogrian Carpet 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. Ogrian Carpet 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 Ogrian Carpet; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *****************************************************************************/ /*------------------------------------* OgrianFrameListener.cpp Original Author: The OGRE Team Additional Authors: Mike Prosser Description: This handles keyboard and mouse input. See OgrianFrameListener.h for command listings *------------------------------------*/ #include "OgrianFrameListener.h" namespace Ogrian { //---------------------------------------------------------------------------- void OgrianFrameListener::updateStats(void) { static String currFps = "Current FPS: "; static String avgFps = "Average FPS: "; static String bestFps = "Best FPS: "; static String worstFps = "Worst FPS: "; static String tris = "Triangle Count: "; // update stats when necessary GuiElement* guiAvg = GuiManager::getSingleton().getGuiElement("Core/AverageFps"); GuiElement* guiCurr = GuiManager::getSingleton().getGuiElement("Core/CurrFps"); GuiElement* guiBest = GuiManager::getSingleton().getGuiElement("Core/BestFps"); GuiElement* guiWorst = GuiManager::getSingleton().getGuiElement("Core/WorstFps"); const RenderTarget::FrameStats& stats = mWindow->getStatistics(); guiAvg->setCaption(avgFps + StringConverter::toString(stats.avgFPS)); guiCurr->setCaption(currFps + StringConverter::toString(stats.lastFPS)); guiBest->setCaption(bestFps + StringConverter::toString(stats.bestFPS) +" "+StringConverter::toString(stats.bestFrameTime)+" ms"); guiWorst->setCaption(worstFps + StringConverter::toString(stats.worstFPS) +" "+StringConverter::toString(stats.worstFrameTime)+" ms"); GuiElement* guiTris = GuiManager::getSingleton().getGuiElement("Core/NumTris"); guiTris->setCaption(tris + StringConverter::toString((unsigned int) stats.triangleCount )); GuiElement* guiDbg = GuiManager::getSingleton().getGuiElement("Core/DebugText"); guiDbg->setCaption(mWindow->getDebugText()); } //---------------------------------------------------------------------------- // Constructor takes a RenderWindow because it uses that to determine input context OgrianFrameListener::OgrianFrameListener(RenderWindow* win, Camera* cam, bool useBufferedInputKeys, bool useBufferedInputMouse) { mUseBufferedInputKeys = useBufferedInputKeys; mUseBufferedInputMouse = useBufferedInputMouse; mInputTypeSwitchingOn = mUseBufferedInputKeys || mUseBufferedInputMouse; mInputDevice = PlatformManager::getSingleton().createInputReader(); mInputDevice->initialise(win,true, true); mEventProcessor = new EventProcessor(); mEventProcessor->initialise(win); mEventProcessor->startProcessingEvents(); mEventProcessor->addKeyListener(this); mCamera = cam; mWindow = win; mStatsOn = false; mNumScreenShots = 0; mTimeUntilNextToggle = 0; mSceneDetailIndex = 0; mMoveScale = 0.0f; mRotScale = 0.0f; mTranslateVector = Vector3::ZERO; mAniso = 1; mFiltering = TFO_BILINEAR; mGameRunning = false; mYinvert = true; mCameraFrozen = true; } //---------------------------------------------------------------------------- OgrianFrameListener::~OgrianFrameListener() { if (mInputTypeSwitchingOn) { delete mEventProcessor; } else { PlatformManager::getSingleton().destroyInputReader( mInputDevice ); } } //---------------------------------------------------------------------------- void OgrianFrameListener::setCameraFrozen(bool frozen) { mCameraFrozen = frozen; } //---------------------------------------------------------------------------- bool OgrianFrameListener::getCameraFrozen() { return mCameraFrozen; } //---------------------------------------------------------------------------- bool OgrianFrameListener::processUnbufferedKeyInput(const FrameEvent& evt) { // handle universal keypresses // if (mInputDevice->isKeyDown(KC_F1) && mTimeUntilNextToggle <= 0) { mStatsOn = !mStatsOn; showDebugOverlay(mStatsOn); mTimeUntilNextToggle = CONR("KEY_DELAY"); } if (mInputDevice->isKeyDown(KC_F2) && mTimeUntilNextToggle <= 0) { switch(mFiltering) { case TFO_BILINEAR: mFiltering = TFO_TRILINEAR; mAniso = 1; break; case TFO_TRILINEAR: mFiltering = TFO_ANISOTROPIC; mAniso = 8; break; case TFO_ANISOTROPIC: mFiltering = TFO_BILINEAR; mAniso = 1; break; } MaterialManager::getSingleton().setDefaultTextureFiltering(mFiltering); MaterialManager::getSingleton().setDefaultAnisotropy(mAniso); showDebugOverlay(mStatsOn); mTimeUntilNextToggle = CONR("KEY_DELAY"); } if (mInputDevice->isKeyDown(KC_SYSRQ) && mTimeUntilNextToggle <= 0) { char tmp[20]; sprintf(tmp, "screenshot_%d.png", ++mNumScreenShots); mWindow->writeContentsToFile(tmp); mTimeUntilNextToggle = CONR("KEY_DELAY"); mWindow->setDebugText(String("Wrote ") + tmp); } if (mInputDevice->isKeyDown(KC_F3) && mTimeUntilNextToggle <=0) { mSceneDetailIndex = (mSceneDetailIndex+1)%3 ; switch(mSceneDetailIndex) { case 0 : mCamera->setDetailLevel(SDL_SOLID) ; break ; case 1 : mCamera->setDetailLevel(SDL_WIREFRAME) ; break ; case 2 : mCamera->setDetailLevel(SDL_POINTS) ; break ; } mTimeUntilNextToggle = CONR("KEY_DELAY"); } // handle menu or game keypresses if (Menu::getSingleton().isActive()) { return Menu::getSingleton().processKeyInput(mInputDevice); } else { // handle camera stuff // CameraThing* cam = Renderer::getSingleton().getCameraThing(); // Move camera forward if (mInputDevice->isKeyDown(KC_W)) cam->moveForward(); if (mInputDevice->isKeyDown(KC_UP)) cam->moveForward(); // Move camera back if (mInputDevice->isKeyDown(KC_S)) cam->moveBack(); if (mInputDevice->isKeyDown(KC_DOWN)) cam->moveBack(); // Move camera left if (mInputDevice->isKeyDown(KC_A)) cam->moveLeft(); if (mInputDevice->isKeyDown(KC_LEFT)) cam->moveLeft(); // Move camera right if (mInputDevice->isKeyDown(KC_D)) cam->moveRight(); if (mInputDevice->isKeyDown(KC_RIGHT)) cam->moveRight(); // handle game input // return Input::getSingleton().processKeyInput(mInputDevice); } } //---------------------------------------------------------------------------- void OgrianFrameListener::setInvertY(bool yinv) { mYinvert = yinv; } //---------------------------------------------------------------------------- bool OgrianFrameListener::getInvertY() { return mYinvert; } //---------------------------------------------------------------------------- bool OgrianFrameListener::processUnbufferedMouseInput(const FrameEvent& evt) { // skip if the camera is frozen if (mCameraFrozen) return true; /* Rotation factors, may not be used if the second mouse button is pressed. */ mRotX = -mInputDevice->getMouseRelativeX() * 0.13; // this handles inverting the mouse y axis mRotY = mInputDevice->getMouseRelativeY() * 0.13 * (mYinvert ? 1 : -1); return true; } //---------------------------------------------------------------------------- void OgrianFrameListener::moveCamera() { if (mGameRunning) Renderer::getSingleton().getCameraThing()->moveCamera(mRotX, mRotY); } //---------------------------------------------------------------------------- void OgrianFrameListener::showDebugOverlay(bool show) { Overlay* o = (Overlay*)OverlayManager::getSingleton().getByName("Core/DebugOverlay"); if (!o) Exception( Exception::ERR_ITEM_NOT_FOUND, "Could not find overlay Core/DebugOverlay", "showDebugOverlay" ); if (show) { o->show(); } else { o->hide(); } } //---------------------------------------------------------------------------- // Override frameStarted event to process that (don't care about frameEnded) bool OgrianFrameListener::frameStarted(const FrameEvent& evt) { Game::getSingleton().frame(evt.timeSinceLastFrame); if (mTimeUntilNextToggle >= 0) mTimeUntilNextToggle -= evt.timeSinceLastFrame; // handle input // if (!mInputTypeSwitchingOn) { mInputDevice->capture(); } if (mUseBufferedInputKeys) { // no need to do any processing here, it is handled by event processor and // you get the results as KeyEvents } else { if (processUnbufferedKeyInput(evt) == false) { return false; } } if (mUseBufferedInputMouse) { // no need to do any processing here, it is handled by event processor and // you get the results as MouseEvents } else { if (processUnbufferedMouseInput(evt) == false) { return false; } } if ( !mUseBufferedInputMouse || !mUseBufferedInputKeys) { // one of the input modes is immediate, so update the movement vector moveCamera(); } return true; } //---------------------------------------------------------------------------- void OgrianFrameListener::setGameRunning(bool running) { mGameRunning = running; } //---------------------------------------------------------------------------- bool OgrianFrameListener::getGameRunning() { return mGameRunning; } //---------------------------------------------------------------------------- bool OgrianFrameListener::frameEnded(const FrameEvent& evt) { updateStats(); return true; } //---------------------------------------------------------------------------- void OgrianFrameListener::switchMouseMode() { mUseBufferedInputMouse = !mUseBufferedInputMouse; mInputDevice->setBufferedInput(mUseBufferedInputKeys, mUseBufferedInputMouse); } //---------------------------------------------------------------------------- void OgrianFrameListener::switchKeyMode() { mUseBufferedInputKeys = !mUseBufferedInputKeys; mInputDevice->setBufferedInput(mUseBufferedInputKeys, mUseBufferedInputMouse); } //---------------------------------------------------------------------------- void OgrianFrameListener::keyPressed(KeyEvent* e) { // forwared the keypress to the menu for text entry if (Menu::getSingleton().isActive()) Menu::getSingleton().keyPressed(e); } //---------------------------------------------------------------------------- }
[ "waveclaw@users.sourceforge.net" ]
waveclaw@users.sourceforge.net
59fa0b93b280336ca99895cc98fca5a9cd0977ee
0f4012d03230b59125ac3c618f9b5e5e61d4cc7d
/Cocos2d-x/2.0-x-2.03_branch_231_NoScript/SIX_Framework/Shared_Interface/SIX_UIMgr.h
5250a90ed8a2c024ea88225eb8cab9dd0dd3d2e7
[ "MIT" ]
permissive
daxingyou/SixCocos2d-xVC2012
80d0a8701dda25d8d97ad88b762aadd7e014c6ee
536e5c44b08c965744cd12103d3fabd403051f19
refs/heads/master
2022-04-27T06:41:50.396490
2020-05-01T02:57:20
2020-05-01T02:57:20
null
0
0
null
null
null
null
GB18030
C++
false
false
5,330
h
/*********************************************** Name:UI管理器 Desc:XML<=>UI解析,UI控件管理 Auth:Cool.Cat@2013-03-29 ***********************************************/ #pragma once #include <SIX_DSTPL.h> #include <SIX_EntityMgr.h> #include <SIX_UIScene.h> #include <SIX_ListView.h> #include <SIX_NumberBatchNode.h> #include "SIX_CacheMgr.h" #include <SIX_CardSuit.h> #include <SIX_CardItem.h> USING_NS_CC; USING_NS_CC_EXT; class SIX_UIScene; class SIX_UIMgr:public SIX_EntityMgr { public: SIX_UIMgr(); ~SIX_UIMgr(); public: virtual int ParseXML(SIX_DSTPL<SIX_XmlDataSet> *pXmlDataSet); virtual int Run(); virtual int Release(); public: void SetParent(SIX_UIScene *pParnet) {m_Parent = pParnet;} SIX_UIScene *GetParent() {return m_Parent;} public: // CCNode bool ParseAttribute(CCNode *pControl,SIX_KV *pKV); // CCNode->CCSpriteBatchNode bool ParseAttribute(CCSpriteBatchNode *pControl,SIX_KV *pKV); // CCNode->CCScale9Sprite bool ParseAttribute(CCScale9Sprite *pControl,SIX_KV *pKV); // CCNode->CCProgressTimer bool ParseAttribute(CCProgressTimer *pControl,SIX_KV *pKV); // CCNode->CCSprite bool ParseAttribute(CCSprite *pControl,SIX_KV *pKV); // CCSprite->CCLabelTTF bool ParseAttribute(CCLabelTTF *pControl,SIX_KV *pKV); // CCNode->CCMenuItem bool ParseAttribute(CCMenuItem *pControl,SIX_KV *pKV); // CCMenuItem->CCMenuItemToggle bool ParseAttribute(CCMenuItemToggle *pControl,SIX_KV *pKV); // CCMenuItem->CCMenuItemSprite bool ParseAttribute(CCMenuItemSprite *pControl,SIX_KV *pKV); // CCMenuItemSprite->CCMenuItemImage bool ParseAttribute(CCMenuItemImage *pControl,SIX_KV *pKV); // CCMenuItem->CCMenuItemLabel bool ParseAttribute(CCMenuItemLabel *pControl,SIX_KV *pKV); // CCMenuItemLabel->CCMenuItemAtlasFont bool ParseAttribute(CCMenuItemAtlasFont *pControl,SIX_KV *pKV); // CCMenuItemLabel->CCMenuItemFont bool ParseAttribute(CCMenuItemFont *pControl,SIX_KV *pKV); // CCNode->CCLayer bool ParseAttribute(CCLayer *pControl,SIX_KV *pKV); // CCLayer->CCMenu bool ParseAttribute(CCMenu *pControl,SIX_KV *pKV); // CCLayer->CCLayerMultiplex bool ParseAttribute(CCLayerMultiplex *pControl,SIX_KV *pKV); // CCLayer->CCLayerColor bool ParseAttribute(CCLayerColor *pControl,SIX_KV *pKV); // CCLayerColor->CCLayerGradient bool ParseAttribute(CCLayerGradient *pControl,SIX_KV *pKV); // CCLayer->CCControl bool ParseAttribute(CCControl *pControl,SIX_KV *pKV); // CCControl->CCControlButton bool ParseAttribute(CCControlButton *pControl,SIX_KV *pKV); // CCControl->SIX_CardSuit bool ParseAttribute(SIX_CardSuit *pControl,SIX_KV *pKV); // CCControl->SIX_CardItem bool ParseAttribute(SIX_CardItem *pControl,SIX_KV *pKV); bool GetAttributeSplit(const char *src,const char *name,string &value); int GetAttributeAndPos(SIX_DSTPL<SIX_KV> *pDataElement,const char *attribute,SIX_KV *pResult); CCObject *ParseObject(SIX_XmlDataSet *pDataSet,const char *nodeName); CCNode *ParseControl(SIX_XmlDataSet *pDataSet,CCNode *pRoot); //CCAction *CreateAction(CCObject *pObject,SIX_DSTPL<SIX_KV> *pDataElement); //CCAnimate *CreateAnimate(CCObject *pObject,SIX_DSTPL<SIX_KV> *pDataElement); CCAnimation *CreateAnimation(CCObject *pObject,SIX_XmlDataSet *pDataSet); CCSpriteFrame *CreateSpriteFrame(CCObject *pObject,SIX_DSTPL<SIX_KV> *pDataElement); CCSprite *CreateSprite(CCNode *pControl,SIX_DSTPL<SIX_KV> *pDataElement); CCScale9Sprite *CreateScale9Sprite(CCNode *pControl,SIX_DSTPL<SIX_KV> *pDataElement); CCControlButton *CreateButton(CCNode *pControl,SIX_DSTPL<SIX_KV> *pDataElement); CCProgressTimer *CreateProgressTimer(CCNode *pControl,SIX_DSTPL<SIX_KV> *pDataElement); CCSpriteBatchNode *CreateSpriteBatchNode(CCNode *pControl,SIX_DSTPL<SIX_KV> *pDataElement); SIX_NumberBatchNode *CreateNumberBatchNode(CCNode *pControl,SIX_DSTPL<SIX_KV> *pDataElement); SIX_ListView *CreateListView(CCNode *pControl,SIX_DSTPL<SIX_KV> *pDataElement); SIX_ListViewCell *CreateListViewCell(CCNode *pControl,SIX_DSTPL<SIX_KV> *pDataElement); // 新增2种牌控件 // Cool.Cat SIX_CardSuit *CreateCardSuit(CCNode *pControl,SIX_DSTPL<SIX_KV> *pDataElement); SIX_CardItem *CreateCardItem(CCNode *pControl,SIX_DSTPL<SIX_KV> *pDataElement); // 传入控件内部属性节点描述,解析后返回一个DSTPL对象 SIX_DSTPL<SIX_KV> *SIX_UIMgr::ParseKV(const char *name,SIX_DSTPL<SIX_KV> *pDataElement); // 加载帧精灵缓存 void LoadFrameCache(SIX_DSTPL<SIX_KV> *pDataElement); // 移除帧精灵缓存 void UnloadFrameCache(); //unsigned int GetFrameCacheCount() {return m_FrameCache.size();} // 加载动作组 void LoadAnimationCache(SIX_XmlDataSet *pDataSet); // 查找动作 CCAnimation *GetAnimationFromCache(const char *animationName); // 移除动作组 void UnloadAnimationCache(); unsigned int GetAnimationCacheCount() {return m_AnimationCache.count();} void addControlEvents(unsigned int controlEvents,CCControl *pContrl,CCObject *pTarget=0); void doEvents(CCObject* pSender, CCControlEvent event); ////弹起(鼠标在控件区域内) //void onCCControlEventTouchUpInside(CCObject* pSender, CCControlEvent event); //void setAllDirty(bool bDirty); //bool getAllDirty(); public: SIX_UIScene *m_Parent; // 动作组缓存容器 CCDictionary m_AnimationCache; //map<const char*,CCAnimation*> m_AnimationCache; bool m_bDirty; };
[ "hanshouqing85@163.com" ]
hanshouqing85@163.com
31527a77b2cf57ccf8f9ced8a29df9578f132d3e
db8c174c21d0c0b238d1b33f1976c7819f7c0fc2
/OpenVideoCall/AGEngineEventHandler.h
57fe4d5e01d9f30079610f365f155910dea3a44a
[ "MIT" ]
permissive
alekseyIsakin/OpenVideoCall
9d52d28a688a02e82b16753b764d4a86876caac3
3030bcb40490da161393adcaad4f000db333bf55
refs/heads/master
2023-04-30T16:56:47.789925
2021-05-17T05:13:07
2021-05-17T05:13:07
364,576,702
0
0
MIT
2021-05-17T05:13:07
2021-05-05T12:56:57
C++
UTF-8
C++
false
false
2,431
h
#pragma once using namespace agora::rtc; class CAGEngineEventHandler : public IRtcEngineEventHandler { public: //CAGEngineEventHandler(void) ; //~CAGEngineEventHandler(void) ; void SetMsgReceiver(HWND hWnd = NULL) ; HWND GetMsgReceiver() {return m_hMainWnd;}; virtual void onJoinChannelSuccess(const char* channel, uid_t uid, int elapsed) override; virtual void onRejoinChannelSuccess(const char* channel, uid_t uid, int elapsed) override; virtual void onWarning(int warn, const char* msg) override; virtual void onError(int err, const char* msg) override; virtual void onAudioQuality(uid_t uid, int quality, unsigned short delay, unsigned short lost) override; virtual void onAudioVolumeIndication(const AudioVolumeInfo* speakers, unsigned int speakerNumber, int totalVolume) override; virtual void onLeaveChannel(const RtcStats& stat) override; virtual void onRtcStats(const RtcStats& stat) override; virtual void onAudioDeviceStateChanged(const char* deviceId, int deviceType, int deviceState) override; virtual void onVideoDeviceStateChanged(const char* deviceId, int deviceType, int deviceState) override; virtual void onLastmileQuality(int quality) override; virtual void onFirstLocalVideoFrame(int width, int height, int elapsed) override; virtual void onFirstRemoteVideoDecoded(uid_t uid, int width, int height, int elapsed) override; virtual void onFirstRemoteVideoFrame(uid_t uid, int width, int height, int elapsed) override; virtual void onUserJoined(uid_t uid, int elapsed) override; virtual void onUserOffline(uid_t uid, USER_OFFLINE_REASON_TYPE reason) override; virtual void onUserMuteAudio(uid_t uid, bool muted) override; virtual void onUserMuteVideo(uid_t uid, bool muted) override; virtual void onApiCallExecuted(int err, const char* api, const char* result) override; virtual void onStreamMessage(uid_t uid, int streamId, const char* data, size_t length) override; virtual void onLocalVideoStats(const LocalVideoStats& stats) override; virtual void onRemoteVideoStats(const RemoteVideoStats& stats) override; virtual void onCameraReady() override; virtual void onVideoStopped() override; virtual void onConnectionLost() override; virtual void onConnectionInterrupted() override; virtual void onUserEnableVideo(uid_t uid, bool enabled) override; virtual void onLocalUserRegistered(uid_t uid, const char* userAccount) override; private: HWND m_hMainWnd; };
[ "karahunforever@gmail.com" ]
karahunforever@gmail.com
86f0482a110e7202374d58891a4987a38173557b
58c90c3b496939235da3151811a4d434489c461d
/c++/ClassesAndObjects/main.cpp
b44ff00464db17a3f8801114dc2feb37c365221f
[]
no_license
HalilGumus/Hackerrank
e02128ef14874d6d49c3f37765976b4cd0d3c4f1
4c47eda99cf121e685f24269f61262290c8fbdf7
refs/heads/main
2023-03-30T06:32:55.444912
2021-03-24T20:11:56
2021-03-24T20:11:56
349,854,428
0
0
null
null
null
null
UTF-8
C++
false
false
1,061
cpp
#include <iostream> using namespace std; class Student{ private: int scores[5]; public: void input(){ int n1, n2, n3, n4, n5; cin >> n1 >> n2 >> n3 >> n4 >> n5; scores[0] = n1; scores[1] = n2; scores[2] = n3; scores[3] = n4; scores[4] = n5; } int calculateTotalScore(){ int total = 0; for(int i = 0; i < 5; i++){ total = total + scores[i]; } return total; } }; int main(){ int n; // number of students cin >> n; Student *s = new Student[n]; // an array of n students for(int i = 0; i < n; i++){ s[i].input(); } // calculate kristen's score int kristen_score = s[0].calculateTotalScore(); // determine how many students scored higher than kristen int count = 0; for(int i = 1; i < n; i++){ int total = s[i].calculateTotalScore(); if(total > kristen_score){ count++; } } // print result cout << count; return 0; }
[ "halilgumus08@gmail.com" ]
halilgumus08@gmail.com
2e71c4fa6f6a3c119d3241e80084b1f77fb03523
27c9857a74d02c3c4430a5b9f6702dbac6171ea6
/my_cpp_ver/cp06/remote_control/stereo_command.h
b6592937ce4fd128eeb0f18ff5027ec3da7f0115
[]
no_license
XINZHANGXZZ/head_first
c3783ee69041d80e1cbf803dd48038773c67ddf1
4edc2d71600c6dffa61e27af7aee550edc9466f0
refs/heads/master
2021-04-15T18:59:49.793952
2017-02-26T04:26:33
2017-02-26T04:26:33
126,889,885
1
0
null
null
null
null
UTF-8
C++
false
false
723
h
#ifndef _STEREO_COMMAND_H_ #define _STEREO_COMMAND_H_ #include "command.h" namespace control{ class stereo_on_command : public command { public: stereo_on_command(stereo *ste){ this->ste = ste; } ~stereo_on_command(); void excute(){ ste->on(); ste->setmode("dvd"); ste->setvol(12); } void undo(){ ste->off(); } private: stereo *ste; }; class stereo_off_command :public command { public: stereo_off_command(stereo *ste){ this->ste = ste; } ~stereo_off_command(); void excute(){ ste->off(); } void undo(){ ste->on(); ste->setmode(ste->getmode()); ste->setvol(ste->getvol()); } private: stereo *ste; }; } #endif
[ "qizheng1993hit@gmail.com" ]
qizheng1993hit@gmail.com
15556fd41b2e3ff4927d20d67844847117f768b6
97bcc00c0be6158ed8fd1ca771919d2fcc947f75
/qt_nuklear_extended/SystemAbstraction/data_headers/icon/img.png.hpp
5cfab43138b90221e721b7b057e9b362333a440c
[]
no_license
rafal-tarnow/nuklear_qt_gles2
7cc7ec4291e2e7ea43187ac8abf6f7182a7f4f36
5d0c11caa32a0a54bc81d9f79dfdffe2bb657c5e
refs/heads/master
2021-04-27T06:21:18.552452
2018-03-07T10:55:07
2018-03-07T10:55:07
122,612,552
0
1
null
null
null
null
UTF-8
C++
false
false
3,991
hpp
#pragma once const static int size_of_img = 648; unsigned char img[size_of_img] = { 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x14, 0x08, 0x06, 0x00, 0x00, 0x00, 0x8d, 0x89, 0x1d, 0x0d, 0x00, 0x00, 0x00, 0x06, 0x62, 0x4b, 0x47, 0x44, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0xa0, 0xbd, 0xa7, 0x93, 0x00, 0x00, 0x00, 0x09, 0x70, 0x48, 0x59, 0x73, 0x00, 0x00, 0x0d, 0xd7, 0x00, 0x00, 0x0d, 0xd7, 0x01, 0x42, 0x28, 0x9b, 0x78, 0x00, 0x00, 0x00, 0x07, 0x74, 0x49, 0x4d, 0x45, 0x07, 0xdf, 0x0a, 0x14, 0x0e, 0x21, 0x22, 0xe9, 0x16, 0xa5, 0x3e, 0x00, 0x00, 0x02, 0x15, 0x49, 0x44, 0x41, 0x54, 0x38, 0xcb, 0xcd, 0x94, 0xcf, 0x6b, 0x13, 0x41, 0x14, 0xc7, 0x3f, 0xb3, 0x3b, 0xbb, 0x9b, 0x1f, 0xae, 0x4d, 0xd7, 0x6c, 0xd2, 0x06, 0x25, 0x34, 0x34, 0x3d, 0x18, 0xa9, 0x0a, 0x31, 0xa6, 0x89, 0x46, 0x28, 0x3d, 0xa8, 0x54, 0x10, 0x4f, 0xf9, 0x03, 0x84, 0x9e, 0xf4, 0xa4, 0x5e, 0xc4, 0xff, 0xa3, 0xa7, 0xe4, 0xea, 0x49, 0xc9, 0xa1, 0x37, 0xcd, 0x45, 0x3c, 0x78, 0x10, 0x3c, 0x14, 0xa4, 0x12, 0x0c, 0x11, 0x8c, 0x82, 0x45, 0xa5, 0x74, 0x5b, 0xb4, 0x69, 0xc7, 0x43, 0x6a, 0x6d, 0x93, 0x25, 0x89, 0x9e, 0xfc, 0xc2, 0xf0, 0x98, 0xe1, 0xf1, 0x9d, 0xef, 0xcc, 0x7b, 0xef, 0x2b, 0xe8, 0x87, 0xec, 0x89, 0x9d, 0x9e, 0x38, 0x10, 0xd2, 0x67, 0x2f, 0x81, 0x63, 0x80, 0x05, 0xe8, 0xc0, 0x16, 0xb0, 0x39, 0x2a, 0xa9, 0xf0, 0x21, 0x3b, 0x61, 0x59, 0x56, 0xcb, 0x71, 0x1c, 0xdd, 0x34, 0x4d, 0x3c, 0xcf, 0x43, 0x88, 0x3f, 0x69, 0x42, 0x08, 0x94, 0x52, 0x07, 0x7b, 0xa5, 0x14, 0xeb, 0xeb, 0xeb, 0xc2, 0x4f, 0xa1, 0x04, 0x22, 0x9a, 0xa6, 0xb5, 0xd2, 0xe9, 0xb4, 0x9e, 0xcd, 0x66, 0xa9, 0x56, 0xab, 0xd4, 0x6a, 0x35, 0x5c, 0xd7, 0x25, 0x1a, 0x8d, 0x62, 0x9a, 0x66, 0x9f, 0xa2, 0x62, 0xb1, 0xe8, 0xab, 0x50, 0x02, 0x11, 0xe0, 0x53, 0x26, 0x93, 0x91, 0xe9, 0x64, 0x92, 0xa7, 0x2b, 0x2b, 0x00, 0x9c, 0x99, 0x9a, 0xe2, 0x7a, 0x3e, 0x8f, 0x1d, 0x0e, 0x11, 0x0e, 0x59, 0xfb, 0xaa, 0xc0, 0xd2, 0x0d, 0xae, 0xdd, 0xb9, 0x4b, 0xa9, 0x54, 0xa2, 0xdd, 0x6e, 0x0b, 0xbf, 0x02, 0x58, 0x93, 0x93, 0x93, 0x32, 0x97, 0xcb, 0x51, 0xa9, 0x54, 0x0e, 0x6e, 0x3c, 0x3b, 0x3d, 0xcd, 0xe2, 0xa5, 0x3c, 0x71, 0x77, 0x0c, 0xd7, 0x39, 0xde, 0x25, 0xdc, 0x13, 0xbc, 0x79, 0xfb, 0x7e, 0x78, 0x51, 0x2c, 0xcb, 0x3a, 0x42, 0x06, 0x30, 0xe1, 0x38, 0x48, 0x43, 0x43, 0x37, 0x04, 0xce, 0xc2, 0x2d, 0x00, 0xbe, 0x3e, 0x7f, 0x02, 0xda, 0xe0, 0x2a, 0x77, 0x80, 0x1f, 0x9e, 0xe7, 0x51, 0xaf, 0xd7, 0xb9, 0xb7, 0xb4, 0xc4, 0xf9, 0x99, 0x19, 0xdc, 0xb1, 0x31, 0x92, 0x13, 0x31, 0x42, 0x01, 0x0b, 0xd3, 0x30, 0x0e, 0x7d, 0x94, 0x1a, 0xa9, 0x6d, 0x36, 0x85, 0x10, 0xb8, 0xae, 0xcb, 0x62, 0xa1, 0xc0, 0x8d, 0x42, 0x01, 0x01, 0x18, 0x52, 0x62, 0x07, 0x02, 0x84, 0xcd, 0x60, 0x57, 0x19, 0xa0, 0x76, 0x35, 0x50, 0xc3, 0x15, 0x22, 0x84, 0xc0, 0xb6, 0x6d, 0xec, 0x50, 0x88, 0xf8, 0xf8, 0x38, 0x4a, 0x29, 0xa4, 0xae, 0x63, 0x18, 0x92, 0xbd, 0x1d, 0x10, 0xbb, 0x62, 0xff, 0x0f, 0x61, 0x6f, 0x77, 0xb8, 0xc2, 0x83, 0xa6, 0x7d, 0xb0, 0xbc, 0xcc, 0xeb, 0xb5, 0x35, 0x00, 0x4e, 0xc5, 0x62, 0xdc, 0x2f, 0x97, 0x51, 0x3b, 0xf0, 0x72, 0x75, 0x95, 0xc7, 0xf5, 0x3a, 0xe5, 0xf9, 0x79, 0xc2, 0xc1, 0xe0, 0xf0, 0xb1, 0x89, 0xc7, 0xe3, 0xaa, 0xd9, 0x6c, 0x2a, 0xba, 0x0f, 0x1a, 0xba, 0x1a, 0x8d, 0x86, 0x4a, 0x24, 0x12, 0x6a, 0xd0, 0xe8, 0x01, 0x70, 0xf5, 0xca, 0x4d, 0xce, 0x9d, 0xbe, 0xd0, 0x77, 0x7e, 0x79, 0xe1, 0x22, 0x00, 0x2f, 0x9e, 0xbd, 0xe2, 0xf3, 0x97, 0x8f, 0xc3, 0xdb, 0x46, 0xd3, 0xba, 0xbd, 0x10, 0x3d, 0x99, 0x22, 0x35, 0x3b, 0xd7, 0x97, 0x1c, 0x8c, 0xc4, 0x01, 0x48, 0xcd, 0xce, 0xa1, 0x7f, 0x78, 0x37, 0x92, 0x39, 0x1c, 0x99, 0xd3, 0x5e, 0x6c, 0x6f, 0xfd, 0xfc, 0x6b, 0xb7, 0x01, 0xc0, 0x90, 0x26, 0x2d, 0x1f, 0x05, 0xdf, 0xbe, 0x77, 0x0b, 0xb1, 0xb1, 0xb1, 0x3d, 0x1a, 0xe1, 0x6f, 0x57, 0x79, 0xf8, 0xe8, 0x36, 0xff, 0x8a, 0xc3, 0xf6, 0x85, 0xe3, 0x38, 0xca, 0xcf, 0x51, 0x06, 0xa1, 0xd3, 0xe9, 0x1c, 0xb1, 0xaf, 0xff, 0x1f, 0xbf, 0x00, 0xc8, 0x41, 0x93, 0xf5, 0x23, 0x79, 0x6a, 0x35, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82, };
[ "rafal-tarnow@wp.pl" ]
rafal-tarnow@wp.pl
849bf3491e0193628282bdf133b4fd06093863ad
340ff6a19dc059fd19cb7311365a719473e813f0
/examples/Simple_Detection/cpp/Vision.cpp
817b0c11d2655817b72fca433f5b7b18526df3b2
[ "MIT" ]
permissive
wml-frc/CJ-Vision
0c6b51809871f6b42f271262dee2ad9d35c25227
ba336d56fd92a34e0d0b533553e796bc1d94012d
refs/heads/master
2022-03-18T10:42:20.360059
2022-03-01T04:05:01
2022-03-01T04:05:01
228,177,343
4
8
MIT
2022-03-01T04:05:03
2019-12-15T12:03:22
C++
UTF-8
C++
false
false
3,639
cpp
#include "Vision.h" // required before other #includes #include "UDP_TransferNT.h" using namespace UDP_TransferNT; /** * Container for images passed between layers */ struct Images { CJ::Image origin; CJ::Image filtered; CJ::Image processed; }; /** * Camera Capture Layer */ class CaptureLayer : public CJ::Layer { public: CaptureLayer(CJ::Application &app, CJ::Image &origin) : Layer("Capture Layer"), _app(app), _origin(origin) { CJ_PRINT_INFO("Capture Layer Created"); } void onAttach() override { CJ_PRINT_INFO("Capture Layer Attached"); _camera.config.port = 0; _camera.config.fps = 60; _camera.config.autoExposure = true; _camera.config.name = "Cam"; _origin.name = "Origin Image"; if (_camera.init() != 0) { CJ_PRINT_ERROR("Could not init camera"); _app.setRunning(false); } } void onDetach() override { CJ_PRINT_WARN("Capture Layer Detached"); } void onUpdate() override { _camera.capture(_origin); } private: CJ::Application &_app; CJ::Camera _camera; // main camera CJ::Image &_origin; // reference to origin passed into layer }; class ProcessingLayer : public CJ::Layer { public: ProcessingLayer(CJ::Application &app, Images &images) : Layer("Processing Layer"), _app(app), _images(images) { CJ_PRINT_INFO("Processing Layer Created"); } void onAttach() override { CJ_PRINT_INFO("Processing Layer Attached"); _images.filtered.name = "Filtered Images"; _hsv_options = { // green track for low exposure logitech 1080p webcam 30, // H 83, 113, // S 214, 104, // V 168, 0, // Erosion 15 // Dilation }; _images.filtered.name = "Filtered"; _images.processed.name = "Processed Image"; // Create filter trackbar to edit hsv_options CJ::ColourFilter::createFilterTrackbar(_hsv_options); } void onDetach() override { CJ_PRINT_INFO("Processing Layer Detached"); } void onUpdate() override { // Filter image CJ::ColourFilter::filter(_images.origin, _images.filtered, _hsv_options); // Detect Contours CJ::Contours::detectContours(_images.filtered, _images.processed); // Draw Convex Around contours CJ::Bound::drawConvexHull(_images.processed, _images.processed); // Draw Bounding Box CJ::Bound::drawBoundingBox(_images.processed, _images.processed); } private: CJ::Application &_app; Images &_images; // HSV Options CJ::ColourFilter::HSV_Options _hsv_options; }; /** * Output Layer * Has no real purpose unless specific output methods are needed * I.e MJPEG Streaming */ class OutputLayer : public CJ::Layer { public: OutputLayer(CJ::Application &app, Images &images) : Layer("Output Layer"), _app(app), _images(images) { CJ_PRINT_INFO("Output Layer Created"); } void onAttach() override { CJ_PRINT_INFO("Output Layer Attached"); } void onDetach() override { CJ_PRINT_INFO("Output Layer Detached"); } void onUpdate() override { if (CJ::Output::display(30, _images.origin, _images.filtered, _images.processed) == 27) { CJ_PRINT_WARN("Esc Called"); _app.setRunning(false); } } private: CJ::Application &_app; Images &_images; }; /** * Simple Detection Vision application */ class SimpleDetection : public CJ::Application { public: SimpleDetection() : CJ::Application("Simple Detection") { CJ_PRINT_INFO("App created"); pushLayer(new CaptureLayer(get(), _images.origin)); pushLayer(new ProcessingLayer(get(), _images)); pushOverlay(new OutputLayer(get(), _images)); } ~SimpleDetection() { CJ_PRINT_WARN("App Destroyed"); } private: /** * Images shared between layers */ Images _images; }; CJ_CREATE_APPLICATION(SimpleDetection)
[ "connorbuchel@gmail.com" ]
connorbuchel@gmail.com
92fdae95535c0dabafefef364f2056a4f7503310
e36906be9399685b0d03daffec9c33735eda8ba1
/src/seem/yocto/seem/compiler.cpp
771c59c84e417f37ffd54f46231665e18db599d2
[]
no_license
ybouret/yocto4
20deaa21c1ed4f52d5d6a7991450d90103a7fe8e
c02aa079d21cf9828f188153e5d65c1f0d62021c
refs/heads/master
2020-04-06T03:34:11.834637
2016-09-09T14:41:55
2016-09-09T14:41:55
33,724,799
1
0
null
null
null
null
UTF-8
C++
false
false
1,111
cpp
#include "yocto/seem/compiler.hpp" #include "yocto/ios/imstream.hpp" namespace yocto { namespace Seem { Compiler:: ~Compiler() throw() { } namespace { static const char grammar_data[] = { #include "seem.inc" }; } Compiler:: Compiler(const bool emitFiles) : impl( lingua::parser::generate(grammar_data,sizeof(grammar_data),emitFiles) ), gram( & *impl ) { } vCode Compiler:: compile(ios::istream &fp) { impl->restart(); const vCode ans( impl->parse(fp) ); return ans; } vCode Compiler::compile(const string &s) { ios::imstream fp(s); return compile(fp); } vCode Compiler::compile(const char *s) { ios::imstream fp(s,length_of(s)); return compile(fp); } vCode Compiler:: load( ios::istream &fp ) const { const vCode ans( vNode::load(fp,*gram) ); return ans; } } }
[ "yann.bouret@gmail.com" ]
yann.bouret@gmail.com
ae26797dc8803819e0890b16086562448ac2c5ed
07c3e4c4f82056e76285c81f14ea0fbb263ed906
/Re-Abyss/app/scenes/Scene/Home/Scene.cpp
b80d4bdf3bf8c6dc81fb5df6c8e6e3a384e46438
[]
no_license
tyanmahou/Re-Abyss
f030841ca395c6b7ca6f9debe4d0de8a8c0036b5
bd36687ddabad0627941dbe9b299b3c715114240
refs/heads/master
2023-08-02T22:23:43.867123
2023-08-02T14:20:26
2023-08-02T14:20:26
199,132,051
9
1
null
2021-11-22T20:46:39
2019-07-27T07:28:34
C++
UTF-8
C++
false
false
2,324
cpp
#include <abyss/scenes/Scene/Home/Scene.hpp> #include <abyss/commons/Factory/System/Injector.hpp> #include <abyss/commons/Resource/Preload/Preloader.hpp> #include <abyss/commons/Resource/Preload/Param.hpp> #include <abyss/scenes/Sys/System.hpp> #include <abyss/scenes/Scene/Home/Booter.hpp> #include <Siv3D.hpp> namespace abyss::Scene::Home { class Scene::Impl final : public Cycle::Home::IMasterObserver { public: Impl(const InitData& init) : m_data(init._s) {} void loading() { Resource::Assets::Main()->release(); Resource::Preload::Preloader preloader(U"Scene/Home"); preloader.preload(); this->init(); } void init() { m_system = Factory::System::Home(m_data.get()) .instantiate<Sys::System>(); m_system->boot<Booter>(this); } void update() { m_system->update(); } void draw() { m_system->draw(); } public: bool onStageStart(const StageDef& stage) override { return onSceneEnd({ .stage = stage }); } bool onBack() { return onSceneEnd({ .isBack = true }); } bool onSceneEnd(const SceneResult& result) { m_data->isRequestedSceneEnd = true; m_data->result = result; return true; } private: std::shared_ptr<Sys::System> m_system; std::shared_ptr<Data_t> m_data; }; Scene::Scene(const InitData& init) : ISceneBase(init), m_pImpl(std::make_unique<Impl>(init)) { // ローディング m_pImpl->loading(); #if ABYSS_DEBUG m_reloader .setMessage(U"Home") .setCallback([this, init](const Debug::FileChanges& changes) { Debug::HotReloadUtil::ReloadAssetCommon(changes); m_pImpl = std::make_unique<Impl>(init); m_pImpl->loading(); }); #endif } Scene::~Scene() {} void Scene::onSceneUpdate() { m_pImpl->update(); } void Scene::onSceneDraw() const { m_pImpl->draw(); } }
[ "tyanmahou@gmail.com" ]
tyanmahou@gmail.com
f199a92ebd77dfaea7cd7305679fbf48cc2989b3
2fa4f16865266a4422de32b09a7a928fc5a3ccb3
/2019/Øving-07/Emojis.cpp
eadba9795e0d2e5d8f237b2221e414523f981469
[]
no_license
chrstrom/TDT4102
06ed075a415f0d1b531749ad3f1c725cee350614
a43fc42dccb6991e694391f29196519e0f5f8cd3
refs/heads/master
2022-11-21T01:34:10.471288
2020-07-24T18:42:38
2020-07-24T18:42:38
null
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
4,387
cpp
#include "Emojis.h" EmptyFace::EmptyFace(Point center, const int radius) : Face{ center, radius }, eyeRadius{radius/5}, leftEyeCenter{ center.x - radius/3, center.y - radius/5 }, rightEyeCenter{ center.x + radius/3, center.y - radius/5 } { leftEye.set_fill_color(Color::black); leftEye.set_color(Color::black); rightEye.set_fill_color(Color::black); rightEye.set_color(Color::black); } void EmptyFace::attachTo(Graph_lib::Window& win) { Face::attachTo(win); win.attach(rightEye); win.attach(leftEye); } //A SmilingFace::SmilingFace(Point center, const int radius) : EmptyFace{ center, radius }, startDeg{ 180 }, endDeg{ 360 }, mouthWidth{ radius }, mouthHeight{ 3*radius / 4 }, mouthStart{ center.x, center.y+ radius/5} { mouth.set_color(Color::black); Line_style style{ Line_style::solid, radius/15 }; mouth.set_style(style); } void SmilingFace::attachTo(Graph_lib::Window& win) { EmptyFace::attachTo(win); win.attach(mouth); } //B SadFace::SadFace(Point center, int radius) : EmptyFace{ center, radius }, startDeg{ 0 }, endDeg{ 180 }, mouthWidth{radius}, mouthHeight{3*radius/4}, mouthStart{center.x, center.y+radius/2} { mouth.set_color(Color::black); Line_style style{ Line_style::solid, radius/15 }; mouth.set_style(style); } void SadFace::attachTo(Graph_lib::Window& win) { EmptyFace::attachTo(win); win.attach(mouth); } //C AngryFace::AngryFace(Point center, const int radius) : SadFace{ center, radius }, maxY{center.y - 2*radius/3}, minY{center.y - radius/3}, topLeftX{center.x - 2*radius/3 }, botLeftX{center.x - radius/7}, topRightX{center.x + 2*radius/3 }, botRightX{center.x + radius/7} { Line_style eyebrowStyle{ Line_style::solid, radius/15 }; rightEyebrow.set_color(Color::black); rightEyebrow.set_style(eyebrowStyle); leftEyebrow.set_color(Color::black); leftEyebrow.set_style(eyebrowStyle); } void AngryFace::attachTo(Graph_lib::Window& win) { SadFace::attachTo(win); win.attach(leftEyebrow); win.attach(rightEyebrow); } //D WinkingFace::WinkingFace(Point center,const int radius) : EmptyFace{center, radius}, eyeRadius{radius/5}, winkingEyeCenter{ center.x + radius / 3, center.y - radius / 8 }, mouthWidth{ radius }, mouthHeight{ 3 * radius / 4 }, mouthStart{ center.x, center.y + radius / 5 } { mouth.set_color(Color::black); Line_style style{ Line_style::solid, radius / 15 }; mouth.set_style(style); winkingEye.set_fill_color(Color::black); winkingEye.set_color(Color::black); winkingEye.set_style(style); } void WinkingFace::attachTo(Graph_lib::Window& win) { EmptyFace::attachTo(win); win.detach(EmptyFace::rightEye); win.attach(winkingEye); win.attach(mouth); } //E SurprisedFace::SurprisedFace(Point center, const int radius) : EmptyFace{ center, radius }, mouthCenter{ center.x, center.y + radius/2}, mouthWidth{radius/2}, mouthHeight{radius/3} { mouth.set_color(Color::black); mouth.set_fill_color(Color::black); } void SurprisedFace::attachTo(Graph_lib::Window& win) { EmptyFace::attachTo(win); win.attach(mouth); } void drawEmojis(Graph_lib::Window& win) { constexpr int xStep{ 180 }; constexpr int y{ 300 }; constexpr int radius{ 60 }; int i{ 1 }; static SmilingFace smilingFace{ { xStep*i, y }, radius }; i++; smilingFace.attachTo(win); static SadFace sadFace{ { xStep*i, y }, radius }; i++; sadFace.attachTo(win); static AngryFace angryFace{ { xStep*i, y }, radius }; i++; angryFace.attachTo(win); static WinkingFace winkingFace{ { xStep*i, y }, radius }; i++; winkingFace.attachTo(win); static SurprisedFace surprisedFace{ { xStep*i, y }, radius }; surprisedFace.attachTo(win); //Read Access violation error ved å legge inn emojis inn i Vector_ref. Brute-forcer isteden. } Vector_ref<Emoji> initVector() { Vector_ref<Emoji> vec; constexpr int xStep{ 180 }; constexpr int y{ 300 }; constexpr int radius{ 60 }; int i{ 1 }; static SmilingFace smilingFace{ { xStep*i, y }, radius }; i++; static SadFace sadFace{ { xStep*i, y }, radius }; i++; static AngryFace angryFace{ { xStep*i, y }, radius }; i++; static WinkingFace winkingFace{ { xStep*i, y }, radius }; i++; static SurprisedFace surprisedFace{ { xStep*i, y }, radius }; vec.push_back(smilingFace); vec.push_back(sadFace); vec.push_back(angryFace); vec.push_back(winkingFace); vec.push_back(surprisedFace); return vec; }
[ "chstr@stud.ntnu.no" ]
chstr@stud.ntnu.no
6d6c062b02f2e2fcff573eb6a4c75de7aa7d213e
408271e09e88805b01f191c8ac27ba0b5e07f68a
/src/TSprayCan.h
dd273866af1d28bb7fc44a3c095b98eff7ab6f63
[]
no_license
KanikaPuri/PhotoShop-Application-in-C-
d3234894d2fda8a4a11f68e38e32543a44fa2362
b622d4c5a4f7b7abb8b2593d0010c140ce634ded
refs/heads/master
2021-01-18T01:58:35.389164
2015-04-08T17:37:00
2015-04-08T17:37:00
33,621,585
0
1
null
null
null
null
UTF-8
C++
false
false
358
h
// // TSprayCan.h // Student Support // // Created by Seth Johnson on 2/6/15. // Copyright (c) 2015 Seth Johnson. All rights reserved. // // For educational purposes only. Please do not post online. #ifndef TSPRAYCAN_H #define TSPRAYCAN_H #include "Tool.h" class TSprayCan : public Tool { public: TSprayCan(); std::string getName(); }; #endif
[ "purix021@umn.edu" ]
purix021@umn.edu
1a9dd5c73c1ce57510927d11ef262b0c3a5760ae
3c471f5a9ac015c24c8166f9158804f11e8b4915
/mediatek/platform/mt6589/hardware/camera/core/featureio/pipe/fdft_hal/fd_hal_base.cpp
8c55107f6c738d00139d93bb663bf005ce9a2f96
[]
no_license
chrmhoffmann/android_kernel_fp_FP1
50580f946d4c63285c4837502ab0b6ed81ad4176
db3064c34e6e70e337bf98c278decc59b19b9104
refs/heads/master
2021-01-21T02:56:12.792406
2014-08-26T15:03:01
2014-08-26T15:10:58
23,490,109
5
3
null
null
null
null
UTF-8
C++
false
false
1,251
cpp
#define LOG_TAG "fd_hal_base" #include <stdlib.h> #include <stdio.h> #include <cutils/log.h> #include "fd_hal_base.h" //#include "fd_hal.h" #include "fdvt_hal.h" /******************************************************************************* * ********************************************************************************/ halFDBase* halFDBase::createInstance(HalFDObject_e eobject) { if (eobject == HAL_FD_OBJ_SW) { return halFDVT::getInstance(); } else if (eobject == HAL_FD_OBJ_HW) { return halFDVT::getInstance(); } else if (eobject == HAL_FD_OBJ_FDFT_SW) { return halFDVT::getInstance(); } else { return halFDTmp::getInstance(); } return NULL; } /******************************************************************************* * ********************************************************************************/ halFDBase* halFDTmp:: getInstance() { //LOGD("[halFDTmp] getInstance \n"); static halFDTmp singleton; return &singleton; } /******************************************************************************* * ********************************************************************************/ void halFDTmp:: destroyInstance() { }
[ "kees.jongenburger@gmail.com" ]
kees.jongenburger@gmail.com
de5f1c003bcb661d1fc3df7eff34c29e7be9270e
c0caed81b5b3e1498cbca4c1627513c456908e38
/src/protocols/loops/LoopsFileFallbackConfiguration.cc
daa632342d8bfa656035f0e6ed7e69d38b7414ad
[]
no_license
malaifa/source
5b34ac0a4e7777265b291fc824da8837ecc3ee84
fc0af245885de0fb82e0a1144422796a6674aeae
refs/heads/master
2021-01-19T22:10:22.942155
2017-04-19T14:13:07
2017-04-19T14:13:07
88,761,668
0
2
null
null
null
null
UTF-8
C++
false
false
5,100
cc
// -*- mode:c++;tab-width:2;indent-tabs-mode:t;show-trailing-whitespace:t;rm-trailing-spaces:t -*- // vi: set ts=2 noet: // // (c) Copyright Rosetta Commons Member Institutions. // (c) This file is part of the Rosetta software suite and is made available under license. // (c) The Rosetta software is developed by the contributing members of the Rosetta Commons. // (c) For more information, see http://www.rosettacommons.org. Questions about this can be // (c) addressed to University of Washington UW TechTransfer, email: license@u.washington.edu. /// @file protocols/loops/LoopsFileFallbackConfiguration.cc /// @author Brian D. Weitzner brian.weitzner@gmail.com // Unit Headers #include <protocols/loops/LoopsFileFallbackConfiguration.hh> #include <protocols/loops/LoopsFileFallbackConfigurationCreator.hh> // Platform Headers #include <core/types.hh> #include <utility/vector1.hh> // basic headers #include <basic/resource_manager/ResourceOptions.hh> #include <basic/options/option.hh> #include <basic/options/keys/loops.OptionKeys.gen.hh> // numeric headers #include <numeric/random/random.hh> //utility headers #include <utility/excn/Exceptions.hh> #include <utility/file/FileName.hh> #include <utility/file/PathName.hh> //C++ Headers #include <string> #include <map> namespace protocols { namespace loops { using basic::resource_manager::LoaderType; using basic::resource_manager::LocatorID; using basic::resource_manager::LocatorTag; using basic::resource_manager::ResourceDescription; using basic::resource_manager::ResourceTag; using basic::resource_manager::ResourceOptionsTag; LoopsFileFallbackConfiguration::LoopsFileFallbackConfiguration() {} /// @details Return true if the user has set the "-loops:loop_file" flag and false otherwise. bool LoopsFileFallbackConfiguration::fallback_specified( ResourceDescription const & ) const { return basic::options::option[ basic::options::OptionKeys::loops::loop_file ].user(); } /// @details The return value is "loops_file" to indicate that a LoopsFileLoader is required. basic::resource_manager::LoaderType LoopsFileFallbackConfiguration::get_resource_loader( ResourceDescription const & ) const { return "LoopsFile"; } /// @details The %locator_id for the fallback configuration is set by the options system. The /// get_loops_filename_from_options() helper method is used to handle complex cases. basic::resource_manager::LocatorID LoopsFileFallbackConfiguration::get_locator_id( ResourceDescription const & ) const { return get_loops_filename_from_options(); } /// @details Return a NULL pointer to trigger the creation of a default LoopsFileOptions later in the %resource creation /// process. basic::resource_manager::ResourceOptionsOP LoopsFileFallbackConfiguration::get_resource_options( ResourceDescription const & ) const { // use the default loops file options. return NULL; } /// @details Return a string that provides a helpful message to the user so s/he can determine how to correctly use the /// loops_file resource. std::string LoopsFileFallbackConfiguration::could_not_create_resource_error_message( ResourceDescription const & ) const { return "The LoopsFileFallbackConfiguration requires that the flag '-loops:loop_file' be set on the command line."; } /// @details There are three options system scenarios this method can handle. Each scenario and the corresponding ///behavior is outlined below: /// @li A single filename is specified - return the filename as a string /// @li Several filenames are specified - return one of the filenames, chosen at random, as a string /// @li No filename is specified - throw an exception requesting that the user double check his/her flags. /// @throws EXCN_Msg_Exception basic::resource_manager::LocatorID LoopsFileFallbackConfiguration::get_loops_filename_from_options() const { // the next line uses value_or to avoid a call to std::exit in the options class. I can test things that throw exceptions. Just sayin'. utility::vector1< std::string > loops_files = basic::options::option[ basic::options::OptionKeys::loops::loop_file ].value_or( utility::vector1< std::string >() ); if ( ! loops_files.size() ) { throw utility::excn::EXCN_Msg_Exception("The fallback LoopsFile resource option has no loops files associated with it! Was the option omitted from the command line?"); } core::Size const which_loops_file( loops_files.size() == 1 ? 1 : core::Size( numeric::random::rg().random_range(1,( loops_files.size() )))); return loops_files[ which_loops_file ]; } /// @details Return an owning pointer to a newly constructed default instance of FallbackConfiguration. basic::resource_manager::FallbackConfigurationOP LoopsFileFallbackConfigurationCreator::create_fallback_configuration() const { return basic::resource_manager::FallbackConfigurationOP( new LoopsFileFallbackConfiguration ); } /// @details Return a string specifying the type of %FallbackConfiguration to create (loops_file). std::string LoopsFileFallbackConfigurationCreator::resource_description() const { return "LoopsFile"; } } // namespace loops } // namespace protocols
[ "malaifa@yahoo.com" ]
malaifa@yahoo.com
aab55650faeed52a16bdf00e674a030bcec6aea9
dbe8b5b38eaba3db558f8ddece39f8b5017685df
/3rd/asio/asio/bind_executor.hpp
32195e04dfca1938996a6030eaabc3b5104ea194
[]
no_license
code1w/tomnet
f717194b644e1f32662a9c7024ea7f9a259f3991
e1685b72b97206cd3daefab7f8f8bab45fd4ce76
refs/heads/master
2023-02-27T12:25:34.143976
2021-02-01T06:52:07
2021-02-01T06:52:07
287,296,220
2
0
null
null
null
null
UTF-8
C++
false
false
16,602
hpp
// // bind_executor.hpp // ~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef ASIO_BIND_EXECUTOR_HPP #define ASIO_BIND_EXECUTOR_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/detail/type_traits.hpp" #include "asio/detail/variadic_templates.hpp" #include "asio/associated_executor.hpp" #include "asio/associated_allocator.hpp" #include "asio/async_result.hpp" #include "asio/execution/executor.hpp" #include "asio/execution_context.hpp" #include "asio/is_executor.hpp" #include "asio/uses_executor.hpp" #include "asio/detail/push_options.hpp" namespace asio { namespace detail { // Helper to automatically define nested typedef result_type. template <typename T, typename = void> struct executor_binder_result_type { protected: typedef void result_type_or_void; }; template <typename T> struct executor_binder_result_type<T, typename void_type<typename T::result_type>::type> { typedef typename T::result_type result_type; protected: typedef result_type result_type_or_void; }; template <typename R> struct executor_binder_result_type<R(*)()> { typedef R result_type; protected: typedef result_type result_type_or_void; }; template <typename R> struct executor_binder_result_type<R(&)()> { typedef R result_type; protected: typedef result_type result_type_or_void; }; template <typename R, typename A1> struct executor_binder_result_type<R(*)(A1)> { typedef R result_type; protected: typedef result_type result_type_or_void; }; template <typename R, typename A1> struct executor_binder_result_type<R(&)(A1)> { typedef R result_type; protected: typedef result_type result_type_or_void; }; template <typename R, typename A1, typename A2> struct executor_binder_result_type<R(*)(A1, A2)> { typedef R result_type; protected: typedef result_type result_type_or_void; }; template <typename R, typename A1, typename A2> struct executor_binder_result_type<R(&)(A1, A2)> { typedef R result_type; protected: typedef result_type result_type_or_void; }; // Helper to automatically define nested typedef argument_type. template <typename T, typename = void> struct executor_binder_argument_type {}; template <typename T> struct executor_binder_argument_type<T, typename void_type<typename T::argument_type>::type> { typedef typename T::argument_type argument_type; }; template <typename R, typename A1> struct executor_binder_argument_type<R(*)(A1)> { typedef A1 argument_type; }; template <typename R, typename A1> struct executor_binder_argument_type<R(&)(A1)> { typedef A1 argument_type; }; // Helper to automatically define nested typedefs first_argument_type and // second_argument_type. template <typename T, typename = void> struct executor_binder_argument_types {}; template <typename T> struct executor_binder_argument_types<T, typename void_type<typename T::first_argument_type>::type> { typedef typename T::first_argument_type first_argument_type; typedef typename T::second_argument_type second_argument_type; }; template <typename R, typename A1, typename A2> struct executor_binder_argument_type<R(*)(A1, A2)> { typedef A1 first_argument_type; typedef A2 second_argument_type; }; template <typename R, typename A1, typename A2> struct executor_binder_argument_type<R(&)(A1, A2)> { typedef A1 first_argument_type; typedef A2 second_argument_type; }; // Helper to perform uses_executor construction of the target type, if // required. template <typename T, typename Executor, bool UsesExecutor> class executor_binder_base; template <typename T, typename Executor> class executor_binder_base<T, Executor, true> { protected: template <typename E, typename U> executor_binder_base(ASIO_MOVE_ARG(E) e, ASIO_MOVE_ARG(U) u) : executor_(ASIO_MOVE_CAST(E)(e)), target_(executor_arg_t(), executor_, ASIO_MOVE_CAST(U)(u)) { } Executor executor_; T target_; }; template <typename T, typename Executor> class executor_binder_base<T, Executor, false> { protected: template <typename E, typename U> executor_binder_base(ASIO_MOVE_ARG(E) e, ASIO_MOVE_ARG(U) u) : executor_(ASIO_MOVE_CAST(E)(e)), target_(ASIO_MOVE_CAST(U)(u)) { } Executor executor_; T target_; }; // Helper to enable SFINAE on zero-argument operator() below. template <typename T, typename = void> struct executor_binder_result_of0 { typedef void type; }; template <typename T> struct executor_binder_result_of0<T, typename void_type<typename result_of<T()>::type>::type> { typedef typename result_of<T()>::type type; }; } // namespace detail /// A call wrapper type to bind an executor of type @c Executor to an object of /// type @c T. template <typename T, typename Executor> class executor_binder #if !defined(GENERATING_DOCUMENTATION) : public detail::executor_binder_result_type<T>, public detail::executor_binder_argument_type<T>, public detail::executor_binder_argument_types<T>, private detail::executor_binder_base< T, Executor, uses_executor<T, Executor>::value> #endif // !defined(GENERATING_DOCUMENTATION) { public: /// The type of the target object. typedef T target_type; /// The type of the associated executor. typedef Executor executor_type; #if defined(GENERATING_DOCUMENTATION) /// The return type if a function. /** * The type of @c result_type is based on the type @c T of the wrapper's * target object: * * @li if @c T is a pointer to function type, @c result_type is a synonym for * the return type of @c T; * * @li if @c T is a class type with a member type @c result_type, then @c * result_type is a synonym for @c T::result_type; * * @li otherwise @c result_type is not defined. */ typedef see_below result_type; /// The type of the function's argument. /** * The type of @c argument_type is based on the type @c T of the wrapper's * target object: * * @li if @c T is a pointer to a function type accepting a single argument, * @c argument_type is a synonym for the return type of @c T; * * @li if @c T is a class type with a member type @c argument_type, then @c * argument_type is a synonym for @c T::argument_type; * * @li otherwise @c argument_type is not defined. */ typedef see_below argument_type; /// The type of the function's first argument. /** * The type of @c first_argument_type is based on the type @c T of the * wrapper's target object: * * @li if @c T is a pointer to a function type accepting two arguments, @c * first_argument_type is a synonym for the return type of @c T; * * @li if @c T is a class type with a member type @c first_argument_type, * then @c first_argument_type is a synonym for @c T::first_argument_type; * * @li otherwise @c first_argument_type is not defined. */ typedef see_below first_argument_type; /// The type of the function's second argument. /** * The type of @c second_argument_type is based on the type @c T of the * wrapper's target object: * * @li if @c T is a pointer to a function type accepting two arguments, @c * second_argument_type is a synonym for the return type of @c T; * * @li if @c T is a class type with a member type @c first_argument_type, * then @c second_argument_type is a synonym for @c T::second_argument_type; * * @li otherwise @c second_argument_type is not defined. */ typedef see_below second_argument_type; #endif // defined(GENERATING_DOCUMENTATION) /// Construct an executor wrapper for the specified object. /** * This constructor is only valid if the type @c T is constructible from type * @c U. */ template <typename U> executor_binder(executor_arg_t, const executor_type& e, ASIO_MOVE_ARG(U) u) : base_type(e, ASIO_MOVE_CAST(U)(u)) { } /// Copy constructor. executor_binder(const executor_binder& other) : base_type(other.get_executor(), other.get()) { } /// Construct a copy, but specify a different executor. executor_binder(executor_arg_t, const executor_type& e, const executor_binder& other) : base_type(e, other.get()) { } /// Construct a copy of a different executor wrapper type. /** * This constructor is only valid if the @c Executor type is constructible * from type @c OtherExecutor, and the type @c T is constructible from type * @c U. */ template <typename U, typename OtherExecutor> executor_binder(const executor_binder<U, OtherExecutor>& other) : base_type(other.get_executor(), other.get()) { } /// Construct a copy of a different executor wrapper type, but specify a /// different executor. /** * This constructor is only valid if the type @c T is constructible from type * @c U. */ template <typename U, typename OtherExecutor> executor_binder(executor_arg_t, const executor_type& e, const executor_binder<U, OtherExecutor>& other) : base_type(e, other.get()) { } #if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) /// Move constructor. executor_binder(executor_binder&& other) : base_type(ASIO_MOVE_CAST(executor_type)(other.get_executor()), ASIO_MOVE_CAST(T)(other.get())) { } /// Move construct the target object, but specify a different executor. executor_binder(executor_arg_t, const executor_type& e, executor_binder&& other) : base_type(e, ASIO_MOVE_CAST(T)(other.get())) { } /// Move construct from a different executor wrapper type. template <typename U, typename OtherExecutor> executor_binder(executor_binder<U, OtherExecutor>&& other) : base_type(ASIO_MOVE_CAST(OtherExecutor)(other.get_executor()), ASIO_MOVE_CAST(U)(other.get())) { } /// Move construct from a different executor wrapper type, but specify a /// different executor. template <typename U, typename OtherExecutor> executor_binder(executor_arg_t, const executor_type& e, executor_binder<U, OtherExecutor>&& other) : base_type(e, ASIO_MOVE_CAST(U)(other.get())) { } #endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) /// Destructor. ~executor_binder() { } /// Obtain a reference to the target object. target_type& get() ASIO_NOEXCEPT { return this->target_; } /// Obtain a reference to the target object. const target_type& get() const ASIO_NOEXCEPT { return this->target_; } /// Obtain the associated executor. executor_type get_executor() const ASIO_NOEXCEPT { return this->executor_; } #if defined(GENERATING_DOCUMENTATION) template <typename... Args> auto operator()(Args&& ...); template <typename... Args> auto operator()(Args&& ...) const; #elif defined(ASIO_HAS_VARIADIC_TEMPLATES) /// Forwarding function call operator. template <typename... Args> typename result_of<T(Args...)>::type operator()( ASIO_MOVE_ARG(Args)... args) { return this->target_(ASIO_MOVE_CAST(Args)(args)...); } /// Forwarding function call operator. template <typename... Args> typename result_of<T(Args...)>::type operator()( ASIO_MOVE_ARG(Args)... args) const { return this->target_(ASIO_MOVE_CAST(Args)(args)...); } #elif defined(ASIO_HAS_STD_TYPE_TRAITS) && !defined(_MSC_VER) typename detail::executor_binder_result_of0<T>::type operator()() { return this->target_(); } typename detail::executor_binder_result_of0<T>::type operator()() const { return this->target_(); } #define ASIO_PRIVATE_BIND_EXECUTOR_CALL_DEF(n) \ template <ASIO_VARIADIC_TPARAMS(n)> \ typename result_of<T(ASIO_VARIADIC_TARGS(n))>::type operator()( \ ASIO_VARIADIC_MOVE_PARAMS(n)) \ { \ return this->target_(ASIO_VARIADIC_MOVE_ARGS(n)); \ } \ \ template <ASIO_VARIADIC_TPARAMS(n)> \ typename result_of<T(ASIO_VARIADIC_TARGS(n))>::type operator()( \ ASIO_VARIADIC_MOVE_PARAMS(n)) const \ { \ return this->target_(ASIO_VARIADIC_MOVE_ARGS(n)); \ } \ /**/ ASIO_VARIADIC_GENERATE(ASIO_PRIVATE_BIND_EXECUTOR_CALL_DEF) #undef ASIO_PRIVATE_BIND_EXECUTOR_CALL_DEF #else // defined(ASIO_HAS_STD_TYPE_TRAITS) && !defined(_MSC_VER) typedef typename detail::executor_binder_result_type<T>::result_type_or_void result_type_or_void; result_type_or_void operator()() { return this->target_(); } result_type_or_void operator()() const { return this->target_(); } #define ASIO_PRIVATE_BIND_EXECUTOR_CALL_DEF(n) \ template <ASIO_VARIADIC_TPARAMS(n)> \ result_type_or_void operator()( \ ASIO_VARIADIC_MOVE_PARAMS(n)) \ { \ return this->target_(ASIO_VARIADIC_MOVE_ARGS(n)); \ } \ \ template <ASIO_VARIADIC_TPARAMS(n)> \ result_type_or_void operator()( \ ASIO_VARIADIC_MOVE_PARAMS(n)) const \ { \ return this->target_(ASIO_VARIADIC_MOVE_ARGS(n)); \ } \ /**/ ASIO_VARIADIC_GENERATE(ASIO_PRIVATE_BIND_EXECUTOR_CALL_DEF) #undef ASIO_PRIVATE_BIND_EXECUTOR_CALL_DEF #endif // defined(ASIO_HAS_STD_TYPE_TRAITS) && !defined(_MSC_VER) private: typedef detail::executor_binder_base<T, Executor, uses_executor<T, Executor>::value> base_type; }; /// Associate an object of type @c T with an executor of type @c Executor. template <typename Executor, typename T> inline executor_binder<typename decay<T>::type, Executor> bind_executor(const Executor& ex, ASIO_MOVE_ARG(T) t, typename enable_if< is_executor<Executor>::value || execution::is_executor<Executor>::value >::type* = 0) { return executor_binder<typename decay<T>::type, Executor>( executor_arg_t(), ex, ASIO_MOVE_CAST(T)(t)); } /// Associate an object of type @c T with an execution context's executor. template <typename ExecutionContext, typename T> inline executor_binder<typename decay<T>::type, typename ExecutionContext::executor_type> bind_executor(ExecutionContext& ctx, ASIO_MOVE_ARG(T) t, typename enable_if<is_convertible< ExecutionContext&, execution_context&>::value>::type* = 0) { return executor_binder<typename decay<T>::type, typename ExecutionContext::executor_type>( executor_arg_t(), ctx.get_executor(), ASIO_MOVE_CAST(T)(t)); } #if !defined(GENERATING_DOCUMENTATION) template <typename T, typename Executor> struct uses_executor<executor_binder<T, Executor>, Executor> : true_type {}; template <typename T, typename Executor, typename Signature> class async_result<executor_binder<T, Executor>, Signature> { public: typedef executor_binder< typename async_result<T, Signature>::completion_handler_type, Executor> completion_handler_type; typedef typename async_result<T, Signature>::return_type return_type; explicit async_result(executor_binder<T, Executor>& b) : target_(b.get()) { } return_type get() { return target_.get(); } private: async_result(const async_result&) ASIO_DELETED; async_result& operator=(const async_result&) ASIO_DELETED; async_result<T, Signature> target_; }; template <typename T, typename Executor, typename Allocator> struct associated_allocator<executor_binder<T, Executor>, Allocator> { typedef typename associated_allocator<T, Allocator>::type type; static type get(const executor_binder<T, Executor>& b, const Allocator& a = Allocator()) ASIO_NOEXCEPT { return associated_allocator<T, Allocator>::get(b.get(), a); } }; template <typename T, typename Executor, typename Executor1> struct associated_executor<executor_binder<T, Executor>, Executor1> { typedef Executor type; static type get(const executor_binder<T, Executor>& b, const Executor1& = Executor1()) ASIO_NOEXCEPT { return b.get_executor(); } }; #endif // !defined(GENERATING_DOCUMENTATION) } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_BIND_EXECUTOR_HPP
[ "root@zt-2017914.ztgame.com" ]
root@zt-2017914.ztgame.com
0717f76619c0c604c91c6a59ff3d6273c46a8965
829b3f2d0ae685d01fe097c03bf5c1976cbc4723
/deps/boost/include/boost/multiprecision/mpc.hpp
b0b5a03dbe8c5b746dd9be5aeac0f2b469b5eb67
[ "Apache-2.0" ]
permissive
liyoung1992/mediasoup-sfu-cpp
f0f0321f8974beb1f4263c9e658402620d82385f
b76564e068626b0d675f5486e56da3d69151e287
refs/heads/main
2023-08-21T21:40:51.710022
2021-10-14T06:29:18
2021-10-14T06:29:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
52,857
hpp
/////////////////////////////////////////////////////////////////////////////// // Copyright 2018 John Maddock. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_MULTIPRECISION_MPC_HPP #define BOOST_MULTIPRECISION_MPC_HPP #include <boost/multiprecision/number.hpp> #include <boost/cstdint.hpp> #include <boost/multiprecision/detail/digits.hpp> #include <boost/multiprecision/detail/atomic.hpp> #include <boost/multiprecision/traits/is_variable_precision.hpp> #include <boost/multiprecision/mpfr.hpp> #include <boost/multiprecision/logged_adaptor.hpp> #include <boost/functional/hash_fwd.hpp> #include <mpc.h> #include <cmath> #include <algorithm> #include <complex> #ifndef BOOST_MULTIPRECISION_MPFI_DEFAULT_PRECISION #define BOOST_MULTIPRECISION_MPFI_DEFAULT_PRECISION 20 #endif namespace boost { namespace multiprecision { namespace backends { template <unsigned digits10> struct mpc_complex_backend; } // namespace backends template <unsigned digits10> struct number_category<backends::mpc_complex_backend<digits10> > : public mpl::int_<number_kind_complex> {}; namespace backends { namespace detail { inline void mpc_copy_precision(mpc_t dest, const mpc_t src) { mpfr_prec_t p_dest = mpc_get_prec(dest); mpfr_prec_t p_src = mpc_get_prec(src); if (p_dest != p_src) mpc_set_prec(dest, p_src); } inline void mpc_copy_precision(mpc_t dest, const mpc_t src1, const mpc_t src2) { mpfr_prec_t p_dest = mpc_get_prec(dest); mpfr_prec_t p_src1 = mpc_get_prec(src1); mpfr_prec_t p_src2 = mpc_get_prec(src2); if (p_src2 > p_src1) p_src1 = p_src2; if (p_dest != p_src1) mpc_set_prec(dest, p_src1); } template <unsigned digits10> struct mpc_complex_imp { #ifdef BOOST_HAS_LONG_LONG typedef mpl::list<long, boost::long_long_type> signed_types; typedef mpl::list<unsigned long, boost::ulong_long_type> unsigned_types; #else typedef mpl::list<long> signed_types; typedef mpl::list<unsigned long> unsigned_types; #endif typedef mpl::list<double, long double> float_types; typedef long exponent_type; mpc_complex_imp() { mpc_init2(m_data, multiprecision::detail::digits10_2_2(digits10 ? digits10 : (unsigned)get_default_precision())); mpc_set_ui(m_data, 0u, GMP_RNDN); } mpc_complex_imp(unsigned digits2) { mpc_init2(m_data, digits2); mpc_set_ui(m_data, 0u, GMP_RNDN); } mpc_complex_imp(const mpc_complex_imp& o) { mpc_init2(m_data, mpc_get_prec(o.m_data)); if (o.m_data[0].re[0]._mpfr_d) mpc_set(m_data, o.m_data, GMP_RNDN); } #ifndef BOOST_NO_CXX11_RVALUE_REFERENCES mpc_complex_imp(mpc_complex_imp&& o) BOOST_NOEXCEPT { m_data[0] = o.m_data[0]; o.m_data[0].re[0]._mpfr_d = 0; } #endif mpc_complex_imp& operator=(const mpc_complex_imp& o) { if ((o.m_data[0].re[0]._mpfr_d) && (this != &o)) { if (m_data[0].re[0]._mpfr_d == 0) mpc_init2(m_data, mpc_get_prec(o.m_data)); mpc_set(m_data, o.m_data, GMP_RNDD); } return *this; } #ifndef BOOST_NO_CXX11_RVALUE_REFERENCES mpc_complex_imp& operator=(mpc_complex_imp&& o) BOOST_NOEXCEPT { mpc_swap(m_data, o.m_data); return *this; } #endif #ifdef BOOST_HAS_LONG_LONG #ifdef _MPFR_H_HAVE_INTMAX_T mpc_complex_imp& operator=(boost::ulong_long_type i) { if (m_data[0].re[0]._mpfr_d == 0) mpc_init2(m_data, multiprecision::detail::digits10_2_2(digits10 ? digits10 : (unsigned)get_default_precision())); mpc_set_uj(data(), i, GMP_RNDD); return *this; } mpc_complex_imp& operator=(boost::long_long_type i) { if (m_data[0].re[0]._mpfr_d == 0) mpc_init2(m_data, multiprecision::detail::digits10_2_2(digits10 ? digits10 : (unsigned)get_default_precision())); mpc_set_sj(data(), i, GMP_RNDD); return *this; } #else mpc_complex_imp& operator=(boost::ulong_long_type i) { mpfr_float_backend<digits10> f(0uL, mpc_get_prec(m_data)); f = i; mpc_set_fr(this->data(), f.data(), GMP_RNDN); return *this; } mpc_complex_imp& operator=(boost::long_long_type i) { mpfr_float_backend<digits10> f(0uL, mpc_get_prec(m_data)); f = i; mpc_set_fr(this->data(), f.data(), GMP_RNDN); return *this; } #endif #endif mpc_complex_imp& operator=(unsigned long i) { if (m_data[0].re[0]._mpfr_d == 0) mpc_init2(m_data, multiprecision::detail::digits10_2_2(digits10 ? digits10 : (unsigned)get_default_precision())); mpc_set_ui(m_data, i, GMP_RNDN); return *this; } mpc_complex_imp& operator=(long i) { if (m_data[0].re[0]._mpfr_d == 0) mpc_init2(m_data, multiprecision::detail::digits10_2_2(digits10 ? digits10 : (unsigned)get_default_precision())); mpc_set_si(m_data, i, GMP_RNDN); return *this; } mpc_complex_imp& operator=(double d) { if (m_data[0].re[0]._mpfr_d == 0) mpc_init2(m_data, multiprecision::detail::digits10_2_2(digits10 ? digits10 : (unsigned)get_default_precision())); mpc_set_d(m_data, d, GMP_RNDN); return *this; } mpc_complex_imp& operator=(long double d) { if (m_data[0].re[0]._mpfr_d == 0) mpc_init2(m_data, multiprecision::detail::digits10_2_2(digits10 ? digits10 : (unsigned)get_default_precision())); mpc_set_ld(m_data, d, GMP_RNDN); return *this; } mpc_complex_imp& operator=(mpz_t i) { if (m_data[0].re[0]._mpfr_d == 0) mpc_init2(m_data, multiprecision::detail::digits10_2_2(digits10 ? digits10 : (unsigned)get_default_precision())); mpc_set_z(m_data, i, GMP_RNDN); return *this; } mpc_complex_imp& operator=(gmp_int i) { if (m_data[0].re[0]._mpfr_d == 0) mpc_init2(m_data, multiprecision::detail::digits10_2_2(digits10 ? digits10 : (unsigned)get_default_precision())); mpc_set_z(m_data, i.data(), GMP_RNDN); return *this; } mpc_complex_imp& operator=(const char* s) { using default_ops::eval_fpclassify; if (m_data[0].re[0]._mpfr_d == 0) mpc_init2(m_data, multiprecision::detail::digits10_2_2(digits10 ? digits10 : (unsigned)get_default_precision())); mpfr_float_backend<digits10> a(0uL, mpc_get_prec(m_data)), b(0uL, mpc_get_prec(m_data)); if (s && (*s == '(')) { std::string part; const char* p = ++s; while (*p && (*p != ',') && (*p != ')')) ++p; part.assign(s, p); if (part.size()) a = part.c_str(); else a = 0uL; s = p; if (*p && (*p != ')')) { ++p; while (*p && (*p != ')')) ++p; part.assign(s + 1, p); } else part.erase(); if (part.size()) b = part.c_str(); else b = 0uL; } else { a = s; b = 0uL; } if (eval_fpclassify(a) == (int)FP_NAN) { mpc_set_fr(this->data(), a.data(), GMP_RNDN); } else if (eval_fpclassify(b) == (int)FP_NAN) { mpc_set_fr(this->data(), b.data(), GMP_RNDN); } else { mpc_set_fr_fr(m_data, a.data(), b.data(), GMP_RNDN); } return *this; } void swap(mpc_complex_imp& o) BOOST_NOEXCEPT { mpc_swap(m_data, o.m_data); } std::string str(std::streamsize digits, std::ios_base::fmtflags f) const { BOOST_ASSERT(m_data[0].re[0]._mpfr_d); mpfr_float_backend<digits10> a(0uL, mpc_get_prec(m_data)), b(0uL, mpc_get_prec(m_data)); mpc_real(a.data(), m_data, GMP_RNDD); mpc_imag(b.data(), m_data, GMP_RNDD); if (eval_is_zero(b)) return a.str(digits, f); return "(" + a.str(digits, f) + "," + b.str(digits, f) + ")"; } ~mpc_complex_imp() BOOST_NOEXCEPT { if (m_data[0].re[0]._mpfr_d) mpc_clear(m_data); } void negate() BOOST_NOEXCEPT { BOOST_ASSERT(m_data[0].re[0]._mpfr_d); mpc_neg(m_data, m_data, GMP_RNDD); } int compare(const mpc_complex_imp& o) const BOOST_NOEXCEPT { BOOST_ASSERT(m_data[0].re[0]._mpfr_d && o.m_data[0].re[0]._mpfr_d); return mpc_cmp(m_data, o.m_data); } int compare(const mpc_complex_backend<digits10>& o) const BOOST_NOEXCEPT { BOOST_ASSERT(m_data[0].re[0]._mpfr_d && o.m_data[0].re[0]._mpfr_d); return mpc_cmp(m_data, o.data()); } int compare(long int i) const BOOST_NOEXCEPT { BOOST_ASSERT(m_data[0].re[0]._mpfr_d); return mpc_cmp_si(m_data, i); } int compare(unsigned long int i) const BOOST_NOEXCEPT { BOOST_ASSERT(m_data[0].re[0]._mpfr_d); static const unsigned long int max_val = (std::numeric_limits<long>::max)(); if (i > max_val) { mpc_complex_imp d(mpc_get_prec(m_data)); d = i; return compare(d); } return mpc_cmp_si(m_data, (long)i); } template <class V> int compare(const V& v) const BOOST_NOEXCEPT { mpc_complex_imp d(mpc_get_prec(m_data)); d = v; return compare(d); } mpc_t& data() BOOST_NOEXCEPT { BOOST_ASSERT(m_data[0].re[0]._mpfr_d); return m_data; } const mpc_t& data() const BOOST_NOEXCEPT { BOOST_ASSERT(m_data[0].re[0]._mpfr_d); return m_data; } protected: mpc_t m_data; static boost::multiprecision::detail::precision_type& get_default_precision() BOOST_NOEXCEPT { static boost::multiprecision::detail::precision_type val(BOOST_MULTIPRECISION_MPFI_DEFAULT_PRECISION); return val; } }; } // namespace detail template <unsigned digits10> struct mpc_complex_backend : public detail::mpc_complex_imp<digits10> { mpc_complex_backend() : detail::mpc_complex_imp<digits10>() {} mpc_complex_backend(const mpc_complex_backend& o) : detail::mpc_complex_imp<digits10>(o) {} #ifndef BOOST_NO_CXX11_RVALUE_REFERENCES mpc_complex_backend(mpc_complex_backend&& o) : detail::mpc_complex_imp<digits10>(static_cast<detail::mpc_complex_imp<digits10>&&>(o)) {} #endif template <unsigned D> mpc_complex_backend(const mpc_complex_backend<D>& val, typename enable_if_c<D <= digits10>::type* = 0) : detail::mpc_complex_imp<digits10>() { mpc_set(this->m_data, val.data(), GMP_RNDN); } template <unsigned D> explicit mpc_complex_backend(const mpc_complex_backend<D>& val, typename disable_if_c<D <= digits10>::type* = 0) : detail::mpc_complex_imp<digits10>() { mpc_set(this->m_data, val.data(), GMP_RNDN); } template <unsigned D> mpc_complex_backend(const mpfr_float_backend<D>& val, typename enable_if_c<D <= digits10>::type* = 0) : detail::mpc_complex_imp<digits10>() { mpc_set_fr(this->m_data, val.data(), GMP_RNDN); } template <unsigned D> explicit mpc_complex_backend(const mpfr_float_backend<D>& val, typename disable_if_c<D <= digits10>::type* = 0) : detail::mpc_complex_imp<digits10>() { mpc_set(this->m_data, val.data(), GMP_RNDN); } mpc_complex_backend(const mpc_t val) : detail::mpc_complex_imp<digits10>() { mpc_set(this->m_data, val, GMP_RNDN); } mpc_complex_backend(const std::complex<float>& val) : detail::mpc_complex_imp<digits10>() { mpc_set_d_d(this->m_data, val.real(), val.imag(), GMP_RNDN); } mpc_complex_backend(const std::complex<double>& val) : detail::mpc_complex_imp<digits10>() { mpc_set_d_d(this->m_data, val.real(), val.imag(), GMP_RNDN); } mpc_complex_backend(const std::complex<long double>& val) : detail::mpc_complex_imp<digits10>() { mpc_set_ld_ld(this->m_data, val.real(), val.imag(), GMP_RNDN); } mpc_complex_backend(mpz_srcptr val) : detail::mpc_complex_imp<digits10>() { mpc_set_z(this->m_data, val, GMP_RNDN); } mpc_complex_backend& operator=(mpz_srcptr val) { mpc_set_z(this->m_data, val, GMP_RNDN); return *this; } mpc_complex_backend(gmp_int const& val) : detail::mpc_complex_imp<digits10>() { mpc_set_z(this->m_data, val.data(), GMP_RNDN); } mpc_complex_backend& operator=(gmp_int const& val) { mpc_set_z(this->m_data, val.data(), GMP_RNDN); return *this; } mpc_complex_backend(mpf_srcptr val) : detail::mpc_complex_imp<digits10>() { mpc_set_f(this->m_data, val, GMP_RNDN); } mpc_complex_backend& operator=(mpf_srcptr val) { mpc_set_f(this->m_data, val, GMP_RNDN); return *this; } template <unsigned D10> mpc_complex_backend(gmp_float<D10> const& val) : detail::mpc_complex_imp<digits10>() { mpc_set_f(this->m_data, val.data(), GMP_RNDN); } template <unsigned D10> mpc_complex_backend& operator=(gmp_float<D10> const& val) { mpc_set_f(this->m_data, val.data(), GMP_RNDN); return *this; } mpc_complex_backend(mpq_srcptr val) : detail::mpc_complex_imp<digits10>() { mpc_set_q(this->m_data, val, GMP_RNDN); } mpc_complex_backend& operator=(mpq_srcptr val) { mpc_set_q(this->m_data, val, GMP_RNDN); return *this; } mpc_complex_backend(gmp_rational const& val) : detail::mpc_complex_imp<digits10>() { mpc_set_q(this->m_data, val.data(), GMP_RNDN); } mpc_complex_backend& operator=(gmp_rational const& val) { mpc_set_q(this->m_data, val.data(), GMP_RNDN); return *this; } mpc_complex_backend(mpfr_srcptr val) : detail::mpc_complex_imp<digits10>() { mpc_set_fr(this->m_data, val, GMP_RNDN); } mpc_complex_backend& operator=(mpfr_srcptr val) { mpc_set_fr(this->m_data, val, GMP_RNDN); return *this; } template <unsigned D10, mpfr_allocation_type AllocationType> mpc_complex_backend(mpfr_float_backend<D10, AllocationType> const& val) : detail::mpc_complex_imp<digits10>() { mpc_set_fr(this->m_data, val.data(), GMP_RNDN); } template <unsigned D10, mpfr_allocation_type AllocationType> mpc_complex_backend& operator=(mpfr_float_backend<D10, AllocationType> const& val) { mpc_set_fr(this->m_data, val.data(), GMP_RNDN); return *this; } mpc_complex_backend& operator=(const mpc_complex_backend& o) { *static_cast<detail::mpc_complex_imp<digits10>*>(this) = static_cast<detail::mpc_complex_imp<digits10> const&>(o); return *this; } #ifndef BOOST_NO_CXX11_RVALUE_REFERENCES mpc_complex_backend& operator=(mpc_complex_backend&& o) BOOST_NOEXCEPT { *static_cast<detail::mpc_complex_imp<digits10>*>(this) = static_cast<detail::mpc_complex_imp<digits10>&&>(o); return *this; } #endif template <class V> mpc_complex_backend& operator=(const V& v) { *static_cast<detail::mpc_complex_imp<digits10>*>(this) = v; return *this; } mpc_complex_backend& operator=(const mpc_t val) { mpc_set(this->m_data, val, GMP_RNDN); return *this; } mpc_complex_backend& operator=(const std::complex<float>& val) { mpc_set_d_d(this->m_data, val.real(), val.imag(), GMP_RNDN); return *this; } mpc_complex_backend& operator=(const std::complex<double>& val) { mpc_set_d_d(this->m_data, val.real(), val.imag(), GMP_RNDN); return *this; } mpc_complex_backend& operator=(const std::complex<long double>& val) { mpc_set_ld_ld(this->m_data, val.real(), val.imag(), GMP_RNDN); return *this; } // We don't change our precision here, this is a fixed precision type: template <unsigned D> mpc_complex_backend& operator=(const mpc_complex_backend<D>& val) { mpc_set(this->m_data, val.data(), GMP_RNDN); return *this; } }; template <> struct mpc_complex_backend<0> : public detail::mpc_complex_imp<0> { mpc_complex_backend() : detail::mpc_complex_imp<0>() {} mpc_complex_backend(const mpc_t val) : detail::mpc_complex_imp<0>(mpc_get_prec(val)) { mpc_set(this->m_data, val, GMP_RNDN); } mpc_complex_backend(const mpc_complex_backend& o) : detail::mpc_complex_imp<0>(o) {} #ifndef BOOST_NO_CXX11_RVALUE_REFERENCES mpc_complex_backend(mpc_complex_backend&& o) BOOST_NOEXCEPT : detail::mpc_complex_imp<0>(static_cast<detail::mpc_complex_imp<0>&&>(o)) {} #endif mpc_complex_backend(const mpc_complex_backend& o, unsigned digits10) : detail::mpc_complex_imp<0>(multiprecision::detail::digits10_2_2(digits10)) { mpc_set(this->m_data, o.data(), GMP_RNDN); } template <unsigned D> mpc_complex_backend(const mpc_complex_backend<D>& val) : detail::mpc_complex_imp<0>(mpc_get_prec(val.data())) { mpc_set(this->m_data, val.data(), GMP_RNDN); } template <unsigned D> mpc_complex_backend(const mpfr_float_backend<D>& val) : detail::mpc_complex_imp<0>(mpfr_get_prec(val.data())) { mpc_set_fr(this->m_data, val.data(), GMP_RNDN); } mpc_complex_backend(mpz_srcptr val) : detail::mpc_complex_imp<0>() { mpc_set_z(this->m_data, val, GMP_RNDN); } mpc_complex_backend& operator=(mpz_srcptr val) { mpc_set_z(this->m_data, val, GMP_RNDN); return *this; } mpc_complex_backend(gmp_int const& val) : detail::mpc_complex_imp<0>() { mpc_set_z(this->m_data, val.data(), GMP_RNDN); } mpc_complex_backend& operator=(gmp_int const& val) { mpc_set_z(this->m_data, val.data(), GMP_RNDN); return *this; } mpc_complex_backend(mpf_srcptr val) : detail::mpc_complex_imp<0>((unsigned)mpf_get_prec(val)) { mpc_set_f(this->m_data, val, GMP_RNDN); } mpc_complex_backend& operator=(mpf_srcptr val) { if ((mp_bitcnt_t)mpc_get_prec(data()) != mpf_get_prec(val)) { mpc_complex_backend t(val); t.swap(*this); } else mpc_set_f(this->m_data, val, GMP_RNDN); return *this; } template <unsigned digits10> mpc_complex_backend(gmp_float<digits10> const& val) : detail::mpc_complex_imp<0>((unsigned)mpf_get_prec(val.data())) { mpc_set_f(this->m_data, val.data(), GMP_RNDN); } template <unsigned digits10> mpc_complex_backend& operator=(gmp_float<digits10> const& val) { if (mpc_get_prec(data()) != (mpfr_prec_t)mpf_get_prec(val.data())) { mpc_complex_backend t(val); t.swap(*this); } else mpc_set_f(this->m_data, val.data(), GMP_RNDN); return *this; } mpc_complex_backend(mpq_srcptr val) : detail::mpc_complex_imp<0>() { mpc_set_q(this->m_data, val, GMP_RNDN); } mpc_complex_backend& operator=(mpq_srcptr val) { mpc_set_q(this->m_data, val, GMP_RNDN); return *this; } mpc_complex_backend(gmp_rational const& val) : detail::mpc_complex_imp<0>() { mpc_set_q(this->m_data, val.data(), GMP_RNDN); } mpc_complex_backend& operator=(gmp_rational const& val) { mpc_set_q(this->m_data, val.data(), GMP_RNDN); return *this; } mpc_complex_backend(mpfr_srcptr val) : detail::mpc_complex_imp<0>(mpfr_get_prec(val)) { mpc_set_fr(this->m_data, val, GMP_RNDN); } mpc_complex_backend& operator=(mpfr_srcptr val) { if (mpc_get_prec(data()) != mpfr_get_prec(val)) { mpc_complex_backend t(val); t.swap(*this); } else mpc_set_fr(this->m_data, val, GMP_RNDN); return *this; } mpc_complex_backend(const std::complex<float>& val) : detail::mpc_complex_imp<0>() { mpc_set_d_d(this->m_data, val.real(), val.imag(), GMP_RNDN); } mpc_complex_backend(const std::complex<double>& val) : detail::mpc_complex_imp<0>() { mpc_set_d_d(this->m_data, val.real(), val.imag(), GMP_RNDN); } mpc_complex_backend(const std::complex<long double>& val) : detail::mpc_complex_imp<0>() { mpc_set_ld_ld(this->m_data, val.real(), val.imag(), GMP_RNDN); } // Construction with precision: template <class T, class U> mpc_complex_backend(const T& a, const U& b, unsigned digits10) : detail::mpc_complex_imp<0>(multiprecision::detail::digits10_2_2(digits10)) { // We can't use assign_components here because it copies the precision of // a and b, not digits10.... mpfr_float ca(a), cb(b); mpc_set_fr_fr(this->data(), ca.backend().data(), cb.backend().data(), GMP_RNDN); } template <unsigned N> mpc_complex_backend(const mpfr_float_backend<N>& a, const mpfr_float_backend<N>& b, unsigned digits10) : detail::mpc_complex_imp<0>(multiprecision::detail::digits10_2_2(digits10)) { mpc_set_fr_fr(this->data(), a.data(), b.data(), GMP_RNDN); } mpc_complex_backend& operator=(const mpc_complex_backend& o) { if (this != &o) { detail::mpc_copy_precision(this->m_data, o.data()); mpc_set(this->m_data, o.data(), GMP_RNDN); } return *this; } #ifndef BOOST_NO_CXX11_RVALUE_REFERENCES mpc_complex_backend& operator=(mpc_complex_backend&& o) BOOST_NOEXCEPT { *static_cast<detail::mpc_complex_imp<0>*>(this) = static_cast<detail::mpc_complex_imp<0>&&>(o); return *this; } #endif template <class V> mpc_complex_backend& operator=(const V& v) { *static_cast<detail::mpc_complex_imp<0>*>(this) = v; return *this; } mpc_complex_backend& operator=(const mpc_t val) { mpc_set_prec(this->m_data, mpc_get_prec(val)); mpc_set(this->m_data, val, GMP_RNDN); return *this; } template <unsigned D> mpc_complex_backend& operator=(const mpc_complex_backend<D>& val) { mpc_set_prec(this->m_data, mpc_get_prec(val.data())); mpc_set(this->m_data, val.data(), GMP_RNDN); return *this; } template <unsigned D> mpc_complex_backend& operator=(const mpfr_float_backend<D>& val) { mpc_set_prec(this->m_data, mpfr_get_prec(val.data())); mpc_set_fr(this->m_data, val.data(), GMP_RNDN); return *this; } mpc_complex_backend& operator=(const std::complex<float>& val) { mpc_set_d_d(this->m_data, val.real(), val.imag(), GMP_RNDN); return *this; } mpc_complex_backend& operator=(const std::complex<double>& val) { mpc_set_d_d(this->m_data, val.real(), val.imag(), GMP_RNDN); return *this; } mpc_complex_backend& operator=(const std::complex<long double>& val) { mpc_set_ld_ld(this->m_data, val.real(), val.imag(), GMP_RNDN); return *this; } static unsigned default_precision() BOOST_NOEXCEPT { return get_default_precision(); } static void default_precision(unsigned v) BOOST_NOEXCEPT { get_default_precision() = v; } unsigned precision() const BOOST_NOEXCEPT { return multiprecision::detail::digits2_2_10(mpc_get_prec(this->m_data)); } void precision(unsigned digits10) BOOST_NOEXCEPT { mpfr_prec_round(mpc_realref(this->m_data), multiprecision::detail::digits10_2_2((digits10)), GMP_RNDN); mpfr_prec_round(mpc_imagref(this->m_data), multiprecision::detail::digits10_2_2((digits10)), GMP_RNDN); } }; template <unsigned digits10, class T> inline typename enable_if<is_arithmetic<T>, bool>::type eval_eq(const mpc_complex_backend<digits10>& a, const T& b) BOOST_NOEXCEPT { return a.compare(b) == 0; } template <unsigned digits10, class T> inline typename enable_if<is_arithmetic<T>, bool>::type eval_lt(const mpc_complex_backend<digits10>& a, const T& b) BOOST_NOEXCEPT { return a.compare(b) < 0; } template <unsigned digits10, class T> inline typename enable_if<is_arithmetic<T>, bool>::type eval_gt(const mpc_complex_backend<digits10>& a, const T& b) BOOST_NOEXCEPT { return a.compare(b) > 0; } template <unsigned D1, unsigned D2> inline void eval_add(mpc_complex_backend<D1>& result, const mpc_complex_backend<D2>& o) { mpc_add(result.data(), result.data(), o.data(), GMP_RNDD); } template <unsigned D1, unsigned D2> inline void eval_add(mpc_complex_backend<D1>& result, const mpfr_float_backend<D2>& o) { mpc_add_fr(result.data(), result.data(), o.data(), GMP_RNDD); } template <unsigned D1, unsigned D2> inline void eval_subtract(mpc_complex_backend<D1>& result, const mpc_complex_backend<D2>& o) { mpc_sub(result.data(), result.data(), o.data(), GMP_RNDD); } template <unsigned D1, unsigned D2> inline void eval_subtract(mpc_complex_backend<D1>& result, const mpfr_float_backend<D2>& o) { mpc_sub_fr(result.data(), result.data(), o.data(), GMP_RNDD); } template <unsigned D1, unsigned D2> inline void eval_multiply(mpc_complex_backend<D1>& result, const mpc_complex_backend<D2>& o) { if ((void*)&result == (void*)&o) mpc_sqr(result.data(), o.data(), GMP_RNDN); else mpc_mul(result.data(), result.data(), o.data(), GMP_RNDN); } template <unsigned D1, unsigned D2> inline void eval_multiply(mpc_complex_backend<D1>& result, const mpfr_float_backend<D2>& o) { mpc_mul_fr(result.data(), result.data(), o.data(), GMP_RNDN); } template <unsigned D1, unsigned D2> inline void eval_divide(mpc_complex_backend<D1>& result, const mpc_complex_backend<D2>& o) { mpc_div(result.data(), result.data(), o.data(), GMP_RNDD); } template <unsigned D1, unsigned D2> inline void eval_divide(mpc_complex_backend<D1>& result, const mpfr_float_backend<D2>& o) { mpc_div_fr(result.data(), result.data(), o.data(), GMP_RNDD); } template <unsigned digits10> inline void eval_add(mpc_complex_backend<digits10>& result, unsigned long i) { mpc_add_ui(result.data(), result.data(), i, GMP_RNDN); } template <unsigned digits10> inline void eval_subtract(mpc_complex_backend<digits10>& result, unsigned long i) { mpc_sub_ui(result.data(), result.data(), i, GMP_RNDN); } template <unsigned digits10> inline void eval_multiply(mpc_complex_backend<digits10>& result, unsigned long i) { mpc_mul_ui(result.data(), result.data(), i, GMP_RNDN); } template <unsigned digits10> inline void eval_divide(mpc_complex_backend<digits10>& result, unsigned long i) { mpc_div_ui(result.data(), result.data(), i, GMP_RNDN); } template <unsigned digits10> inline void eval_add(mpc_complex_backend<digits10>& result, long i) { if (i > 0) mpc_add_ui(result.data(), result.data(), i, GMP_RNDN); else mpc_sub_ui(result.data(), result.data(), boost::multiprecision::detail::unsigned_abs(i), GMP_RNDN); } template <unsigned digits10> inline void eval_subtract(mpc_complex_backend<digits10>& result, long i) { if (i > 0) mpc_sub_ui(result.data(), result.data(), i, GMP_RNDN); else mpc_add_ui(result.data(), result.data(), boost::multiprecision::detail::unsigned_abs(i), GMP_RNDN); } template <unsigned digits10> inline void eval_multiply(mpc_complex_backend<digits10>& result, long i) { mpc_mul_ui(result.data(), result.data(), boost::multiprecision::detail::unsigned_abs(i), GMP_RNDN); if (i < 0) mpc_neg(result.data(), result.data(), GMP_RNDN); } template <unsigned digits10> inline void eval_divide(mpc_complex_backend<digits10>& result, long i) { mpc_div_ui(result.data(), result.data(), boost::multiprecision::detail::unsigned_abs(i), GMP_RNDN); if (i < 0) mpc_neg(result.data(), result.data(), GMP_RNDN); } // // Specialised 3 arg versions of the basic operators: // template <unsigned D1, unsigned D2, unsigned D3> inline void eval_add(mpc_complex_backend<D1>& a, const mpc_complex_backend<D2>& x, const mpc_complex_backend<D3>& y) { mpc_add(a.data(), x.data(), y.data(), GMP_RNDD); } template <unsigned D1, unsigned D2, unsigned D3> inline void eval_add(mpc_complex_backend<D1>& a, const mpc_complex_backend<D2>& x, const mpfr_float_backend<D3>& y) { mpc_add_fr(a.data(), x.data(), y.data(), GMP_RNDD); } template <unsigned D1, unsigned D2, unsigned D3> inline void eval_add(mpc_complex_backend<D1>& a, const mpfr_float_backend<D2>& x, const mpc_complex_backend<D3>& y) { mpc_add_fr(a.data(), y.data(), x.data(), GMP_RNDD); } template <unsigned D1, unsigned D2> inline void eval_add(mpc_complex_backend<D1>& a, const mpc_complex_backend<D2>& x, unsigned long y) { mpc_add_ui(a.data(), x.data(), y, GMP_RNDD); } template <unsigned D1, unsigned D2> inline void eval_add(mpc_complex_backend<D1>& a, const mpc_complex_backend<D2>& x, long y) { if (y < 0) mpc_sub_ui(a.data(), x.data(), boost::multiprecision::detail::unsigned_abs(y), GMP_RNDD); else mpc_add_ui(a.data(), x.data(), y, GMP_RNDD); } template <unsigned D1, unsigned D2> inline void eval_add(mpc_complex_backend<D1>& a, unsigned long x, const mpc_complex_backend<D2>& y) { mpc_add_ui(a.data(), y.data(), x, GMP_RNDD); } template <unsigned D1, unsigned D2> inline void eval_add(mpc_complex_backend<D1>& a, long x, const mpc_complex_backend<D2>& y) { if (x < 0) { mpc_ui_sub(a.data(), boost::multiprecision::detail::unsigned_abs(x), y.data(), GMP_RNDN); mpc_neg(a.data(), a.data(), GMP_RNDD); } else mpc_add_ui(a.data(), y.data(), x, GMP_RNDD); } template <unsigned D1, unsigned D2, unsigned D3> inline void eval_subtract(mpc_complex_backend<D1>& a, const mpc_complex_backend<D2>& x, const mpc_complex_backend<D3>& y) { mpc_sub(a.data(), x.data(), y.data(), GMP_RNDD); } template <unsigned D1, unsigned D2, unsigned D3> inline void eval_subtract(mpc_complex_backend<D1>& a, const mpc_complex_backend<D2>& x, const mpfr_float_backend<D3>& y) { mpc_sub_fr(a.data(), x.data(), y.data(), GMP_RNDD); } template <unsigned D1, unsigned D2, unsigned D3> inline void eval_subtract(mpc_complex_backend<D1>& a, const mpfr_float_backend<D2>& x, const mpc_complex_backend<D3>& y) { mpc_fr_sub(a.data(), x.data(), y.data(), GMP_RNDD); } template <unsigned D1, unsigned D2> inline void eval_subtract(mpc_complex_backend<D1>& a, const mpc_complex_backend<D2>& x, unsigned long y) { mpc_sub_ui(a.data(), x.data(), y, GMP_RNDD); } template <unsigned D1, unsigned D2> inline void eval_subtract(mpc_complex_backend<D1>& a, const mpc_complex_backend<D2>& x, long y) { if (y < 0) mpc_add_ui(a.data(), x.data(), boost::multiprecision::detail::unsigned_abs(y), GMP_RNDD); else mpc_sub_ui(a.data(), x.data(), y, GMP_RNDD); } template <unsigned D1, unsigned D2> inline void eval_subtract(mpc_complex_backend<D1>& a, unsigned long x, const mpc_complex_backend<D2>& y) { mpc_ui_sub(a.data(), x, y.data(), GMP_RNDN); } template <unsigned D1, unsigned D2> inline void eval_subtract(mpc_complex_backend<D1>& a, long x, const mpc_complex_backend<D2>& y) { if (x < 0) { mpc_add_ui(a.data(), y.data(), boost::multiprecision::detail::unsigned_abs(x), GMP_RNDD); mpc_neg(a.data(), a.data(), GMP_RNDD); } else mpc_ui_sub(a.data(), x, y.data(), GMP_RNDN); } template <unsigned D1, unsigned D2, unsigned D3> inline void eval_multiply(mpc_complex_backend<D1>& a, const mpc_complex_backend<D2>& x, const mpc_complex_backend<D3>& y) { if ((void*)&x == (void*)&y) mpc_sqr(a.data(), x.data(), GMP_RNDD); else mpc_mul(a.data(), x.data(), y.data(), GMP_RNDD); } template <unsigned D1, unsigned D2, unsigned D3> inline void eval_multiply(mpc_complex_backend<D1>& a, const mpc_complex_backend<D2>& x, const mpfr_float_backend<D3>& y) { mpc_mul_fr(a.data(), x.data(), y.data(), GMP_RNDD); } template <unsigned D1, unsigned D2, unsigned D3> inline void eval_multiply(mpc_complex_backend<D1>& a, const mpfr_float_backend<D2>& x, const mpc_complex_backend<D3>& y) { mpc_mul_fr(a.data(), y.data(), x.data(), GMP_RNDD); } template <unsigned D1, unsigned D2> inline void eval_multiply(mpc_complex_backend<D1>& a, const mpc_complex_backend<D2>& x, unsigned long y) { mpc_mul_ui(a.data(), x.data(), y, GMP_RNDD); } template <unsigned D1, unsigned D2> inline void eval_multiply(mpc_complex_backend<D1>& a, const mpc_complex_backend<D2>& x, long y) { if (y < 0) { mpc_mul_ui(a.data(), x.data(), boost::multiprecision::detail::unsigned_abs(y), GMP_RNDD); a.negate(); } else mpc_mul_ui(a.data(), x.data(), y, GMP_RNDD); } template <unsigned D1, unsigned D2> inline void eval_multiply(mpc_complex_backend<D1>& a, unsigned long x, const mpc_complex_backend<D2>& y) { mpc_mul_ui(a.data(), y.data(), x, GMP_RNDD); } template <unsigned D1, unsigned D2> inline void eval_multiply(mpc_complex_backend<D1>& a, long x, const mpc_complex_backend<D2>& y) { if (x < 0) { mpc_mul_ui(a.data(), y.data(), boost::multiprecision::detail::unsigned_abs(x), GMP_RNDD); mpc_neg(a.data(), a.data(), GMP_RNDD); } else mpc_mul_ui(a.data(), y.data(), x, GMP_RNDD); } template <unsigned D1, unsigned D2, unsigned D3> inline void eval_divide(mpc_complex_backend<D1>& a, const mpc_complex_backend<D2>& x, const mpc_complex_backend<D3>& y) { mpc_div(a.data(), x.data(), y.data(), GMP_RNDD); } template <unsigned D1, unsigned D2, unsigned D3> inline void eval_divide(mpc_complex_backend<D1>& a, const mpc_complex_backend<D2>& x, const mpfr_float_backend<D3>& y) { mpc_div_fr(a.data(), x.data(), y.data(), GMP_RNDD); } template <unsigned D1, unsigned D2, unsigned D3> inline void eval_divide(mpc_complex_backend<D1>& a, const mpfr_float_backend<D2>& x, const mpc_complex_backend<D3>& y) { mpc_fr_div(a.data(), x.data(), y.data(), GMP_RNDD); } template <unsigned D1, unsigned D2> inline void eval_divide(mpc_complex_backend<D1>& a, const mpc_complex_backend<D2>& x, unsigned long y) { mpc_div_ui(a.data(), x.data(), y, GMP_RNDD); } template <unsigned D1, unsigned D2> inline void eval_divide(mpc_complex_backend<D1>& a, const mpc_complex_backend<D2>& x, long y) { if (y < 0) { mpc_div_ui(a.data(), x.data(), boost::multiprecision::detail::unsigned_abs(y), GMP_RNDD); a.negate(); } else mpc_div_ui(a.data(), x.data(), y, GMP_RNDD); } template <unsigned D1, unsigned D2> inline void eval_divide(mpc_complex_backend<D1>& a, unsigned long x, const mpc_complex_backend<D2>& y) { mpc_ui_div(a.data(), x, y.data(), GMP_RNDD); } template <unsigned D1, unsigned D2> inline void eval_divide(mpc_complex_backend<D1>& a, long x, const mpc_complex_backend<D2>& y) { if (x < 0) { mpc_ui_div(a.data(), boost::multiprecision::detail::unsigned_abs(x), y.data(), GMP_RNDD); mpc_neg(a.data(), a.data(), GMP_RNDD); } else mpc_ui_div(a.data(), x, y.data(), GMP_RNDD); } template <unsigned digits10> inline bool eval_is_zero(const mpc_complex_backend<digits10>& val) BOOST_NOEXCEPT { return (0 != mpfr_zero_p(mpc_realref(val.data()))) && (0 != mpfr_zero_p(mpc_imagref(val.data()))); } template <unsigned digits10> inline int eval_get_sign(const mpc_complex_backend<digits10>&) { BOOST_STATIC_ASSERT_MSG(digits10 == UINT_MAX, "Complex numbers have no sign bit."); // designed to always fail return 0; } template <unsigned digits10> inline void eval_convert_to(unsigned long* result, const mpc_complex_backend<digits10>& val) { if (0 == mpfr_zero_p(mpc_imagref(val.data()))) { BOOST_THROW_EXCEPTION(std::runtime_error("Could not convert imaginary number to scalar.")); } mpfr_float_backend<digits10> t; mpc_real(t.data(), val.data(), GMP_RNDN); eval_convert_to(result, t); } template <unsigned digits10> inline void eval_convert_to(long* result, const mpc_complex_backend<digits10>& val) { if (0 == mpfr_zero_p(mpc_imagref(val.data()))) { BOOST_THROW_EXCEPTION(std::runtime_error("Could not convert imaginary number to scalar.")); } mpfr_float_backend<digits10> t; mpc_real(t.data(), val.data(), GMP_RNDN); eval_convert_to(result, t); } #ifdef _MPFR_H_HAVE_INTMAX_T template <unsigned digits10> inline void eval_convert_to(boost::ulong_long_type* result, const mpc_complex_backend<digits10>& val) { if (0 == mpfr_zero_p(mpc_imagref(val.data()))) { BOOST_THROW_EXCEPTION(std::runtime_error("Could not convert imaginary number to scalar.")); } mpfr_float_backend<digits10> t; mpc_real(t.data(), val.data(), GMP_RNDN); eval_convert_to(result, t); } template <unsigned digits10> inline void eval_convert_to(boost::long_long_type* result, const mpc_complex_backend<digits10>& val) { if (0 == mpfr_zero_p(mpc_imagref(val.data()))) { BOOST_THROW_EXCEPTION(std::runtime_error("Could not convert imaginary number to scalar.")); } mpfr_float_backend<digits10> t; mpc_real(t.data(), val.data(), GMP_RNDN); eval_convert_to(result, t); } #endif template <unsigned digits10> inline void eval_convert_to(double* result, const mpc_complex_backend<digits10>& val) BOOST_NOEXCEPT { if (0 == mpfr_zero_p(mpc_imagref(val.data()))) { BOOST_THROW_EXCEPTION(std::runtime_error("Could not convert imaginary number to scalar.")); } mpfr_float_backend<digits10> t; mpc_real(t.data(), val.data(), GMP_RNDN); eval_convert_to(result, t); } template <unsigned digits10> inline void eval_convert_to(long double* result, const mpc_complex_backend<digits10>& val) BOOST_NOEXCEPT { if (0 == mpfr_zero_p(mpc_imagref(val.data()))) { BOOST_THROW_EXCEPTION(std::runtime_error("Could not convert imaginary number to scalar.")); } mpfr_float_backend<digits10> t; mpc_real(t.data(), val.data(), GMP_RNDN); eval_convert_to(result, t); } template <unsigned D1, unsigned D2, mpfr_allocation_type AllocationType> inline void assign_components(mpc_complex_backend<D1>& result, const mpfr_float_backend<D2, AllocationType>& a, const mpfr_float_backend<D2, AllocationType>& b) { // // This is called from class number's constructors, so if we have variable // precision, then copy the precision of the source variables. // if (!D1) { unsigned long prec = (std::max)(mpfr_get_prec(a.data()), mpfr_get_prec(b.data())); mpc_set_prec(result.data(), prec); } using default_ops::eval_fpclassify; if (eval_fpclassify(a) == (int)FP_NAN) { mpc_set_fr(result.data(), a.data(), GMP_RNDN); } else if (eval_fpclassify(b) == (int)FP_NAN) { mpc_set_fr(result.data(), b.data(), GMP_RNDN); } else { mpc_set_fr_fr(result.data(), a.data(), b.data(), GMP_RNDN); } } template <unsigned D1, unsigned D2, mpfr_allocation_type AllocationType> inline void assign_components(mpc_complex_backend<D1>& result, unsigned long a, unsigned long b) { mpc_set_ui_ui(result.data(), a, b, GMP_RNDN); } template <unsigned D1, unsigned D2, mpfr_allocation_type AllocationType> inline void assign_components(mpc_complex_backend<D1>& result, long a, long b) { mpc_set_si_si(result.data(), a, b, GMP_RNDN); } #if defined(BOOST_HAS_LONG_LONG) && defined(_MPFR_H_HAVE_INTMAX_T) template <unsigned D1, unsigned D2, mpfr_allocation_type AllocationType> inline void assign_components(mpc_complex_backend<D1>& result, unsigned long long a, unsigned long long b) { mpc_set_uj_uj(result.data(), a, b, GMP_RNDN); } template <unsigned D1, unsigned D2, mpfr_allocation_type AllocationType> inline void assign_components(mpc_complex_backend<D1>& result, long long a, long long b) { mpc_set_sj_sj(result.data(), a, b, GMP_RNDN); } #endif template <unsigned D1, unsigned D2, mpfr_allocation_type AllocationType> inline void assign_components(mpc_complex_backend<D1>& result, double a, double b) { if ((boost::math::isnan)(a)) { mpc_set_d(result.data(), a, GMP_RNDN); } else if ((boost::math::isnan)(b)) { mpc_set_d(result.data(), b, GMP_RNDN); } else { mpc_set_d_d(result.data(), a, b, GMP_RNDN); } } template <unsigned D1, unsigned D2, mpfr_allocation_type AllocationType> inline void assign_components(mpc_complex_backend<D1>& result, long double a, long double b) { if ((boost::math::isnan)(a)) { mpc_set_d(result.data(), a, GMP_RNDN); } else if ((boost::math::isnan)(b)) { mpc_set_d(result.data(), b, GMP_RNDN); } else { mpc_set_ld_ld(result.data(), a, b, GMP_RNDN); } } // // Native non-member operations: // template <unsigned Digits10> inline void eval_sqrt(mpc_complex_backend<Digits10>& result, const mpc_complex_backend<Digits10>& val) { mpc_sqrt(result.data(), val.data(), GMP_RNDN); } template <unsigned Digits10> inline void eval_pow(mpc_complex_backend<Digits10>& result, const mpc_complex_backend<Digits10>& b, const mpc_complex_backend<Digits10>& e) { mpc_pow(result.data(), b.data(), e.data(), GMP_RNDN); } template <unsigned Digits10> inline void eval_exp(mpc_complex_backend<Digits10>& result, const mpc_complex_backend<Digits10>& arg) { mpc_exp(result.data(), arg.data(), GMP_RNDN); } template <unsigned Digits10> inline void eval_log(mpc_complex_backend<Digits10>& result, const mpc_complex_backend<Digits10>& arg) { mpc_log(result.data(), arg.data(), GMP_RNDN); } template <unsigned Digits10> inline void eval_log10(mpc_complex_backend<Digits10>& result, const mpc_complex_backend<Digits10>& arg) { mpc_log10(result.data(), arg.data(), GMP_RNDN); } template <unsigned Digits10> inline void eval_sin(mpc_complex_backend<Digits10>& result, const mpc_complex_backend<Digits10>& arg) { mpc_sin(result.data(), arg.data(), GMP_RNDN); } template <unsigned Digits10> inline void eval_cos(mpc_complex_backend<Digits10>& result, const mpc_complex_backend<Digits10>& arg) { mpc_cos(result.data(), arg.data(), GMP_RNDN); } template <unsigned Digits10> inline void eval_tan(mpc_complex_backend<Digits10>& result, const mpc_complex_backend<Digits10>& arg) { mpc_tan(result.data(), arg.data(), GMP_RNDN); } template <unsigned Digits10> inline void eval_asin(mpc_complex_backend<Digits10>& result, const mpc_complex_backend<Digits10>& arg) { mpc_asin(result.data(), arg.data(), GMP_RNDN); } template <unsigned Digits10> inline void eval_acos(mpc_complex_backend<Digits10>& result, const mpc_complex_backend<Digits10>& arg) { mpc_acos(result.data(), arg.data(), GMP_RNDN); } template <unsigned Digits10> inline void eval_atan(mpc_complex_backend<Digits10>& result, const mpc_complex_backend<Digits10>& arg) { mpc_atan(result.data(), arg.data(), GMP_RNDN); } template <unsigned Digits10> inline void eval_sinh(mpc_complex_backend<Digits10>& result, const mpc_complex_backend<Digits10>& arg) { mpc_sinh(result.data(), arg.data(), GMP_RNDN); } template <unsigned Digits10> inline void eval_cosh(mpc_complex_backend<Digits10>& result, const mpc_complex_backend<Digits10>& arg) { mpc_cosh(result.data(), arg.data(), GMP_RNDN); } template <unsigned Digits10> inline void eval_tanh(mpc_complex_backend<Digits10>& result, const mpc_complex_backend<Digits10>& arg) { mpc_tanh(result.data(), arg.data(), GMP_RNDN); } template <unsigned Digits10> inline void eval_asinh(mpc_complex_backend<Digits10>& result, const mpc_complex_backend<Digits10>& arg) { mpc_asinh(result.data(), arg.data(), GMP_RNDN); } template <unsigned Digits10> inline void eval_acosh(mpc_complex_backend<Digits10>& result, const mpc_complex_backend<Digits10>& arg) { mpc_acosh(result.data(), arg.data(), GMP_RNDN); } template <unsigned Digits10> inline void eval_atanh(mpc_complex_backend<Digits10>& result, const mpc_complex_backend<Digits10>& arg) { mpc_atanh(result.data(), arg.data(), GMP_RNDN); } template <unsigned Digits10> inline void eval_conj(mpc_complex_backend<Digits10>& result, const mpc_complex_backend<Digits10>& arg) { mpc_conj(result.data(), arg.data(), GMP_RNDN); } template <unsigned Digits10> inline void eval_proj(mpc_complex_backend<Digits10>& result, const mpc_complex_backend<Digits10>& arg) { mpc_proj(result.data(), arg.data(), GMP_RNDN); } template <unsigned Digits10> inline void eval_real(mpfr_float_backend<Digits10>& result, const mpc_complex_backend<Digits10>& arg) { mpfr_set_prec(result.data(), mpfr_get_prec(mpc_realref(arg.data()))); mpfr_set(result.data(), mpc_realref(arg.data()), GMP_RNDN); } template <unsigned Digits10> inline void eval_imag(mpfr_float_backend<Digits10>& result, const mpc_complex_backend<Digits10>& arg) { mpfr_set_prec(result.data(), mpfr_get_prec(mpc_imagref(arg.data()))); mpfr_set(result.data(), mpc_imagref(arg.data()), GMP_RNDN); } template <unsigned Digits10> inline void eval_set_imag(mpc_complex_backend<Digits10>& result, const mpfr_float_backend<Digits10>& arg) { mpfr_set(mpc_imagref(result.data()), arg.data(), GMP_RNDN); } template <unsigned Digits10> inline void eval_set_real(mpc_complex_backend<Digits10>& result, const mpfr_float_backend<Digits10>& arg) { mpfr_set(mpc_realref(result.data()), arg.data(), GMP_RNDN); } template <unsigned Digits10> inline void eval_set_real(mpc_complex_backend<Digits10>& result, const gmp_int& arg) { mpfr_set_z(mpc_realref(result.data()), arg.data(), GMP_RNDN); } template <unsigned Digits10> inline void eval_set_real(mpc_complex_backend<Digits10>& result, const gmp_rational& arg) { mpfr_set_q(mpc_realref(result.data()), arg.data(), GMP_RNDN); } template <unsigned Digits10> inline void eval_set_real(mpc_complex_backend<Digits10>& result, const unsigned& arg) { mpfr_set_ui(mpc_realref(result.data()), arg, GMP_RNDN); } template <unsigned Digits10> inline void eval_set_real(mpc_complex_backend<Digits10>& result, const unsigned long& arg) { mpfr_set_ui(mpc_realref(result.data()), arg, GMP_RNDN); } template <unsigned Digits10> inline void eval_set_real(mpc_complex_backend<Digits10>& result, const int& arg) { mpfr_set_si(mpc_realref(result.data()), arg, GMP_RNDN); } template <unsigned Digits10> inline void eval_set_real(mpc_complex_backend<Digits10>& result, const long& arg) { mpfr_set_si(mpc_realref(result.data()), arg, GMP_RNDN); } template <unsigned Digits10> inline void eval_set_real(mpc_complex_backend<Digits10>& result, const float& arg) { mpfr_set_flt(mpc_realref(result.data()), arg, GMP_RNDN); } template <unsigned Digits10> inline void eval_set_real(mpc_complex_backend<Digits10>& result, const double& arg) { mpfr_set_d(mpc_realref(result.data()), arg, GMP_RNDN); } template <unsigned Digits10> inline void eval_set_real(mpc_complex_backend<Digits10>& result, const long double& arg) { mpfr_set_ld(mpc_realref(result.data()), arg, GMP_RNDN); } #if defined(BOOST_HAS_LONG_LONG) && defined(_MPFR_H_HAVE_INTMAX_T) template <unsigned Digits10> inline void eval_set_real(mpc_complex_backend<Digits10>& result, const unsigned long long& arg) { mpfr_set_uj(mpc_realref(result.data()), arg, GMP_RNDN); } template <unsigned Digits10> inline void eval_set_real(mpc_complex_backend<Digits10>& result, const long long& arg) { mpfr_set_sj(mpc_realref(result.data()), arg, GMP_RNDN); } #endif template <unsigned Digits10> inline void eval_set_imag(mpc_complex_backend<Digits10>& result, const gmp_int& arg) { mpfr_set_z(mpc_imagref(result.data()), arg.data(), GMP_RNDN); } template <unsigned Digits10> inline void eval_set_imag(mpc_complex_backend<Digits10>& result, const gmp_rational& arg) { mpfr_set_q(mpc_imagref(result.data()), arg.data(), GMP_RNDN); } template <unsigned Digits10> inline void eval_set_imag(mpc_complex_backend<Digits10>& result, const unsigned& arg) { mpfr_set_ui(mpc_imagref(result.data()), arg, GMP_RNDN); } template <unsigned Digits10> inline void eval_set_imag(mpc_complex_backend<Digits10>& result, const unsigned long& arg) { mpfr_set_ui(mpc_imagref(result.data()), arg, GMP_RNDN); } template <unsigned Digits10> inline void eval_set_imag(mpc_complex_backend<Digits10>& result, const int& arg) { mpfr_set_si(mpc_imagref(result.data()), arg, GMP_RNDN); } template <unsigned Digits10> inline void eval_set_imag(mpc_complex_backend<Digits10>& result, const long& arg) { mpfr_set_si(mpc_imagref(result.data()), arg, GMP_RNDN); } template <unsigned Digits10> inline void eval_set_imag(mpc_complex_backend<Digits10>& result, const float& arg) { mpfr_set_flt(mpc_imagref(result.data()), arg, GMP_RNDN); } template <unsigned Digits10> inline void eval_set_imag(mpc_complex_backend<Digits10>& result, const double& arg) { mpfr_set_d(mpc_imagref(result.data()), arg, GMP_RNDN); } template <unsigned Digits10> inline void eval_set_imag(mpc_complex_backend<Digits10>& result, const long double& arg) { mpfr_set_ld(mpc_imagref(result.data()), arg, GMP_RNDN); } #if defined(BOOST_HAS_LONG_LONG) && defined(_MPFR_H_HAVE_INTMAX_T) template <unsigned Digits10> inline void eval_set_imag(mpc_complex_backend<Digits10>& result, const unsigned long long& arg) { mpfr_set_uj(mpc_imagref(result.data()), arg, GMP_RNDN); } template <unsigned Digits10> inline void eval_set_imag(mpc_complex_backend<Digits10>& result, const long long& arg) { mpfr_set_sj(mpc_imagref(result.data()), arg, GMP_RNDN); } #endif template <unsigned Digits10> inline std::size_t hash_value(const mpc_complex_backend<Digits10>& val) { std::size_t result = 0; std::size_t len = val.data()[0].re[0]._mpfr_prec / mp_bits_per_limb; if (val.data()[0].re[0]._mpfr_prec % mp_bits_per_limb) ++len; for (std::size_t i = 0; i < len; ++i) boost::hash_combine(result, val.data()[0].re[0]._mpfr_d[i]); boost::hash_combine(result, val.data()[0].re[0]._mpfr_exp); boost::hash_combine(result, val.data()[0].re[0]._mpfr_sign); len = val.data()[0].im[0]._mpfr_prec / mp_bits_per_limb; if (val.data()[0].im[0]._mpfr_prec % mp_bits_per_limb) ++len; for (std::size_t i = 0; i < len; ++i) boost::hash_combine(result, val.data()[0].im[0]._mpfr_d[i]); boost::hash_combine(result, val.data()[0].im[0]._mpfr_exp); boost::hash_combine(result, val.data()[0].im[0]._mpfr_sign); return result; } } // namespace backends #ifdef BOOST_NO_SFINAE_EXPR namespace detail { template <unsigned D1, unsigned D2> struct is_explicitly_convertible<backends::mpc_complex_backend<D1>, backends::mpc_complex_backend<D2> > : public mpl::true_ {}; } // namespace detail #endif namespace detail { template <> struct is_variable_precision<backends::mpc_complex_backend<0> > : public true_type {}; } // namespace detail template <> struct number_category<detail::canonical<mpc_t, backends::mpc_complex_backend<0> >::type> : public mpl::int_<number_kind_floating_point> {}; using boost::multiprecision::backends::mpc_complex_backend; typedef number<mpc_complex_backend<50> > mpc_complex_50; typedef number<mpc_complex_backend<100> > mpc_complex_100; typedef number<mpc_complex_backend<500> > mpc_complex_500; typedef number<mpc_complex_backend<1000> > mpc_complex_1000; typedef number<mpc_complex_backend<0> > mpc_complex; template <unsigned Digits10, expression_template_option ExpressionTemplates> struct component_type<number<mpc_complex_backend<Digits10>, ExpressionTemplates> > { typedef number<mpfr_float_backend<Digits10>, ExpressionTemplates> type; }; template <unsigned Digits10, expression_template_option ExpressionTemplates> struct component_type<number<logged_adaptor<mpc_complex_backend<Digits10> >, ExpressionTemplates> > { typedef number<mpfr_float_backend<Digits10>, ExpressionTemplates> type; }; template <unsigned Digits10, expression_template_option ExpressionTemplates> struct complex_result_from_scalar<number<mpfr_float_backend<Digits10>, ExpressionTemplates> > { typedef number<mpc_complex_backend<Digits10>, ExpressionTemplates> type; }; } } // namespace boost::multiprecision #endif
[ "yanhua133@126.com" ]
yanhua133@126.com