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
986 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
145 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
122 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
c135d628cdb7ecd56b8cefe41ef656aefdb3f2ac
f9f8bd992dac718043a5e8c12deed3dd190c21d0
/Dynamic-Programming/Staircase (Dynamic Programming).cpp
0fe074f2af1bf04f75f6ea65e25f7cffd5ef2dc3
[]
no_license
sankalp163/CPP-codes
e51e920ac296aa3481edaa56566c9e63913550c7
1cc1a75311262b19fcab8086c58f7c68871100b8
refs/heads/main
2023-06-14T18:19:55.967344
2021-07-12T06:45:10
2021-07-12T06:45:10
338,971,480
1
0
null
null
null
null
UTF-8
C++
false
false
242
cpp
long staircase(int n) { //Write your code here long ans[n+1]; ans[0]=1; ans[1]=1; ans[2]=2; for(int i=3;i<=n;i++){ ans[i]=ans[i-1]+ans[i-2]+ans[i-3]; } return ans[n]; }
[ "noreply@github.com" ]
sankalp163.noreply@github.com
3103c67aa8c2614ff8627c0a6e39f6bf48b74896
70971245fb7c522dfa06e4f632b86ff2b8499528
/Source/Core/World/World.cpp
0990fe324ccead11edd4484c1556eea75e6f272d
[ "MIT" ]
permissive
Cube219/CubeEngine
f0f5afdf19ab908490f2b9981fe7baaabb1dd7c4
b54a7373be96333aa38fdf49ea32272c28c42a4b
refs/heads/master
2021-06-08T12:38:13.206138
2021-03-28T06:23:20
2021-03-28T06:23:20
102,942,324
2
0
null
null
null
null
UTF-8
C++
false
false
1,290
cpp
#include "World.h" #include "../Assertion.h" namespace cube { void World::Initialize() { } void World::Shutdown() { mWorldObjectTable.ReleaseAll(); mWorldObjects.clear(); } void World::Update(float dt) { } HWorldObject World::RegisterWorldObject(UPtr<WorldObject>&& wo) { CHECK(wo->GetID() == Uint64InvalidValue, "Failed to register GameObject. It is already registered. (id: {})", wo->GetID()); wo->mEntity = mRegistry.create(); mRegistry.emplace<Transform>(wo->mEntity, Vector3::Zero(), Vector3::Zero(), Vector3(1.0f, 1.0f, 1.0f)); mWorldObjects.push_back(std::move(wo)); HWorldObject hwo = mWorldObjectTable.CreateNewHandler(mWorldObjects.back().get()); return hwo; } void World::UnregisterWorldObject(HWorldObject& wo) { mRegistry.destroy(wo->mEntity); WorldObject* pWo = mWorldObjectTable.ReleaseHandler(wo); auto findIter = std::find_if(mWorldObjects.cbegin(), mWorldObjects.cend(), [pWo](auto& element) { return element.get() == pWo; }); CHECK(findIter != mWorldObjects.cend(), "Cannot unregister WorldObject. It is not registered."); mWorldObjects.erase(findIter); } } // namespace cube
[ "max804800@gmail.com" ]
max804800@gmail.com
2db6139b17c565f378bf89f8c625046ea2ab0ad2
753a57645d0824a750fa07176bdf7e37369940f6
/Engine/Plugins/UnrealCS/Source/MonoPlugin/Private/GeneratedScriptLibraries/LightmassPrimitiveSettingsObject.script.h
aa3dfbbe734c6832f9fd395a4e2484542f48f538
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
marynate/UnrealCS
5782c4dd1b3fe6e136dcee54ce430aabd97b70a4
de43f7e42ca037445202d59c8114fafc30e031ec
refs/heads/master
2021-01-19T13:01:35.048880
2017-02-22T02:18:33
2017-02-22T02:18:33
82,354,770
2
1
null
2017-02-18T02:17:07
2017-02-18T02:17:06
null
UTF-8
C++
false
false
351
h
#pragma once namespace UnrealEngine { class _ULightmassPrimitiveSettingsObject { static UClass* StaticClass(){return ULightmassPrimitiveSettingsObject::StaticClass();} public: static void BindFunctions() { mono_add_internal_call("UnrealEngine.ULightmassPrimitiveSettingsObject::StaticClass",(const void*)StaticClass); } } ; }
[ "xg_55@126.com" ]
xg_55@126.com
b9ca5b9fc60d6f560cde434383d7640aaa5e9120
7d39413b4d6e99369519db7772f010dce95e79ed
/cpp/test/shared_from_this_test.h
14a55d55447071233fe80aad7ccde4ba0a5afd05
[]
no_license
wangjiaming0909/al
62a890cae0c1b753eccf14eec770adfb71fa8957
2b40372edfc9dcde1a379e97175f006c3c53f557
refs/heads/master
2023-04-20T22:45:11.799670
2023-04-15T09:52:44
2023-04-15T09:52:44
145,864,078
0
0
null
2022-12-08T01:36:19
2018-08-23T14:20:01
HTML
UTF-8
C++
false
false
1,102
h
#pragma once #include <boost\enable_shared_from_this.hpp> #include <string> using namespace boost; class class_without_default_constructor { public: class_without_default_constructor(int a) : a_(a){} private: int a_; }; class share_from_me : public enable_shared_from_this<share_from_me>{ public: friend std::ostream& operator<<(std::ostream& os, const share_from_me& me) { os << me.a_; return os; } share_from_me(int a) : a_(a), c_(a){} shared_ptr<share_from_me> f() { return this->shared_from_this(); } private: int a_; std::string str_; class_without_default_constructor c_; }; class parent { public: parent() { std::cout << "parent" << std::endl; } ~parent() { std::cout << "~parent" << std::endl; } }; std::ostream& operator<<(std::ostream& os, const parent& p) { os << "parent"; return os; } class son : public parent { public: son() { std::cout << "son" << std::endl; } ~son() { std::cout << "~son" << std::endl; } friend std::ostream& operator<<(std::ostream& os, const son& s) { os << "son"; return os; } };
[ "JWang284@slb.com" ]
JWang284@slb.com
9c938ff603321364a192d999d6d9762414a40ecd
09f3df9b4ae970025b8a422635d70287db91493b
/src/cpp/conv3x3.cpp
95ea57901c629ef350ff30cbb8aeae80ddc9af53
[ "BSD-2-Clause" ]
permissive
ikwzm/QCONV-STRIP-Ultra96
3390f07a41e91fe2d4c5552964748770c4ec2b51
38c7ae9af9de9b8d0bfdd0bee8fc49784bd4aa11
refs/heads/master
2021-07-12T21:13:31.441444
2020-08-21T00:52:38
2020-08-21T00:52:38
188,438,599
3
2
null
null
null
null
UTF-8
C++
false
false
5,819
cpp
/* Copyright 2018 The Blueoil Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <iostream> #include "common/global.h" #include "cpp/utils.h" namespace cpp { namespace p = conv_common_params; void conv3x3_impl(T_in in_data[], T_out out_data[], T_k k_data[], T_out threshold_data[], unsigned in_w, unsigned in_h, unsigned in_c, unsigned out_w, unsigned out_h, unsigned out_c, unsigned pad, unsigned stride) { unsigned k_c = in_c; unsigned k_w = 3; unsigned k_h = 3; unsigned k_n = out_c; unsigned k_size = k_h * k_w * k_c; T_k* k_local = new T_k[k_size * k_n]; T_out threshold_local[out_c][p::num_thresholds]; unsigned idx_k = 0; unsigned idx_t = 0; for (unsigned kn = 0; kn < k_n; kn++) { for (unsigned k = 0; k < k_size; k++) { k_local[k * k_n + kn] = k_data[idx_k++]; } } if (threshold_data != NULL) { for (unsigned oc = 0; oc < out_c; oc++) { for (unsigned i = 0; i < p::num_thresholds; i++) { threshold_local[oc][i] = threshold_data[idx_t++]; } } } unsigned idx_out = 0; for (unsigned oh = 0; oh < out_h; ++oh) for (unsigned ow = 0; ow < out_w; ++ow) { T_out out[k_n] = {}; unsigned idx_k_local = 0; for (unsigned kh = 0; kh < k_h; kh++) { for (unsigned kw = 0; kw < k_w; kw++) { int ih = (oh * stride) - pad + kh; int iw = (ow * stride) - pad + kw; bool valid = (iw >= 0) && (iw < int(in_w)) && (ih >= 0) && (ih < int(in_h)); for (unsigned kc = 0; kc < in_c; kc++) { if (valid) { int idx_in = ih * in_w * in_c + iw * in_c + kc; T_in in_buf = in_data[idx_in]; for (int kn = 0; kn < k_n; kn++) { T_k k_buf = k_local[idx_k_local * k_n + kn]; out[kn] += in_buf * k_buf; } } idx_k_local++; } } } for (int oc = 0; oc < out_c; oc++) { T_out conv_result = out[oc]; T_out out_buf; if (threshold_data != NULL) { T_out ts0 = threshold_local[oc][0]; T_out ts1 = threshold_local[oc][1]; T_out ts2 = threshold_local[oc][2]; T_out flag = threshold_local[oc][3]; if (flag == 1) // increasing function { if (conv_result < ts0) out_buf = 0; else if (conv_result < ts1) out_buf = 1; else if (conv_result < ts2) out_buf = 2; else out_buf = 3; } else if (flag == -1) // decreasing function { if (conv_result > ts2) out_buf = 0; else if (conv_result > ts1) out_buf = 1; else if (conv_result > ts0) out_buf = 2; else out_buf = 3; } else { // max value of 2 bits out_buf = flag - 2; // note: 2 is a magic number! } } else { out_buf = conv_result; } out_data[idx_out++] = out_buf; } } // for LOOP_CONV_INPUT delete[] k_local; } void qconv3x3_impl(T_q in_data[], T_out out_data[], T_q k_data[], T_out threshold_data, unsigned in_w, unsigned in_h, unsigned in_c_by_word, unsigned out_w, unsigned out_h, unsigned out_c, unsigned pad, unsigned stride) { unsigned idx_k = 0; unsigned k_w = 3; unsigned k_h = 3; unsigned k_n = out_c; unsigned k_c_by_word = in_c_by_word; unsigned k_size_packed = k_h * k_w * k_c_by_word * conv_common_params::nbits_k_data; for (int oc_out = 0; oc_out < out_c; oc_out += p::num_pe) { T_q* k_local = new T_q[k_size_packed * p::num_pe]; for (unsigned kn = 0; kn < p::num_pe; ++kn) { for (unsigned k = 0; k < k_size_packed; ++k) { k_local[k * p::num_pe + kn] = k_data[idx_k++]; } } unsigned idx_out = oc_out; for (unsigned oh = 0; oh < out_h; ++oh) for (unsigned ow = 0; ow < out_w; ++ow) { T_out out[p::num_pe] = {}; unsigned idx_k_local = 0; for (unsigned kh = 0; kh < k_h; ++kh) for (unsigned kw = 0; kw < k_w; ++kw) for (unsigned ic = 0; ic < in_c_by_word; ++ic) { int ih = (oh * stride) - pad + kh; int iw = (ow * stride) - pad + kw; bool valid = (iw >= 0) && (iw < int(in_w)) && (ih >= 0) && (ih < int(in_h)); if (valid) { int idx_in = (ih * in_w * in_c_by_word + iw * in_c_by_word + ic) * p::nbits_in_data; T_q in_buf0 = in_data[idx_in]; T_q in_buf1 = in_data[idx_in + 1]; for (int kn = 0; kn < p::num_pe; kn++) { T_q k_buf = k_local[idx_k_local * p::num_pe + kn]; out[kn] += PE(k_buf, in_buf0, in_buf1); } } idx_k_local++; // should be executed, even while no corresponding input } for (int kn = 0; kn < p::num_pe; kn++) { out_data[idx_out + kn] = out[kn]; } idx_out += out_c; } // for LOOP_CONV_INPUT delete[] k_local; } } } // namespace cpp
[ "ichiro_k@ca2.so-net.ne.jp" ]
ichiro_k@ca2.so-net.ne.jp
b84ac7f60d6f47b91b7df1774289a0a4273dd452
3b4f1dbc4c178bccc58a10fdb6eff650b3406aa6
/Game/Money.cpp
349fbe926ec43631209ae512339a4d0c5f2d31a9
[]
no_license
LuongKimPhuong2611/supermario-master
b0c51096611700e7728e781d21c74528ca156091
ed182738d36a178f8ecb067ccd0ed5c1893173f0
refs/heads/master
2023-02-02T18:52:11.905121
2020-12-18T00:36:20
2020-12-18T00:36:20
322,201,046
0
0
null
null
null
null
UTF-8
C++
false
false
2,418
cpp
#include "Money.h" #include "Brick.h" Money::Money(float posX, float posY) { x = posX; y = posY; oldY = y; tag = EntityType::MONEY; SetState(0); //SetState(MUSHROOM_STATE_WALKING); timeDelay = 0; isDone = false; isOnTop = false; } void Money::GetBoundingBox(float& left, float& top, float& right, float& bottom) { if (!isOnTop) { left = x-3; top = y + 3; right = left + 7; bottom = top + 14; } else { if (!isDone) { left = x; top = y; right = x + MONEY_BBOX_WIDTH; bottom = y + MONEY_BBOX_HEIGHT; } else { left = x; top = y; right = x; bottom = y; } } } void Money::Update(DWORD dt, vector<LPGAMEENTITY>* coObjects) { if (isDone) return; Entity::Update(dt, coObjects); /*if (isOnTop) { vy += 0.002 * dt; if (vx == 0) vx = -MONEY_WALKING_SPEED; }*/ if (isCollis == true && isStart == false) { timeDelay += dt; if (timeDelay >= 100) { alpha = 255; vy = -0.18; if (oldY - 50 >= y) { isOnTop = true; isCollis = false; isStart = true; oldY = y; } } } else if (isOnTop) { vy = 0.15; if (abs(y - oldY) > 20) isDone = true; } vector<LPCOLLISIONEVENT> coEvents; vector<LPCOLLISIONEVENT> coEventsResult; coEvents.clear(); CalcPotentialCollisions(coObjects, coEvents); // No collision occured, proceed normally if (coEvents.size() == 0) { x += dx; y += dy; } else { float min_tx, min_ty, nx = 0, ny; float rdx = 0; float rdy = 0; // TODO: This is a very ugly designed function!!!! FilterCollision(coEvents, coEventsResult, min_tx, min_ty, nx, ny, rdx, rdy); for (UINT i = 0; i < coEventsResult.size(); i++) { LPCOLLISIONEVENT e = coEventsResult[i]; if (e->obj->GetType() == EntityType::CBRICK || e->obj->GetType() == EntityType::BRICK) { x += min_tx * dx + nx * 0.4f; y += min_ty * dy + ny * 0.4f; //if (nx != 0) vx = 0; if (e->ny != 0) vy = 0; if (e->nx != 0) vx = -1 * vx; } } } for (UINT i = 0; i < coEvents.size(); i++) delete coEvents[i]; } void Money::Render() { if (isDone) return; int ani = MONEY_ANI_WALKING; animationSet->at(ani)->Render(nx, x, y, alpha); RenderBoundingBox(); } void Money::SetState(int state) { Entity::SetState(state); switch (state) { case MONEY_STATE_WALKING: //y -= 2; isCollis = true; break; case 0: alpha = 0; vx = 0; vy = 0; isCollis = false; break; } }
[ "18521275@gm.uit.edu.vn" ]
18521275@gm.uit.edu.vn
e89208ef5990482965546656c6a36173c60227c2
78918391a7809832dc486f68b90455c72e95cdda
/boost_lib/boost/graph/vf2_sub_graph_iso.hpp
2eff106db658c3613347f288262a88f0efa820cc
[ "MIT" ]
permissive
kyx0r/FA_Patcher
50681e3e8bb04745bba44a71b5fd04e1004c3845
3f539686955249004b4483001a9e49e63c4856ff
refs/heads/master
2022-03-28T10:03:28.419352
2020-01-02T09:16:30
2020-01-02T09:16:30
141,066,396
2
0
null
null
null
null
UTF-8
C++
false
false
42,775
hpp
//======================================================================= // Copyright (C) 2012 Flavio De Lorenzi (fdlorenzi@gmail.com) // Copyright (C) 2013 Jakob Lykke Andersen, University of Southern Denmark (jlandersen@imada.sdu.dk) // // The algorithm implemented here is derived from original ideas by // Pasquale Foggia and colaborators. For further information see // e.g. Cordella et al. 2001, 2004. // // 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) //======================================================================= // Revision History: // 8 April 2013: Fixed a typo in vf2_print_callback. (Flavio De Lorenzi) #ifndef BOOST_VF2_SUB_GRAPH_ISO_HPP #define BOOST_VF2_SUB_GRAPH_ISO_HPP #include <iostream> #include <iomanip> #include <iterator> #include <vector> #include <utility> #include <boost/assert.hpp> #include <boost/concept/assert.hpp> #include <boost/concept_check.hpp> #include <boost/graph/graph_utility.hpp> #include <boost/graph/graph_traits.hpp> #include <boost/graph/mcgregor_common_subgraphs.hpp> // for always_equivalent #include <boost/graph/named_function_params.hpp> #include <boost/type_traits/has_less.hpp> #include <boost/mpl/int.hpp> #include <boost/range/algorithm/sort.hpp> #include <boost/tuple/tuple.hpp> #include <boost/utility/enable_if.hpp> #ifndef BOOST_GRAPH_ITERATION_MACROS_HPP #define BOOST_ISO_INCLUDED_ITER_MACROS // local macro, see bottom of file #include <boost/graph/iteration_macros.hpp> #endif namespace boost { // Default print_callback template <typename Graph1, typename Graph2> struct vf2_print_callback { vf2_print_callback(const Graph1& graph1, const Graph2& graph2) : graph1_(graph1), graph2_(graph2) {} template <typename CorrespondenceMap1To2, typename CorrespondenceMap2To1> bool operator()(CorrespondenceMap1To2 f, CorrespondenceMap2To1) const { // Print (sub)graph isomorphism map BGL_FORALL_VERTICES_T(v, graph1_, Graph1) std::cout << '(' << get(vertex_index_t(), graph1_, v) << ", " << get(vertex_index_t(), graph2_, get(f, v)) << ") "; std::cout << std::endl; return true; } private: const Graph1& graph1_; const Graph2& graph2_; }; namespace detail { // State associated with a single graph (graph_this) template<typename GraphThis, typename GraphOther, typename IndexMapThis, typename IndexMapOther> class base_state { typedef typename graph_traits<GraphThis>::vertex_descriptor vertex_this_type; typedef typename graph_traits<GraphOther>::vertex_descriptor vertex_other_type; typedef typename graph_traits<GraphThis>::vertices_size_type size_type; const GraphThis& graph_this_; const GraphOther& graph_other_; IndexMapThis index_map_this_; IndexMapOther index_map_other_; std::vector<vertex_other_type> core_vec_; typedef iterator_property_map<typename std::vector<vertex_other_type>::iterator, IndexMapThis, vertex_other_type, vertex_other_type&> core_map_type; core_map_type core_; std::vector<size_type> in_vec_, out_vec_; typedef iterator_property_map<typename std::vector<size_type>::iterator, IndexMapThis, size_type, size_type&> in_out_map_type; in_out_map_type in_, out_; size_type term_in_count_, term_out_count_, term_both_count_, core_count_; // Forbidden base_state(const base_state&); base_state& operator=(const base_state&); public: base_state(const GraphThis& graph_this, const GraphOther& graph_other, IndexMapThis index_map_this, IndexMapOther index_map_other) : graph_this_(graph_this), graph_other_(graph_other), index_map_this_(index_map_this), index_map_other_(index_map_other), core_vec_(num_vertices(graph_this_), graph_traits<GraphOther>::null_vertex()), core_(core_vec_.begin(), index_map_this_), in_vec_(num_vertices(graph_this_), 0), out_vec_(num_vertices(graph_this_), 0), in_(in_vec_.begin(), index_map_this_), out_(out_vec_.begin(), index_map_this_), term_in_count_(0), term_out_count_(0), term_both_count_(0), core_count_(0) { } // Adds a vertex pair to the state of graph graph_this void push(const vertex_this_type& v_this, const vertex_other_type& v_other) { ++core_count_; put(core_, v_this, v_other); if (!get(in_, v_this)) { put(in_, v_this, core_count_); ++term_in_count_; if (get(out_, v_this)) ++term_both_count_; } if (!get(out_, v_this)) { put(out_, v_this, core_count_); ++term_out_count_; if (get(in_, v_this)) ++term_both_count_; } BGL_FORALL_INEDGES_T(v_this, e, graph_this_, GraphThis) { vertex_this_type w = source(e, graph_this_); if (!get(in_, w)) { put(in_, w, core_count_); ++term_in_count_; if (get(out_, w)) ++term_both_count_; } } BGL_FORALL_OUTEDGES_T(v_this, e, graph_this_, GraphThis) { vertex_this_type w = target(e, graph_this_); if (!get(out_, w)) { put(out_, w, core_count_); ++term_out_count_; if (get(in_, w)) ++term_both_count_; } } } // Removes vertex pair from state of graph_this void pop(const vertex_this_type& v_this, const vertex_other_type&) { if (!core_count_) return; if (get(in_, v_this) == core_count_) { put(in_, v_this, 0); --term_in_count_; if (get(out_, v_this)) --term_both_count_; } BGL_FORALL_INEDGES_T(v_this, e, graph_this_, GraphThis) { vertex_this_type w = source(e, graph_this_); if (get(in_, w) == core_count_) { put(in_, w, 0); --term_in_count_; if (get(out_, w)) --term_both_count_; } } if (get(out_, v_this) == core_count_) { put(out_, v_this, 0); --term_out_count_; if (get(in_, v_this)) --term_both_count_; } BGL_FORALL_OUTEDGES_T(v_this, e, graph_this_, GraphThis) { vertex_this_type w = target(e, graph_this_); if (get(out_, w) == core_count_) { put(out_, w, 0); --term_out_count_; if (get(in_, w)) --term_both_count_; } } put(core_, v_this, graph_traits<GraphOther>::null_vertex()); --core_count_; } // Returns true if the in-terminal set is not empty bool term_in() const { return core_count_ < term_in_count_ ; } // Returns true if vertex belongs to the in-terminal set bool term_in(const vertex_this_type& v) const { return (get(in_, v) > 0) && (get(core_, v) == graph_traits<GraphOther>::null_vertex()); } // Returns true if the out-terminal set is not empty bool term_out() const { return core_count_ < term_out_count_; } // Returns true if vertex belongs to the out-terminal set bool term_out(const vertex_this_type& v) const { return (get(out_, v) > 0) && (get(core_, v) == graph_traits<GraphOther>::null_vertex()); } // Returns true of both (in- and out-terminal) sets are not empty bool term_both() const { return core_count_ < term_both_count_; } // Returns true if vertex belongs to both (in- and out-terminal) sets bool term_both(const vertex_this_type& v) const { return (get(in_, v) > 0) && (get(out_, v) > 0) && (get(core_, v) == graph_traits<GraphOther>::null_vertex()); } // Returns true if vertex belongs to the core map, i.e. it is in the // present mapping bool in_core(const vertex_this_type& v) const { return get(core_, v) != graph_traits<GraphOther>::null_vertex(); } // Returns the number of vertices in the mapping size_type count() const { return core_count_; } // Returns the image (in graph_other) of vertex v (in graph_this) vertex_other_type core(const vertex_this_type& v) const { return get(core_, v); } // Returns the mapping core_map_type get_map() const { return core_; } // Returns the "time" (or depth) when vertex was added to the in-terminal set size_type in_depth(const vertex_this_type& v) const { return get(in_, v); } // Returns the "time" (or depth) when vertex was added to the out-terminal set size_type out_depth(const vertex_this_type& v) const { return get(out_, v); } // Returns the terminal set counts boost::tuple<size_type, size_type, size_type> term_set() const { return boost::make_tuple(term_in_count_, term_out_count_, term_both_count_); } }; // Function object that checks whether a valid edge // exists. For multi-graphs matched edges are excluded template <typename Graph, typename Enable = void> struct equivalent_edge_exists { typedef typename boost::graph_traits<Graph>::edge_descriptor edge_type; BOOST_CONCEPT_ASSERT(( LessThanComparable<edge_type> )); template<typename EdgePredicate> bool operator()(typename graph_traits<Graph>::vertex_descriptor s, typename graph_traits<Graph>::vertex_descriptor t, EdgePredicate is_valid_edge, const Graph& g) { BGL_FORALL_OUTEDGES_T(s, e, g, Graph) { if ((target(e, g) == t) && is_valid_edge(e) && (matched_edges_.find(e) == matched_edges_.end())) { matched_edges_.insert(e); return true; } } return false; } private: std::set<edge_type> matched_edges_; }; template <typename Graph> struct equivalent_edge_exists<Graph, typename boost::disable_if<is_multigraph<Graph> >::type> { template<typename EdgePredicate> bool operator()(typename graph_traits<Graph>::vertex_descriptor s, typename graph_traits<Graph>::vertex_descriptor t, EdgePredicate is_valid_edge, const Graph& g) { typename graph_traits<Graph>::edge_descriptor e; bool found; boost::tie(e, found) = edge(s, t, g); if (!found) return false; else if (is_valid_edge(e)) return true; return false; } }; // Generates a predicate for edge e1 given a binary predicate and a // fixed edge e2 template <typename Graph1, typename Graph2, typename EdgeEquivalencePredicate> struct edge1_predicate { edge1_predicate(EdgeEquivalencePredicate edge_comp, typename graph_traits<Graph2>::edge_descriptor e2) : edge_comp_(edge_comp), e2_(e2) {} bool operator()(typename graph_traits<Graph1>::edge_descriptor e1) { return edge_comp_(e1, e2_); } EdgeEquivalencePredicate edge_comp_; typename graph_traits<Graph2>::edge_descriptor e2_; }; // Generates a predicate for edge e2 given given a binary predicate and a // fixed edge e1 template <typename Graph1, typename Graph2, typename EdgeEquivalencePredicate> struct edge2_predicate { edge2_predicate(EdgeEquivalencePredicate edge_comp, typename graph_traits<Graph1>::edge_descriptor e1) : edge_comp_(edge_comp), e1_(e1) {} bool operator()(typename graph_traits<Graph2>::edge_descriptor e2) { return edge_comp_(e1_, e2); } EdgeEquivalencePredicate edge_comp_; typename graph_traits<Graph1>::edge_descriptor e1_; }; enum problem_selector {subgraph_mono, subgraph_iso, isomorphism }; // The actual state associated with both graphs template<typename Graph1, typename Graph2, typename IndexMap1, typename IndexMap2, typename EdgeEquivalencePredicate, typename VertexEquivalencePredicate, typename SubGraphIsoMapCallback, problem_selector problem_selection> class state { typedef typename graph_traits<Graph1>::vertex_descriptor vertex1_type; typedef typename graph_traits<Graph2>::vertex_descriptor vertex2_type; typedef typename graph_traits<Graph1>::edge_descriptor edge1_type; typedef typename graph_traits<Graph2>::edge_descriptor edge2_type; typedef typename graph_traits<Graph1>::vertices_size_type graph1_size_type; typedef typename graph_traits<Graph2>::vertices_size_type graph2_size_type; const Graph1& graph1_; const Graph2& graph2_; IndexMap1 index_map1_; EdgeEquivalencePredicate edge_comp_; VertexEquivalencePredicate vertex_comp_; base_state<Graph1, Graph2, IndexMap1, IndexMap2> state1_; base_state<Graph2, Graph1, IndexMap2, IndexMap1> state2_; // Three helper functions used in Feasibility and Valid functions to test // terminal set counts when testing for: // - graph sub-graph monomorphism, or inline bool comp_term_sets(graph1_size_type a, graph2_size_type b, boost::mpl::int_<subgraph_mono>) const { return a <= b; } // - graph sub-graph isomorphism, or inline bool comp_term_sets(graph1_size_type a, graph2_size_type b, boost::mpl::int_<subgraph_iso>) const { return a <= b; } // - graph isomorphism inline bool comp_term_sets(graph1_size_type a, graph2_size_type b, boost::mpl::int_<isomorphism>) const { return a == b; } // Forbidden state(const state&); state& operator=(const state&); public: state(const Graph1& graph1, const Graph2& graph2, IndexMap1 index_map1, IndexMap2 index_map2, EdgeEquivalencePredicate edge_comp, VertexEquivalencePredicate vertex_comp) : graph1_(graph1), graph2_(graph2), index_map1_(index_map1), edge_comp_(edge_comp), vertex_comp_(vertex_comp), state1_(graph1, graph2, index_map1, index_map2), state2_(graph2, graph1, index_map2, index_map1) {} // Add vertex pair to the state void push(const vertex1_type& v, const vertex2_type& w) { state1_.push(v, w); state2_.push(w, v); } // Remove vertex pair from state void pop(const vertex1_type& v, const vertex2_type&) { vertex2_type w = state1_.core(v); state1_.pop(v, w); state2_.pop(w, v); } // Checks the feasibility of a new vertex pair bool feasible(const vertex1_type& v_new, const vertex2_type& w_new) { if (!vertex_comp_(v_new, w_new)) return false; // graph1 graph1_size_type term_in1_count = 0, term_out1_count = 0, rest1_count = 0; { equivalent_edge_exists<Graph2> edge2_exists; BGL_FORALL_INEDGES_T(v_new, e1, graph1_, Graph1) { vertex1_type v = source(e1, graph1_); if (state1_.in_core(v) || (v == v_new)) { vertex2_type w = w_new; if (v != v_new) w = state1_.core(v); if (!edge2_exists(w, w_new, edge2_predicate<Graph1, Graph2, EdgeEquivalencePredicate>(edge_comp_, e1), graph2_)) return false; } else { if (0 < state1_.in_depth(v)) ++term_in1_count; if (0 < state1_.out_depth(v)) ++term_out1_count; if ((state1_.in_depth(v) == 0) && (state1_.out_depth(v) == 0)) ++rest1_count; } } } { equivalent_edge_exists<Graph2> edge2_exists; BGL_FORALL_OUTEDGES_T(v_new, e1, graph1_, Graph1) { vertex1_type v = target(e1, graph1_); if (state1_.in_core(v) || (v == v_new)) { vertex2_type w = w_new; if (v != v_new) w = state1_.core(v); if (!edge2_exists(w_new, w, edge2_predicate<Graph1, Graph2, EdgeEquivalencePredicate>(edge_comp_, e1), graph2_)) return false; } else { if (0 < state1_.in_depth(v)) ++term_in1_count; if (0 < state1_.out_depth(v)) ++term_out1_count; if ((state1_.in_depth(v) == 0) && (state1_.out_depth(v) == 0)) ++rest1_count; } } } // graph2 graph2_size_type term_out2_count = 0, term_in2_count = 0, rest2_count = 0; { equivalent_edge_exists<Graph1> edge1_exists; BGL_FORALL_INEDGES_T(w_new, e2, graph2_, Graph2) { vertex2_type w = source(e2, graph2_); if (state2_.in_core(w) || (w == w_new)) { if (problem_selection != subgraph_mono) { vertex1_type v = v_new; if (w != w_new) v = state2_.core(w); if (!edge1_exists(v, v_new, edge1_predicate<Graph1, Graph2, EdgeEquivalencePredicate>(edge_comp_, e2), graph1_)) return false; } } else { if (0 < state2_.in_depth(w)) ++term_in2_count; if (0 < state2_.out_depth(w)) ++term_out2_count; if ((state2_.in_depth(w) == 0) && (state2_.out_depth(w) == 0)) ++rest2_count; } } } { equivalent_edge_exists<Graph1> edge1_exists; BGL_FORALL_OUTEDGES_T(w_new, e2, graph2_, Graph2) { vertex2_type w = target(e2, graph2_); if (state2_.in_core(w) || (w == w_new)) { if (problem_selection != subgraph_mono) { vertex1_type v = v_new; if (w != w_new) v = state2_.core(w); if (!edge1_exists(v_new, v, edge1_predicate<Graph1, Graph2, EdgeEquivalencePredicate>(edge_comp_, e2), graph1_)) return false; } } else { if (0 < state2_.in_depth(w)) ++term_in2_count; if (0 < state2_.out_depth(w)) ++term_out2_count; if ((state2_.in_depth(w) == 0) && (state2_.out_depth(w) == 0)) ++rest2_count; } } } if (problem_selection != subgraph_mono) // subgraph_iso and isomorphism { return comp_term_sets(term_in1_count, term_in2_count, boost::mpl::int_<problem_selection>()) && comp_term_sets(term_out1_count, term_out2_count, boost::mpl::int_<problem_selection>()) && comp_term_sets(rest1_count, rest2_count, boost::mpl::int_<problem_selection>()); } else // subgraph_mono { return comp_term_sets(term_in1_count, term_in2_count, boost::mpl::int_<problem_selection>()) && comp_term_sets(term_out1_count, term_out2_count, boost::mpl::int_<problem_selection>()) && comp_term_sets(term_in1_count + term_out1_count + rest1_count, term_in2_count + term_out2_count + rest2_count, boost::mpl::int_<problem_selection>()); } } // Returns true if vertex v in graph1 is a possible candidate to // be added to the current state bool possible_candidate1(const vertex1_type& v) const { if (state1_.term_both() && state2_.term_both()) return state1_.term_both(v); else if (state1_.term_out() && state2_.term_out()) return state1_.term_out(v); else if (state1_.term_in() && state2_.term_in()) return state1_.term_in(v); else return !state1_.in_core(v); } // Returns true if vertex w in graph2 is a possible candidate to // be added to the current state bool possible_candidate2(const vertex2_type& w) const { if (state1_.term_both() && state2_.term_both()) return state2_.term_both(w); else if (state1_.term_out() && state2_.term_out()) return state2_.term_out(w); else if (state1_.term_in() && state2_.term_in()) return state2_.term_in(w); else return !state2_.in_core(w); } // Returns true if a mapping was found bool success() const { return state1_.count() == num_vertices(graph1_); } // Returns true if a state is valid bool valid() const { boost::tuple<graph1_size_type, graph1_size_type, graph1_size_type> term1; boost::tuple<graph2_size_type, graph2_size_type, graph2_size_type> term2; term1 = state1_.term_set(); term2 = state2_.term_set(); return comp_term_sets(boost::get<0>(term1), boost::get<0>(term2), boost::mpl::int_<problem_selection>()) && comp_term_sets(boost::get<1>(term1), boost::get<1>(term2), boost::mpl::int_<problem_selection>()) && comp_term_sets(boost::get<2>(term1), boost::get<2>(term2), boost::mpl::int_<problem_selection>()); } // Calls the user_callback with a graph (sub)graph mapping bool call_back(SubGraphIsoMapCallback user_callback) const { return user_callback(state1_.get_map(), state2_.get_map()); } }; // Data structure to keep info used for back tracking during // matching process template<typename Graph1, typename Graph2, typename VertexOrder1> struct vf2_match_continuation { typename VertexOrder1::const_iterator graph1_verts_iter; typename graph_traits<Graph2>::vertex_iterator graph2_verts_iter; }; // Non-recursive method that explores state space using a depth-first // search strategy. At each depth possible pairs candidate are compute // and tested for feasibility to extend the mapping. If a complete // mapping is found, the mapping is output to user_callback in the form // of a correspondence map (graph1 to graph2). Returning false from the // user_callback will terminate the search. Function match will return // true if the entire search space was explored. template<typename Graph1, typename Graph2, typename IndexMap1, typename IndexMap2, typename VertexOrder1, typename EdgeEquivalencePredicate, typename VertexEquivalencePredicate, typename SubGraphIsoMapCallback, problem_selector problem_selection> bool match(const Graph1& graph1, const Graph2& graph2, SubGraphIsoMapCallback user_callback, const VertexOrder1& vertex_order1, state<Graph1, Graph2, IndexMap1, IndexMap2, EdgeEquivalencePredicate, VertexEquivalencePredicate, SubGraphIsoMapCallback, problem_selection>& s) { typename VertexOrder1::const_iterator graph1_verts_iter; typedef typename graph_traits<Graph2>::vertex_iterator vertex2_iterator_type; vertex2_iterator_type graph2_verts_iter, graph2_verts_iter_end; typedef vf2_match_continuation<Graph1, Graph2, VertexOrder1> match_continuation_type; std::vector<match_continuation_type> k; bool found_match = false; recur: if (s.success()) { if (!s.call_back(user_callback)) return true; found_match = true; goto back_track; } if (!s.valid()) goto back_track; graph1_verts_iter = vertex_order1.begin(); while (graph1_verts_iter != vertex_order1.end() && !s.possible_candidate1(*graph1_verts_iter)) { ++graph1_verts_iter; } boost::tie(graph2_verts_iter, graph2_verts_iter_end) = vertices(graph2); while (graph2_verts_iter != graph2_verts_iter_end) { if (s.possible_candidate2(*graph2_verts_iter)) { if (s.feasible(*graph1_verts_iter, *graph2_verts_iter)) { match_continuation_type kk; kk.graph1_verts_iter = graph1_verts_iter; kk.graph2_verts_iter = graph2_verts_iter; k.push_back(kk); s.push(*graph1_verts_iter, *graph2_verts_iter); goto recur; } } graph2_loop: ++graph2_verts_iter; } back_track: if (k.empty()) return found_match; const match_continuation_type kk = k.back(); graph1_verts_iter = kk.graph1_verts_iter; graph2_verts_iter = kk.graph2_verts_iter; k.pop_back(); s.pop(*graph1_verts_iter, *graph2_verts_iter); goto graph2_loop; } // Used to sort nodes by in/out degrees template<typename Graph> struct vertex_in_out_degree_cmp { typedef typename graph_traits<Graph>::vertex_descriptor vertex_type; vertex_in_out_degree_cmp(const Graph& graph) : graph_(graph) {} bool operator()(const vertex_type& v, const vertex_type& w) const { // lexicographical comparison return std::make_pair(in_degree(v, graph_), out_degree(v, graph_)) < std::make_pair(in_degree(w, graph_), out_degree(w, graph_)); } const Graph& graph_; }; // Used to sort nodes by multiplicity of in/out degrees template<typename Graph, typename FrequencyMap> struct vertex_frequency_degree_cmp { typedef typename graph_traits<Graph>::vertex_descriptor vertex_type; vertex_frequency_degree_cmp(const Graph& graph, FrequencyMap freq) : graph_(graph), freq_(freq) {} bool operator()(const vertex_type& v, const vertex_type& w) const { // lexicographical comparison return std::make_pair(freq_[v], in_degree(v, graph_)+out_degree(v, graph_)) < std::make_pair(freq_[w], in_degree(w, graph_)+out_degree(w, graph_)); } const Graph& graph_; FrequencyMap freq_; }; // Sorts vertices of a graph by multiplicity of in/out degrees template<typename Graph, typename IndexMap, typename VertexOrder> void sort_vertices(const Graph& graph, IndexMap index_map, VertexOrder& order) { typedef typename graph_traits<Graph>::vertices_size_type size_type; boost::range::sort(order, vertex_in_out_degree_cmp<Graph>(graph)); std::vector<size_type> freq_vec(num_vertices(graph), 0); typedef iterator_property_map<typename std::vector<size_type>::iterator, IndexMap, size_type, size_type&> frequency_map_type; frequency_map_type freq = make_iterator_property_map(freq_vec.begin(), index_map); typedef typename VertexOrder::iterator order_iterator; for (order_iterator order_iter = order.begin(); order_iter != order.end(); ) { size_type count = 0; for (order_iterator count_iter = order_iter; (count_iter != order.end()) && (in_degree(*order_iter, graph) == in_degree(*count_iter, graph)) && (out_degree(*order_iter, graph) == out_degree(*count_iter, graph)); ++count_iter) ++count; for (size_type i = 0; i < count; ++i) { freq[*order_iter] = count; ++order_iter; } } boost::range::sort(order, vertex_frequency_degree_cmp<Graph, frequency_map_type>(graph, freq)); } // Enumerates all graph sub-graph mono-/iso-morphism mappings between graphs // graph_small and graph_large. Continues until user_callback returns true or the // search space has been fully explored. template <problem_selector problem_selection, typename GraphSmall, typename GraphLarge, typename IndexMapSmall, typename IndexMapLarge, typename VertexOrderSmall, typename EdgeEquivalencePredicate, typename VertexEquivalencePredicate, typename SubGraphIsoMapCallback> bool vf2_subgraph_morphism(const GraphSmall& graph_small, const GraphLarge& graph_large, SubGraphIsoMapCallback user_callback, IndexMapSmall index_map_small, IndexMapLarge index_map_large, const VertexOrderSmall& vertex_order_small, EdgeEquivalencePredicate edge_comp, VertexEquivalencePredicate vertex_comp) { // Graph requirements BOOST_CONCEPT_ASSERT(( BidirectionalGraphConcept<GraphSmall> )); BOOST_CONCEPT_ASSERT(( VertexListGraphConcept<GraphSmall> )); BOOST_CONCEPT_ASSERT(( EdgeListGraphConcept<GraphSmall> )); BOOST_CONCEPT_ASSERT(( AdjacencyMatrixConcept<GraphSmall> )); BOOST_CONCEPT_ASSERT(( BidirectionalGraphConcept<GraphLarge> )); BOOST_CONCEPT_ASSERT(( VertexListGraphConcept<GraphLarge> )); BOOST_CONCEPT_ASSERT(( EdgeListGraphConcept<GraphLarge> )); BOOST_CONCEPT_ASSERT(( AdjacencyMatrixConcept<GraphLarge> )); typedef typename graph_traits<GraphSmall>::vertex_descriptor vertex_small_type; typedef typename graph_traits<GraphLarge>::vertex_descriptor vertex_large_type; typedef typename graph_traits<GraphSmall>::vertices_size_type size_type_small; typedef typename graph_traits<GraphLarge>::vertices_size_type size_type_large; // Property map requirements BOOST_CONCEPT_ASSERT(( ReadablePropertyMapConcept<IndexMapSmall, vertex_small_type> )); typedef typename property_traits<IndexMapSmall>::value_type IndexMapSmallValue; BOOST_STATIC_ASSERT(( is_convertible<IndexMapSmallValue, size_type_small>::value )); BOOST_CONCEPT_ASSERT(( ReadablePropertyMapConcept<IndexMapLarge, vertex_large_type> )); typedef typename property_traits<IndexMapLarge>::value_type IndexMapLargeValue; BOOST_STATIC_ASSERT(( is_convertible<IndexMapLargeValue, size_type_large>::value )); // Edge & vertex requirements typedef typename graph_traits<GraphSmall>::edge_descriptor edge_small_type; typedef typename graph_traits<GraphLarge>::edge_descriptor edge_large_type; BOOST_CONCEPT_ASSERT(( BinaryPredicateConcept<EdgeEquivalencePredicate, edge_small_type, edge_large_type> )); BOOST_CONCEPT_ASSERT(( BinaryPredicateConcept<VertexEquivalencePredicate, vertex_small_type, vertex_large_type> )); // Vertex order requirements BOOST_CONCEPT_ASSERT(( ContainerConcept<VertexOrderSmall> )); typedef typename VertexOrderSmall::value_type order_value_type; BOOST_STATIC_ASSERT(( is_same<vertex_small_type, order_value_type>::value )); BOOST_ASSERT( num_vertices(graph_small) == vertex_order_small.size() ); if (num_vertices(graph_small) > num_vertices(graph_large)) return false; typename graph_traits<GraphSmall>::edges_size_type num_edges_small = num_edges(graph_small); typename graph_traits<GraphLarge>::edges_size_type num_edges_large = num_edges(graph_large); // Double the number of edges for undirected graphs: each edge counts as // in-edge and out-edge if (is_undirected(graph_small)) num_edges_small *= 2; if (is_undirected(graph_large)) num_edges_large *= 2; if (num_edges_small > num_edges_large) return false; detail::state<GraphSmall, GraphLarge, IndexMapSmall, IndexMapLarge, EdgeEquivalencePredicate, VertexEquivalencePredicate, SubGraphIsoMapCallback, problem_selection> s(graph_small, graph_large, index_map_small, index_map_large, edge_comp, vertex_comp); return detail::match(graph_small, graph_large, user_callback, vertex_order_small, s); } } // namespace detail // Returns vertex order (vertices sorted by multiplicity of in/out degrees) template<typename Graph> std::vector<typename graph_traits<Graph>::vertex_descriptor> vertex_order_by_mult(const Graph& graph) { std::vector<typename graph_traits<Graph>::vertex_descriptor> vertex_order; std::copy(vertices(graph).first, vertices(graph).second, std::back_inserter(vertex_order)); detail::sort_vertices(graph, get(vertex_index, graph), vertex_order); return vertex_order; } // Enumerates all graph sub-graph monomorphism mappings between graphs // graph_small and graph_large. Continues until user_callback returns true or the // search space has been fully explored. template <typename GraphSmall, typename GraphLarge, typename IndexMapSmall, typename IndexMapLarge, typename VertexOrderSmall, typename EdgeEquivalencePredicate, typename VertexEquivalencePredicate, typename SubGraphIsoMapCallback> bool vf2_subgraph_mono(const GraphSmall& graph_small, const GraphLarge& graph_large, SubGraphIsoMapCallback user_callback, IndexMapSmall index_map_small, IndexMapLarge index_map_large, const VertexOrderSmall& vertex_order_small, EdgeEquivalencePredicate edge_comp, VertexEquivalencePredicate vertex_comp) { return detail::vf2_subgraph_morphism<detail::subgraph_mono> (graph_small, graph_large, user_callback, index_map_small, index_map_large, vertex_order_small, edge_comp, vertex_comp); } // All default interface for vf2_subgraph_iso template <typename GraphSmall, typename GraphLarge, typename SubGraphIsoMapCallback> bool vf2_subgraph_mono(const GraphSmall& graph_small, const GraphLarge& graph_large, SubGraphIsoMapCallback user_callback) { return vf2_subgraph_mono(graph_small, graph_large, user_callback, get(vertex_index, graph_small), get(vertex_index, graph_large), vertex_order_by_mult(graph_small), always_equivalent(), always_equivalent()); } // Named parameter interface of vf2_subgraph_iso template <typename GraphSmall, typename GraphLarge, typename VertexOrderSmall, typename SubGraphIsoMapCallback, typename Param, typename Tag, typename Rest> bool vf2_subgraph_mono(const GraphSmall& graph_small, const GraphLarge& graph_large, SubGraphIsoMapCallback user_callback, const VertexOrderSmall& vertex_order_small, const bgl_named_params<Param, Tag, Rest>& params) { return vf2_subgraph_mono(graph_small, graph_large, user_callback, choose_const_pmap(get_param(params, vertex_index1), graph_small, vertex_index), choose_const_pmap(get_param(params, vertex_index2), graph_large, vertex_index), vertex_order_small, choose_param(get_param(params, edges_equivalent_t()), always_equivalent()), choose_param(get_param(params, vertices_equivalent_t()), always_equivalent()) ); } // Enumerates all graph sub-graph isomorphism mappings between graphs // graph_small and graph_large. Continues until user_callback returns true or the // search space has been fully explored. template <typename GraphSmall, typename GraphLarge, typename IndexMapSmall, typename IndexMapLarge, typename VertexOrderSmall, typename EdgeEquivalencePredicate, typename VertexEquivalencePredicate, typename SubGraphIsoMapCallback> bool vf2_subgraph_iso(const GraphSmall& graph_small, const GraphLarge& graph_large, SubGraphIsoMapCallback user_callback, IndexMapSmall index_map_small, IndexMapLarge index_map_large, const VertexOrderSmall& vertex_order_small, EdgeEquivalencePredicate edge_comp, VertexEquivalencePredicate vertex_comp) { return detail::vf2_subgraph_morphism<detail::subgraph_iso> (graph_small, graph_large, user_callback, index_map_small, index_map_large, vertex_order_small, edge_comp, vertex_comp); } // All default interface for vf2_subgraph_iso template <typename GraphSmall, typename GraphLarge, typename SubGraphIsoMapCallback> bool vf2_subgraph_iso(const GraphSmall& graph_small, const GraphLarge& graph_large, SubGraphIsoMapCallback user_callback) { return vf2_subgraph_iso(graph_small, graph_large, user_callback, get(vertex_index, graph_small), get(vertex_index, graph_large), vertex_order_by_mult(graph_small), always_equivalent(), always_equivalent()); } // Named parameter interface of vf2_subgraph_iso template <typename GraphSmall, typename GraphLarge, typename VertexOrderSmall, typename SubGraphIsoMapCallback, typename Param, typename Tag, typename Rest> bool vf2_subgraph_iso(const GraphSmall& graph_small, const GraphLarge& graph_large, SubGraphIsoMapCallback user_callback, const VertexOrderSmall& vertex_order_small, const bgl_named_params<Param, Tag, Rest>& params) { return vf2_subgraph_iso(graph_small, graph_large, user_callback, choose_const_pmap(get_param(params, vertex_index1), graph_small, vertex_index), choose_const_pmap(get_param(params, vertex_index2), graph_large, vertex_index), vertex_order_small, choose_param(get_param(params, edges_equivalent_t()), always_equivalent()), choose_param(get_param(params, vertices_equivalent_t()), always_equivalent()) ); } // Enumerates all isomorphism mappings between graphs graph1_ and graph2_. // Continues until user_callback returns true or the search space has been // fully explored. template <typename Graph1, typename Graph2, typename IndexMap1, typename IndexMap2, typename VertexOrder1, typename EdgeEquivalencePredicate, typename VertexEquivalencePredicate, typename GraphIsoMapCallback> bool vf2_graph_iso(const Graph1& graph1, const Graph2& graph2, GraphIsoMapCallback user_callback, IndexMap1 index_map1, IndexMap2 index_map2, const VertexOrder1& vertex_order1, EdgeEquivalencePredicate edge_comp, VertexEquivalencePredicate vertex_comp) { // Graph requirements BOOST_CONCEPT_ASSERT(( BidirectionalGraphConcept<Graph1> )); BOOST_CONCEPT_ASSERT(( VertexListGraphConcept<Graph1> )); BOOST_CONCEPT_ASSERT(( EdgeListGraphConcept<Graph1> )); BOOST_CONCEPT_ASSERT(( AdjacencyMatrixConcept<Graph1> )); BOOST_CONCEPT_ASSERT(( BidirectionalGraphConcept<Graph2> )); BOOST_CONCEPT_ASSERT(( VertexListGraphConcept<Graph2> )); BOOST_CONCEPT_ASSERT(( EdgeListGraphConcept<Graph2> )); BOOST_CONCEPT_ASSERT(( AdjacencyMatrixConcept<Graph2> )); typedef typename graph_traits<Graph1>::vertex_descriptor vertex1_type; typedef typename graph_traits<Graph2>::vertex_descriptor vertex2_type; typedef typename graph_traits<Graph1>::vertices_size_type size_type1; typedef typename graph_traits<Graph2>::vertices_size_type size_type2; // Property map requirements BOOST_CONCEPT_ASSERT(( ReadablePropertyMapConcept<IndexMap1, vertex1_type> )); typedef typename property_traits<IndexMap1>::value_type IndexMap1Value; BOOST_STATIC_ASSERT(( is_convertible<IndexMap1Value, size_type1>::value )); BOOST_CONCEPT_ASSERT(( ReadablePropertyMapConcept<IndexMap2, vertex2_type> )); typedef typename property_traits<IndexMap2>::value_type IndexMap2Value; BOOST_STATIC_ASSERT(( is_convertible<IndexMap2Value, size_type2>::value )); // Edge & vertex requirements typedef typename graph_traits<Graph1>::edge_descriptor edge1_type; typedef typename graph_traits<Graph2>::edge_descriptor edge2_type; BOOST_CONCEPT_ASSERT(( BinaryPredicateConcept<EdgeEquivalencePredicate, edge1_type, edge2_type> )); BOOST_CONCEPT_ASSERT(( BinaryPredicateConcept<VertexEquivalencePredicate, vertex1_type, vertex2_type> )); // Vertex order requirements BOOST_CONCEPT_ASSERT(( ContainerConcept<VertexOrder1> )); typedef typename VertexOrder1::value_type order_value_type; BOOST_STATIC_ASSERT(( is_same<vertex1_type, order_value_type>::value )); BOOST_ASSERT( num_vertices(graph1) == vertex_order1.size() ); if (num_vertices(graph1) != num_vertices(graph2)) return false; typename graph_traits<Graph1>::edges_size_type num_edges1 = num_edges(graph1); typename graph_traits<Graph2>::edges_size_type num_edges2 = num_edges(graph2); // Double the number of edges for undirected graphs: each edge counts as // in-edge and out-edge if (is_undirected(graph1)) num_edges1 *= 2; if (is_undirected(graph2)) num_edges2 *= 2; if (num_edges1 != num_edges2) return false; detail::state<Graph1, Graph2, IndexMap1, IndexMap2, EdgeEquivalencePredicate, VertexEquivalencePredicate, GraphIsoMapCallback, detail::isomorphism> s(graph1, graph2, index_map1, index_map2, edge_comp, vertex_comp); return detail::match(graph1, graph2, user_callback, vertex_order1, s); } // All default interface for vf2_graph_iso template <typename Graph1, typename Graph2, typename GraphIsoMapCallback> bool vf2_graph_iso(const Graph1& graph1, const Graph2& graph2, GraphIsoMapCallback user_callback) { return vf2_graph_iso(graph1, graph2, user_callback, get(vertex_index, graph1), get(vertex_index, graph2), vertex_order_by_mult(graph1), always_equivalent(), always_equivalent()); } // Named parameter interface of vf2_graph_iso template <typename Graph1, typename Graph2, typename VertexOrder1, typename GraphIsoMapCallback, typename Param, typename Tag, typename Rest> bool vf2_graph_iso(const Graph1& graph1, const Graph2& graph2, GraphIsoMapCallback user_callback, const VertexOrder1& vertex_order1, const bgl_named_params<Param, Tag, Rest>& params) { return vf2_graph_iso(graph1, graph2, user_callback, choose_const_pmap(get_param(params, vertex_index1), graph1, vertex_index), choose_const_pmap(get_param(params, vertex_index2), graph2, vertex_index), vertex_order1, choose_param(get_param(params, edges_equivalent_t()), always_equivalent()), choose_param(get_param(params, vertices_equivalent_t()), always_equivalent()) ); } // Verifies a graph (sub)graph isomorphism map template<typename Graph1, typename Graph2, typename CorresponenceMap1To2, typename EdgeEquivalencePredicate, typename VertexEquivalencePredicate> inline bool verify_vf2_subgraph_iso(const Graph1& graph1, const Graph2& graph2, const CorresponenceMap1To2 f, EdgeEquivalencePredicate edge_comp, VertexEquivalencePredicate vertex_comp) { BOOST_CONCEPT_ASSERT(( EdgeListGraphConcept<Graph1> )); BOOST_CONCEPT_ASSERT(( AdjacencyMatrixConcept<Graph2> )); detail::equivalent_edge_exists<Graph2> edge2_exists; BGL_FORALL_EDGES_T(e1, graph1, Graph1) { typename graph_traits<Graph1>::vertex_descriptor s1, t1; typename graph_traits<Graph2>::vertex_descriptor s2, t2; s1 = source(e1, graph1); t1 = target(e1, graph1); s2 = get(f, s1); t2 = get(f, t1); if (!vertex_comp(s1, s2) || !vertex_comp(t1, t2)) return false; typename graph_traits<Graph2>::edge_descriptor e2; if (!edge2_exists(s2, t2, detail::edge2_predicate<Graph1, Graph2, EdgeEquivalencePredicate>(edge_comp, e1), graph2)) return false; } return true; } // Variant of verify_subgraph_iso with all default parameters template<typename Graph1, typename Graph2, typename CorresponenceMap1To2> inline bool verify_vf2_subgraph_iso(const Graph1& graph1, const Graph2& graph2, const CorresponenceMap1To2 f) { return verify_vf2_subgraph_iso(graph1, graph2, f, always_equivalent(), always_equivalent()); } } // namespace boost #ifdef BOOST_ISO_INCLUDED_ITER_MACROS #undef BOOST_ISO_INCLUDED_ITER_MACROS #include <boost/graph/iteration_macros_undef.hpp> #endif #endif // BOOST_VF2_SUB_GRAPH_ISO_HPP
[ "k.melekhin@gmail.com" ]
k.melekhin@gmail.com
8307abb8017947deb399caad05d506a3d9d93921
d0a0170ff260d47a7d251216723a5e8be798544f
/day06/t01/app/src/Container.cpp
d8c691f50aa4fbe3e49d69cf31ab8092a508677a
[]
no_license
mmasniy/Maraphon-CPP-Ucode
c5d5a86c53f21b268c2b138fe3023e138dfecc4c
4611c10c342d808c3f48770058f11eced2839068
refs/heads/master
2022-12-09T23:49:07.052325
2020-08-30T16:24:08
2020-08-30T16:24:08
288,213,058
0
2
null
null
null
null
UTF-8
C++
false
false
499
cpp
#include "Container.h" Container::Container(bool isLocked, const LockpickDifficulty difficulty) : m_isLocked(isLocked), m_difficulty(difficulty){ } bool Container::isLocked() const { return m_isLocked; } LockpickDifficulty Container::lockDifficulty() const { return m_difficulty; } bool Container::tryToOpen(LockpickDifficulty skill) { if (skill >= m_difficulty || !m_isLocked) { m_isLocked = true; return true; } else { return false; } }
[ "masnijmaksim@gmail.com" ]
masnijmaksim@gmail.com
094a6ea26f4356631558c59111f4916d48eae4e8
8383dfe55d0ea81d9d20f8724fd9081bbf3428dd
/vendor/tensorflow_bfloat16_patch/tensorflow/core/kernels/constant_op.cc
00a784c7a9f6895bf2113a081c70e700039868b3
[ "MIT" ]
permissive
soumith/blocksparse
707f179da186e401ba4e6586c64320bd24360127
4071232a4a73a441424434ca2e81b1e4fd4e836c
refs/heads/master
2020-05-25T09:46:53.676995
2019-05-28T05:45:31
2019-05-28T05:45:31
187,745,586
5
0
MIT
2019-05-21T02:16:42
2019-05-21T02:16:42
null
UTF-8
C++
false
false
16,048
cc
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ // See docs in ../ops/array_ops.cc. #define EIGEN_USE_THREADS #if GOOGLE_CUDA #define EIGEN_USE_GPU #endif #include "tensorflow/core/kernels/constant_op.h" #include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor" #include "tensorflow/core/framework/register_types.h" #include "tensorflow/core/framework/tensor.h" #include "tensorflow/core/framework/tensor.pb.h" #include "tensorflow/core/framework/tensor_shape.h" #include "tensorflow/core/framework/tensor_types.h" #include "tensorflow/core/framework/types.h" #include "tensorflow/core/framework/variant_op_registry.h" #include "tensorflow/core/kernels/bounds_check.h" #include "tensorflow/core/kernels/fill_functor.h" #include "tensorflow/core/platform/macros.h" #ifdef TENSORFLOW_USE_SYCL #include "tensorflow/core/common_runtime/sycl/sycl_util.h" #endif // TENSORFLOW_USE_SYCL namespace tensorflow { ConstantOp::ConstantOp(OpKernelConstruction* ctx) : OpKernel(ctx), tensor_(ctx->output_type(0)) { const TensorProto* proto = nullptr; OP_REQUIRES_OK(ctx, ctx->GetAttr("value", &proto)); OP_REQUIRES_OK(ctx, ctx->device()->MakeTensorFromProto( *proto, AllocatorAttributes(), &tensor_)); OP_REQUIRES( ctx, ctx->output_type(0) == tensor_.dtype(), errors::InvalidArgument("Type mismatch between value (", DataTypeString(tensor_.dtype()), ") and dtype (", DataTypeString(ctx->output_type(0)), ")")); } void ConstantOp::Compute(OpKernelContext* ctx) { ctx->set_output(0, tensor_); } ConstantOp::~ConstantOp() {} REGISTER_KERNEL_BUILDER(Name("Const").Device(DEVICE_CPU), ConstantOp); #if GOOGLE_CUDA #define REGISTER_KERNEL(D, TYPE) \ REGISTER_KERNEL_BUILDER( \ Name("Const").Device(DEVICE_##D).TypeConstraint<TYPE>("dtype"), \ ConstantOp); REGISTER_KERNEL(GPU, Eigen::half); REGISTER_KERNEL(GPU, bfloat16); REGISTER_KERNEL(GPU, float); REGISTER_KERNEL(GPU, double); REGISTER_KERNEL(GPU, uint8); REGISTER_KERNEL(GPU, int8); REGISTER_KERNEL(GPU, uint16); REGISTER_KERNEL(GPU, int16); REGISTER_KERNEL(GPU, int64); REGISTER_KERNEL(GPU, complex64); REGISTER_KERNEL(GPU, complex128); REGISTER_KERNEL(GPU, bool); REGISTER_KERNEL(GPU, Variant); #undef REGISTER_KERNEL #endif #ifdef TENSORFLOW_USE_SYCL #define REGISTER_SYCL_KERNEL(D, TYPE) \ REGISTER_KERNEL_BUILDER( \ Name("Const").Device(DEVICE_##D).TypeConstraint<TYPE>("dtype"), \ ConstantOp); REGISTER_SYCL_KERNEL(SYCL, float); REGISTER_SYCL_KERNEL(SYCL, double); REGISTER_SYCL_KERNEL(SYCL, uint8); REGISTER_SYCL_KERNEL(SYCL, int8); REGISTER_SYCL_KERNEL(SYCL, uint16); REGISTER_SYCL_KERNEL(SYCL, int16); REGISTER_SYCL_KERNEL(SYCL, int64); REGISTER_SYCL_KERNEL(SYCL, bool); #undef REGISTER_SYCL_KERNEL #endif HostConstantOp::HostConstantOp(OpKernelConstruction* ctx) : OpKernel(ctx), tensor_(ctx->output_type(0)) { const TensorProto* proto = nullptr; AllocatorAttributes alloc_attr; alloc_attr.set_on_host(true); OP_REQUIRES_OK(ctx, ctx->GetAttr("value", &proto)); OP_REQUIRES_OK( ctx, ctx->device()->MakeTensorFromProto(*proto, alloc_attr, &tensor_)); OP_REQUIRES( ctx, ctx->output_type(0) == tensor_.dtype(), errors::InvalidArgument("Type mismatch between value (", DataTypeString(tensor_.dtype()), ") and dtype (", DataTypeString(ctx->output_type(0)), ")")); } void HostConstantOp::Compute(OpKernelContext* ctx) { ctx->set_output(0, tensor_); } #if GOOGLE_CUDA // A special GPU kernel for int32. // TODO(b/25387198): Also enable int32 in device memory. This kernel // registration requires all int32 inputs and outputs to be in host memory. REGISTER_KERNEL_BUILDER(Name("Const") .Device(DEVICE_GPU) .HostMemory("output") .TypeConstraint<int32>("dtype"), HostConstantOp); #endif #ifdef TENSORFLOW_USE_SYCL REGISTER_KERNEL_BUILDER(Name("Const") .Device(DEVICE_SYCL) .HostMemory("output") .TypeConstraint<int32>("dtype"), HostConstantOp); #endif // TENSORFLOW_USE_SYCL typedef Eigen::ThreadPoolDevice CPUDevice; typedef Eigen::GpuDevice GPUDevice; #ifdef TENSORFLOW_USE_SYCL typedef Eigen::SyclDevice SYCLDevice; #endif // TENSORFLOW_USE_SYCL namespace functor { // Partial specialization of FillFunctor<Device=CPUDevice, T>. template <typename T> struct FillFunctor<CPUDevice, T> { void operator()(const CPUDevice& d, typename TTypes<T>::Flat out, typename TTypes<T>::ConstScalar in) { out.device(d) = out.constant(in()); } }; } // end namespace functor template <typename Device, typename T> class FillOp : public OpKernel { public: explicit FillOp(OpKernelConstruction* context) : OpKernel(context) {} void Compute(OpKernelContext* context) override { const Tensor& Tdims = context->input(0); OP_REQUIRES( context, IsLegacyVector(Tdims.shape()), errors::InvalidArgument("dims must be a vector of int32, got shape ", Tdims.shape().DebugString())); const Tensor& Tvalue = context->input(1); OP_REQUIRES(context, IsLegacyScalar(Tvalue.shape()), errors::InvalidArgument("value must be a scalar, got shape ", Tvalue.shape().DebugString())); auto dims = Tdims.flat<int32>(); TensorShape shape; OP_REQUIRES_OK(context, TensorShapeUtils::MakeShape( reinterpret_cast<const int32*>(dims.data()), dims.size(), &shape)); Tensor* out = nullptr; OP_REQUIRES_OK(context, context->allocate_output(0, shape, &out)); functor::FillFunctor<Device, T> functor; functor(context->eigen_device<Device>(), out->flat<T>(), Tvalue.scalar<T>()); } }; #ifdef TENSORFLOW_USE_SYCL namespace functor { // Partial specialization of FillFunctor<Device=SYCLDevice, T>. template <typename T> struct FillFunctor<SYCLDevice, T> { void operator()(const SYCLDevice& d, typename TTypes<T>::Flat out, typename TTypes<T>::ConstScalar in) { #if !defined(EIGEN_HAS_INDEX_LIST) Eigen::array<int, 1> rank1{1}; #else Eigen::IndexList<Eigen::type2index<1> > rank1; #endif const int size = out.dimension(0); Eigen::array<int, 1> broadcast_dims{size}; To32Bit(out).device(d) = in.reshape(rank1).broadcast(broadcast_dims); } }; } // namespace functor #endif // TENSORFLOW_USE_SYCL #define REGISTER_KERNEL(D, TYPE) \ REGISTER_KERNEL_BUILDER(Name("Fill") \ .Device(DEVICE_##D) \ .TypeConstraint<TYPE>("T") \ .HostMemory("dims"), \ FillOp<D##Device, TYPE>); #define REGISTER_CPU_KERNEL(TYPE) REGISTER_KERNEL(CPU, TYPE) TF_CALL_ALL_TYPES(REGISTER_CPU_KERNEL); // TODO(b/28917570): Add a test for this. Currently python 3 is not happy about // the conversion from uint8 to quint8. REGISTER_KERNEL(CPU, quint8); REGISTER_KERNEL(CPU, quint16); #undef REGISTER_CPU_KERNEL #ifdef TENSORFLOW_USE_SYCL REGISTER_KERNEL(SYCL, float); REGISTER_KERNEL(SYCL, double); REGISTER_KERNEL(SYCL, uint8); REGISTER_KERNEL(SYCL, int8); REGISTER_KERNEL(SYCL, uint16); REGISTER_KERNEL(SYCL, int16); REGISTER_KERNEL(SYCL, int64); REGISTER_KERNEL_BUILDER(Name("Fill") .Device(DEVICE_SYCL) .TypeConstraint<int32>("T") .HostMemory("dims") .HostMemory("value") .HostMemory("output"), FillOp<CPUDevice, int32>); #undef REGISTER_KERNEL_SYCL #endif // TENSORFLOW_USE_SYCL #if GOOGLE_CUDA REGISTER_KERNEL(GPU, Eigen::half); REGISTER_KERNEL(GPU, bfloat16); REGISTER_KERNEL(GPU, float); REGISTER_KERNEL(GPU, double); REGISTER_KERNEL(GPU, uint8); REGISTER_KERNEL(GPU, int8); REGISTER_KERNEL(GPU, uint16); REGISTER_KERNEL(GPU, int16); REGISTER_KERNEL(GPU, int64); REGISTER_KERNEL(GPU, bool); // Currently we do not support filling strings and complex64 on GPU // A special GPU kernel for int32. // TODO(b/25387198): Also enable int32 in device memory. This kernel // registration requires all int32 inputs and outputs to be in host memory. REGISTER_KERNEL_BUILDER(Name("Fill") .Device(DEVICE_GPU) .TypeConstraint<int32>("T") .HostMemory("dims") .HostMemory("value") .HostMemory("output"), FillOp<CPUDevice, int32>); #endif #undef REGISTER_KERNEL template <typename Device, typename T> class ZerosLikeOp : public OpKernel { public: explicit ZerosLikeOp(OpKernelConstruction* ctx) : OpKernel(ctx) {} void Compute(OpKernelContext* ctx) override { const Tensor& input = ctx->input(0); const Device& d = ctx->eigen_device<Device>(); if (std::is_same<T, Variant>::value) { OP_REQUIRES( ctx, input.dims() == 0, errors::InvalidArgument("ZerosLike non-scalar Tensor with " "dtype=DT_VARIANT is not supported.")); const Variant& v = input.scalar<Variant>()(); Tensor out(cpu_allocator(), DT_VARIANT, TensorShape({})); Variant* out_v = &(out.scalar<Variant>()()); OP_REQUIRES_OK(ctx, UnaryOpVariant<Device>( ctx, ZEROS_LIKE_VARIANT_UNARY_OP, v, out_v)); ctx->set_output(0, out); } else { Tensor* out = nullptr; OP_REQUIRES_OK(ctx, ctx->forward_input_or_allocate_output( {0}, 0, input.shape(), &out)); functor::SetZeroFunctor<Device, T> f; f(d, out->flat<T>()); } } }; #define REGISTER_KERNEL(type, dev) \ REGISTER_KERNEL_BUILDER( \ Name("ZerosLike").Device(DEVICE_##dev).TypeConstraint<type>("T"), \ ZerosLikeOp<dev##Device, type>) #define REGISTER_CPU(type) REGISTER_KERNEL(type, CPU) TF_CALL_POD_STRING_TYPES(REGISTER_CPU); REGISTER_CPU(Variant); #undef REGISTER_CPU #ifdef TENSORFLOW_USE_SYCL REGISTER_KERNEL(bool, SYCL); REGISTER_KERNEL(float, SYCL); REGISTER_KERNEL(double, SYCL); REGISTER_KERNEL(int64, SYCL); REGISTER_KERNEL_BUILDER(Name("ZerosLike") .Device(DEVICE_SYCL) .TypeConstraint<int32>("T") .HostMemory("y"), ZerosLikeOp<CPUDevice, int32>); #endif // TENSORFLOW_USE_SYCL #if GOOGLE_CUDA REGISTER_KERNEL(bool, GPU); REGISTER_KERNEL(Eigen::half, GPU); REGISTER_KERNEL(bfloat16, GPU); REGISTER_KERNEL(float, GPU); REGISTER_KERNEL(double, GPU); REGISTER_KERNEL(complex64, GPU); REGISTER_KERNEL(complex128, GPU); REGISTER_KERNEL(int64, GPU); REGISTER_KERNEL_BUILDER(Name("ZerosLike") .Device(DEVICE_GPU) .TypeConstraint<int32>("T") .HostMemory("y"), ZerosLikeOp<CPUDevice, int32>); // TODO(ebrevdo): Once rendezvous has been properly set up for // Variants, we'll no longer need a HostMemory attribute for this case. REGISTER_KERNEL_BUILDER(Name("ZerosLike") .Device(DEVICE_GPU) .TypeConstraint<Variant>("T") .HostMemory("x") .HostMemory("y"), ZerosLikeOp<GPUDevice, Variant>); #endif // GOOGLE_CUDA #undef REGISTER_KERNEL template <typename Device, typename T> class OnesLikeOp : public OpKernel { public: explicit OnesLikeOp(OpKernelConstruction* ctx) : OpKernel(ctx) {} void Compute(OpKernelContext* ctx) override { const Tensor& input = ctx->input(0); Tensor* out = nullptr; OP_REQUIRES_OK(ctx, ctx->forward_input_or_allocate_output( {0}, 0, input.shape(), &out)); functor::SetOneFunctor<Device, T> f; f(ctx->eigen_device<Device>(), out->flat<T>()); } }; #define REGISTER_KERNEL(type, dev) \ REGISTER_KERNEL_BUILDER( \ Name("OnesLike").Device(DEVICE_##dev).TypeConstraint<type>("T"), \ OnesLikeOp<dev##Device, type>) #define REGISTER_CPU(type) REGISTER_KERNEL(type, CPU) TF_CALL_POD_TYPES(REGISTER_CPU); #undef REGISTER_CPU #ifdef TENSORFLOW_USE_SYCL REGISTER_KERNEL(float, SYCL); REGISTER_KERNEL(bool, SYCL); REGISTER_KERNEL_BUILDER(Name("OnesLike") .Device(DEVICE_SYCL) .TypeConstraint<int32>("T") .HostMemory("y"), OnesLikeOp<CPUDevice, int32>); #endif // TENSORFLOW_USE_SYCL #if GOOGLE_CUDA REGISTER_KERNEL(bool, GPU); REGISTER_KERNEL(Eigen::half, GPU); REGISTER_KERNEL(bfloat16, GPU); REGISTER_KERNEL(float, GPU); REGISTER_KERNEL(double, GPU); REGISTER_KERNEL(complex64, GPU); REGISTER_KERNEL(complex128, GPU); REGISTER_KERNEL(int64, GPU); REGISTER_KERNEL_BUILDER(Name("OnesLike") .Device(DEVICE_GPU) .TypeConstraint<int32>("T") .HostMemory("y"), OnesLikeOp<CPUDevice, int32>); #endif // GOOGLE_CUDA #undef REGISTER_KERNEL PlaceholderOp::PlaceholderOp(OpKernelConstruction* ctx) : OpKernel(ctx) { OP_REQUIRES_OK(ctx, ctx->GetAttr("shape", &expected_shape_)); } void PlaceholderOp::Compute(OpKernelContext* ctx) { if (expected_shape_.dims() > 0) { OP_REQUIRES(ctx, false, errors::InvalidArgument( "You must feed a value for placeholder tensor '", name(), "' with dtype ", DataTypeString(output_type(0)), " and shape ", expected_shape_.DebugString())); } else { OP_REQUIRES(ctx, false, errors::InvalidArgument( "You must feed a value for placeholder tensor '", name(), "' with dtype ", DataTypeString(output_type(0)))); } } REGISTER_KERNEL_BUILDER(Name("Placeholder").Device(DEVICE_CPU), PlaceholderOp); REGISTER_KERNEL_BUILDER(Name("PlaceholderV2").Device(DEVICE_CPU), PlaceholderOp); // The following GPU kernel registration is used to address the situation that // a placeholder is added in a GPU device context and soft placement is false. // Since a placeholder should never be executed, adding these GPU kernels has // no effect on graph execution. REGISTER_KERNEL_BUILDER(Name("Placeholder").Device(DEVICE_GPU), PlaceholderOp); REGISTER_KERNEL_BUILDER(Name("PlaceholderV2").Device(DEVICE_GPU), PlaceholderOp); #if TENSORFLOW_USE_SYCL REGISTER_KERNEL_BUILDER(Name("Placeholder").Device(DEVICE_SYCL), PlaceholderOp); REGISTER_KERNEL_BUILDER(Name("PlaceholderV2").Device(DEVICE_SYCL), PlaceholderOp); #endif // TENSORFLOW_USE_SYCL } // namespace tensorflow
[ "jonas@openai.com" ]
jonas@openai.com
f0a32a95bc4489e5010d2bcb142cf234edb61a95
27ffb44629667cb5fc2c0816f7b593a0be462af6
/Library/DXLibrary/DXLibrary/DirectX12/RootSignature/RootSignatureManager.h
6f3daad705e4f2027b86255d1afec712d708cebd
[]
no_license
Moto0116/Library
70ce9c39246781e749209eccdc358966f777abde
856bfdd8cd98e17483fc4734d36caa0189d13778
refs/heads/develop
2021-01-19T18:24:47.576756
2018-03-21T11:16:46
2018-03-21T11:16:46
81,069,617
2
0
null
2017-03-18T11:38:40
2017-02-06T09:21:07
C++
UTF-8
C++
false
false
272
h
#ifndef LIB_DX12_ROOTSIGNATUREMANAGER_H #define LIB_DX12_ROOTSIGNATUREMANAGER_H namespace Lib { namespace Dx12 { class RootSignatureManager { public: RootSignatureManager(); ~RootSignatureManager(); }; } } #endif // !LIB_DX12_ROOTSIGNATUREMANAGER_H
[ "moto01160902@gmail.com" ]
moto01160902@gmail.com
05f6971ee94821cc12169a51e208a0008970d301
7fcd47097c42fcdb7acb2e10e75759e16ade518e
/binding.cc
0ed90062b6157cb68280204e3e2bee19081929b3
[ "MIT" ]
permissive
joaojeronimo/v8worker
eb1c6600ed3d9e387914a1f47e34975be3f5fb9b
e923014340b3a50023b0ea5d8452b275ed957a37
refs/heads/master
2021-01-22T00:24:05.322290
2015-03-30T13:42:41
2015-03-30T13:42:41
33,125,257
1
0
null
2015-03-30T13:39:14
2015-03-30T13:39:13
null
UTF-8
C++
false
false
6,899
cc
#include <stdio.h> #include <assert.h> #include <stdlib.h> #include <string> #include "v8.h" #include "libplatform/libplatform.h" #include "binding.h" using namespace v8; struct worker_s { int x; void* data; worker_recv_cb cb; Isolate* isolate; std::string last_exception; Persistent<Function> recv; Persistent<Context> context; }; // Extracts a C string from a V8 Utf8Value. const char* ToCString(const String::Utf8Value& value) { return *value ? *value : "<string conversion failed>"; } // Exception details will be appended to the first argument. std::string ExceptionString(Isolate* isolate, TryCatch* try_catch) { std::string out; size_t scratchSize = 100; char scratch[scratchSize]; // just some scratch space for sprintf HandleScope handle_scope(isolate); String::Utf8Value exception(try_catch->Exception()); const char* exception_string = ToCString(exception); printf("exception string: %s\n", exception_string); Handle<Message> message = try_catch->Message(); if (message.IsEmpty()) { // V8 didn't provide any extra information about this error; just // print the exception. out.append(exception_string); out.append("\n"); } else { // Print (filename):(line number): (message). String::Utf8Value filename(message->GetScriptOrigin().ResourceName()); const char* filename_string = ToCString(filename); int linenum = message->GetLineNumber(); snprintf(scratch, scratchSize, "%s:%i: %s\n", filename_string, linenum, exception_string); out.append(scratch); // Print line of source code. String::Utf8Value sourceline(message->GetSourceLine()); const char* sourceline_string = ToCString(sourceline); out.append(sourceline_string); out.append("\n"); // Print wavy underline (GetUnderline is deprecated). int start = message->GetStartColumn(); for (int i = 0; i < start; i++) { out.append(" "); } int end = message->GetEndColumn(); for (int i = start; i < end; i++) { out.append("^"); } out.append("\n"); String::Utf8Value stack_trace(try_catch->StackTrace()); if (stack_trace.length() > 0) { const char* stack_trace_string = ToCString(stack_trace); out.append(stack_trace_string); out.append("\n"); } } return out; } extern "C" { #include "_cgo_export.h" void go_recv_cb(const char* msg, void* data) { recvCb((char*)msg, data); } const char* worker_version() { return V8::GetVersion(); } const char* worker_last_exception(worker* w) { return w->last_exception.c_str(); } int worker_load(worker* w, char* name_s, char* source_s) { Locker locker(w->isolate); Isolate::Scope isolate_scope(w->isolate); HandleScope handle_scope(w->isolate); Local<Context> context = Local<Context>::New(w->isolate, w->context); Context::Scope context_scope(context); TryCatch try_catch; Local<String> name = String::NewFromUtf8(w->isolate, name_s); Local<String> source = String::NewFromUtf8(w->isolate, source_s); ScriptOrigin origin(name); Local<Script> script = Script::Compile(source, &origin); if (script.IsEmpty()) { assert(try_catch.HasCaught()); w->last_exception = ExceptionString(w->isolate, &try_catch); return 1; } Handle<Value> result = script->Run(); if (result.IsEmpty()) { assert(try_catch.HasCaught()); w->last_exception = ExceptionString(w->isolate, &try_catch); return 2; } return 0; } void Print(const FunctionCallbackInfo<Value>& args) { bool first = true; for (int i = 0; i < args.Length(); i++) { HandleScope handle_scope(args.GetIsolate()); if (first) { first = false; } else { printf(" "); } String::Utf8Value str(args[i]); const char* cstr = ToCString(str); printf("%s", cstr); } printf("\n"); fflush(stdout); } // sets the recv callback. void Recv(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = args.GetIsolate(); worker* w = (worker*)isolate->GetData(0); assert(w->isolate == isolate); HandleScope handle_scope(isolate); Local<Context> context = Local<Context>::New(w->isolate, w->context); Context::Scope context_scope(context); Local<Value> v = args[0]; assert(v->IsFunction()); Local<Function> func = Local<Function>::Cast(v); w->recv.Reset(isolate, func); } // Called from javascript. Must route message to golang. void Send(const FunctionCallbackInfo<Value>& args) { std::string msg; worker* w = NULL; { Isolate* isolate = args.GetIsolate(); w = static_cast<worker*>(isolate->GetData(0)); assert(w->isolate == isolate); Locker locker(w->isolate); HandleScope handle_scope(isolate); Local<Context> context = Local<Context>::New(w->isolate, w->context); Context::Scope context_scope(context); Local<Value> v = args[0]; assert(v->IsString()); String::Utf8Value str(v); msg = ToCString(str); } // XXX should we use Unlocker? w->cb(msg.c_str(), w->data); } // Called from golang. Must route message to javascript lang. // non-zero return value indicates error. check worker_last_exception(). int worker_send(worker* w, const char* msg) { Locker locker(w->isolate); Isolate::Scope isolate_scope(w->isolate); HandleScope handle_scope(w->isolate); Local<Context> context = Local<Context>::New(w->isolate, w->context); Context::Scope context_scope(context); TryCatch try_catch; Local<Function> recv = Local<Function>::New(w->isolate, w->recv); if (recv.IsEmpty()) { w->last_exception = "$recv not called"; return 1; } Local<Value> args[1]; args[0] = String::NewFromUtf8(w->isolate, msg); assert(!try_catch.HasCaught()); recv->Call(context->Global(), 1, args); if (try_catch.HasCaught()) { w->last_exception = ExceptionString(w->isolate, &try_catch); return 2; } return 0; } worker* worker_new(worker_recv_cb cb, void* data) { V8::Initialize(); Platform* platform = platform::CreateDefaultPlatform(); V8::InitializePlatform(platform); Isolate* isolate = Isolate::New(); Locker locker(isolate); Isolate::Scope isolate_scope(isolate); HandleScope handle_scope(isolate); worker* w = new(worker); w->isolate = isolate; w->isolate->SetCaptureStackTraceForUncaughtExceptions(true); w->isolate->SetData(0, w); w->data = data; w->cb = cb; Local<ObjectTemplate> global = ObjectTemplate::New(w->isolate); global->Set(String::NewFromUtf8(w->isolate, "$print"), FunctionTemplate::New(w->isolate, Print)); global->Set(String::NewFromUtf8(w->isolate, "$recv"), FunctionTemplate::New(w->isolate, Recv)); global->Set(String::NewFromUtf8(w->isolate, "$send"), FunctionTemplate::New(w->isolate, Send)); Local<Context> context = Context::New(w->isolate, NULL, global); w->context.Reset(w->isolate, context); //context->Enter(); return w; } }
[ "ry@tinyclouds.org" ]
ry@tinyclouds.org
116ba7c650b99fb2c34e7d7c8c4352ca32812c55
0e40a0486826825c2c8adba9a538e16ad3efafaf
/lib/boost/include/boost/mpl/vector/aux_/push_back.hpp
b10f072b9b96c4314ef3e932b3e5ad8803944feb
[ "MIT" ]
permissive
iraqigeek/iZ3D
4c45e69a6e476ad434d5477f21f5b5eb48336727
ced8b3a4b0a152d0177f2e94008918efc76935d5
refs/heads/master
2023-05-25T19:04:06.082744
2020-12-28T03:27:55
2020-12-28T03:27:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,008
hpp
#ifndef BOOST_MPL_VECTOR_AUX_PUSH_BACK_HPP_INCLUDED #define BOOST_MPL_VECTOR_AUX_PUSH_BACK_HPP_INCLUDED // Copyright Aleksey Gurtovoy 2000-2004 // // 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) // // See http://www.boost.org/libs/mpl for documentation. // $Id: push_back.hpp 49267 2008-10-11 06:19:02Z agurtovoy $ // $Date: 2008-10-11 10:19:02 +0400 (Ñá, 11 îêò 2008) $ // $Revision: 49267 $ #include <boost/mpl/push_back_fwd.hpp> #include <boost/mpl/aux_/config/typeof.hpp> #if defined(BOOST_MPL_CFG_TYPEOF_BASED_SEQUENCES) # include <boost/mpl/vector/aux_/item.hpp> # include <boost/mpl/vector/aux_/tag.hpp> namespace boost { namespace mpl { template<> struct push_back_impl< aux::vector_tag > { template< typename Vector, typename T > struct apply { typedef v_item<T,Vector,0> type; }; }; }} #endif #endif // BOOST_MPL_VECTOR_AUX_PUSH_BACK_HPP_INCLUDED
[ "github@bo3b.net" ]
github@bo3b.net
fc41d2b3aa56e8aebd921ddc9e0addf38ff13977
ecfa6ca72f03c60a293280108f8dcb6c0f0b7969
/Wordclock/Wordclock/Wordclock/inc/Animation/Clock/AnimationClockTeletype.h
9083ee32f38420f289a9b24f3d033e009f485c5d
[]
no_license
AndreasBur/Wordclock
0946f7b939a4883273237ab903b2eff2087b8306
376a1dd8a385d507a71fa2e67bf2a269b2068242
refs/heads/master
2022-07-19T15:08:35.074029
2022-07-09T11:41:32
2022-07-09T11:41:32
94,092,644
1
0
null
null
null
null
UTF-8
C++
false
false
5,015
h
/****************************************************************************************************************************************************** * COPYRIGHT * --------------------------------------------------------------------------------------------------------------------------------------------------- * \verbatim * Copyright (c) Andreas Burnickl All rights reserved. * * \endverbatim * --------------------------------------------------------------------------------------------------------------------------------------------------- * FILE DESCRIPTION * -------------------------------------------------------------------------------------------------------------------------------------------------*/ /** \file AnimationClockTeletype.h * \brief * * \details * ******************************************************************************************************************************************************/ #ifndef _ANIMATION_CLOCK_TELETYPE_H_ #define _ANIMATION_CLOCK_TELETYPE_H_ /****************************************************************************************************************************************************** * INCLUDES ******************************************************************************************************************************************************/ #include "StandardTypes.h" #include "Arduino.h" #include "Clock.h" #include "AnimationClockCommon.h" /****************************************************************************************************************************************************** * GLOBAL CONSTANT MACROS ******************************************************************************************************************************************************/ /* AnimationClockTeletype configuration parameter */ /* AnimationClockTeletype parameter */ /****************************************************************************************************************************************************** * GLOBAL FUNCTION MACROS ******************************************************************************************************************************************************/ /****************************************************************************************************************************************************** * GLOBAL DATA TYPES AND STRUCTURES *****************************************************************************************************************************************************/ /****************************************************************************************************************************************************** * CLASS AnimationClockTeletype ******************************************************************************************************************************************************/ class AnimationClockTeletype : public AnimationClockCommon { public: /****************************************************************************************************************************************************** * GLOBAL DATA TYPES AND STRUCTURES ******************************************************************************************************************************************************/ /****************************************************************************************************************************************************** * P R I V A T E D A T A A N D F U N C T I O N S ******************************************************************************************************************************************************/ private: Clock* pClock; Display* pDisplay; Clock::ClockWordsTableType ClockWordsTable; byte CurrentWordIndex; byte CurrentWordLength; byte CurrentCharIndex; DisplayWords Words; // functions void reset(); stdReturnType setNextWordIndex(); /****************************************************************************************************************************************************** * P U B L I C F U N C T I O N S ******************************************************************************************************************************************************/ public: AnimationClockTeletype(); ~AnimationClockTeletype(); // get methods // set methods // methods void init(Display*, Clock*); stdReturnType setClock(byte, byte); void task(); void show() { pDisplay->show(); } }; #endif /****************************************************************************************************************************************************** * E N D O F F I L E ******************************************************************************************************************************************************/
[ "a.burnickl@gmail.com" ]
a.burnickl@gmail.com
7db1380d8897bf00a28d7934b2699b88f6e97f41
96f9b1d313eca3cfa731d121d072a44434cec768
/src/qt/editaddressdialog.cpp
d34001ca8ce1a463810dbbecaa8674a4f8086147
[ "MIT" ]
permissive
jjshsgsa/Bixbcoin-core
32256da6d230fa151fa6f0eb5ac2d59d72c4a62d
f4b5c57e351a9285f136a27b70760e468fa830a8
refs/heads/main
2022-12-27T03:42:02.786514
2020-10-14T18:21:58
2020-10-14T18:21:58
306,915,613
1
0
MIT
2020-10-24T15:41:25
2020-10-24T15:41:24
null
UTF-8
C++
false
false
3,948
cpp
// Copyright (c) 2011-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "editaddressdialog.h" #include "ui_editaddressdialog.h" #include "addresstablemodel.h" #include "guiutil.h" #include <QDataWidgetMapper> #include <QMessageBox> EditAddressDialog::EditAddressDialog(Mode _mode, QWidget *parent) : QDialog(parent), ui(new Ui::EditAddressDialog), mapper(0), mode(_mode), model(0) { ui->setupUi(this); GUIUtil::setupAddressWidget(ui->addressEdit, this); switch(mode) { case NewReceivingAddress: setWindowTitle(tr("New receiving address")); ui->addressEdit->setEnabled(false); break; case NewSendingAddress: setWindowTitle(tr("New sending address")); break; case EditReceivingAddress: setWindowTitle(tr("Edit receiving address")); ui->addressEdit->setEnabled(false); break; case EditSendingAddress: setWindowTitle(tr("Edit sending address")); break; } mapper = new QDataWidgetMapper(this); mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit); } EditAddressDialog::~EditAddressDialog() { delete ui; } void EditAddressDialog::setModel(AddressTableModel *_model) { this->model = _model; if(!_model) return; mapper->setModel(_model); mapper->addMapping(ui->labelEdit, AddressTableModel::Label); mapper->addMapping(ui->addressEdit, AddressTableModel::Address); } void EditAddressDialog::loadRow(int row) { mapper->setCurrentIndex(row); } bool EditAddressDialog::saveCurrentRow() { if(!model) return false; switch(mode) { case NewReceivingAddress: case NewSendingAddress: address = model->addRow( mode == NewSendingAddress ? AddressTableModel::Send : AddressTableModel::Receive, ui->labelEdit->text(), ui->addressEdit->text()); break; case EditReceivingAddress: case EditSendingAddress: if(mapper->submit()) { address = ui->addressEdit->text(); } break; } return !address.isEmpty(); } void EditAddressDialog::accept() { if(!model) return; if(!saveCurrentRow()) { switch(model->getEditStatus()) { case AddressTableModel::OK: // Failed with unknown reason. Just reject. break; case AddressTableModel::NO_CHANGES: // No changes were made during edit operation. Just reject. break; case AddressTableModel::INVALID_ADDRESS: QMessageBox::warning(this, windowTitle(), tr("The entered address \"%1\" is not a valid Bixbcoin address.").arg(ui->addressEdit->text()), QMessageBox::Ok, QMessageBox::Ok); break; case AddressTableModel::DUPLICATE_ADDRESS: QMessageBox::warning(this, windowTitle(), tr("The entered address \"%1\" is already in the address book.").arg(ui->addressEdit->text()), QMessageBox::Ok, QMessageBox::Ok); break; case AddressTableModel::WALLET_UNLOCK_FAILURE: QMessageBox::critical(this, windowTitle(), tr("Could not unlock wallet."), QMessageBox::Ok, QMessageBox::Ok); break; case AddressTableModel::KEY_GENERATION_FAILURE: QMessageBox::critical(this, windowTitle(), tr("New key generation failed."), QMessageBox::Ok, QMessageBox::Ok); break; } return; } QDialog::accept(); } QString EditAddressDialog::getAddress() const { return address; } void EditAddressDialog::setAddress(const QString &_address) { this->address = _address; ui->addressEdit->setText(_address); }
[ "info@bixbcoin.com" ]
info@bixbcoin.com
624b678d5e90f9a795c3bfa86e8a809f15a9a0c4
c49a1113fd445046e126a1e38cc16044e9e6fa03
/zhouqi/source/OJ.cpp
337d6a5f3fa8077273a9f24887a61aa33b60331a
[]
no_license
VicoandMe/HW
276a8c289fab17e24afbb7a309a265c393ccd407
6900fbaf97761d2c5b7c4d92f976a5c70920f99e
refs/heads/master
2021-01-10T15:26:04.342717
2016-02-02T07:04:31
2016-02-02T07:04:31
50,571,071
0
0
null
null
null
null
GB18030
C++
false
false
739
cpp
#include "OJ.h" #include <string.h> //#include <stdio.h> /* 功能:计算字符串的最小周期。 原型: int GetMinPeriod(char *string); 输入参数: char * string:字符串。 返回值: int 字符串最小周期。 */ int GetMinPeriod(char *inputstring) { int length = strlen(inputstring); for (int i = 1; i < length;i++) { bool flag = 0; if (length%i == 0) { flag = 1; for (int j = i; j < length; j++) { if (inputstring[j] != inputstring[j-i]) { flag = 0; break; } } if(flag == 1) { return i; } } } return length; } //int main() { // char a[] = "abcabcabcabc....\0"; // printf("%d\n",GetMinPeriod(a)); //}
[ "li362927450@gmail.com" ]
li362927450@gmail.com
81007cfbf3ec7f5e773a72fe7b1b1a5a8ea48168
25b36236d90aa38deb0e28db06f5f5ee5264d931
/NPLib/Core/NPInputParser.h
0791fe5c74a8c47f83b8bfd0390d79066d4dbc61
[]
no_license
adrien-matta/nptool
54b5ea6fe2d8c226e7422a948d3ecc94d62d1ff2
415ad50066f715ca1de312da1202201f9381e87e
refs/heads/NPTool.2.dev
2021-04-18T23:52:44.645407
2019-09-02T12:38:49
2019-09-02T12:38:49
13,268,020
36
20
null
2016-12-05T11:46:35
2013-10-02T10:11:22
C++
UTF-8
C++
false
false
4,562
h
#ifndef NPINPUTPARSER #define NPINPUTPARSER /***************************************************************************** * Copyright (C) 2009-2016 this file is part of the NPTool Project * * * * For the licensing terms see $NPTOOL/Licence/NPTool_Licence * * For the list of contributors see $NPTOOL/Licence/Contributors * *****************************************************************************/ /***************************************************************************** * Original Author: Adrien Matta contact address: matta@lpccaen.in2p3.fr * * * * Creation Date : December 2016 * * Last update : * *---------------------------------------------------------------------------* * Decription: * * This class allow for parsing of tabulated input file with unit and token* * * *---------------------------------------------------------------------------* * Comment: * * * * * *****************************************************************************/ // STL #include<string> #include<vector> #include<map> // ROOT #include"TVector3.h" namespace NPL{ static std::string token_separator = "="; std::string StripSpaces(std::string line); std::string ToLower(std::string line); double ApplyUnit(double value, std::string unit); unsigned int GetLevel(std::string line); class InputBlock{ public: InputBlock(){}; InputBlock(std::string line); ~InputBlock(){}; NPL::InputBlock* Copy(); private: unsigned int m_Level; std::string m_MainToken; std::string m_MainValue; std::vector<std::string> m_Token; std::vector<std::string> m_Value; public: void AddLine(std::string line); std::string ExtractToken(std::string line,std::string separator=""); std::string ExtractValue(std::string line,std::string separator=""); public: std::string GetToken(unsigned int i){return m_Token[i];}; std::string GetValue(unsigned int i){return m_Value[i];}; std::string GetValue(std::string Token); void SetValue(unsigned int i, std::string val){m_Value[i]=val;}; public: bool HasTokenList(std::vector<std::string> TokenList); bool HasToken(std::string Token); public: std::string GetMainToken(){return m_MainToken;}; std::string GetMainValue(){return m_MainValue;}; unsigned int GetSize(){return m_Token.size();}; double GetDouble(std::string Token,std::string default_unit); int GetInt(std::string Token); std::string GetString(std::string Token); TVector3 GetTVector3(std::string Token,std::string default_unit); std::vector<double> GetVectorDouble(std::string Token,std::string default_unit); std::vector<int> GetVectorInt(std::string Token); std::vector<std::string> GetVectorString(std::string Token); std::vector<NPL::InputBlock*> GetSubBlock(std::string Token); public: void Dump(); }; //////////////////////////////////////////////////////////////////////////////// class InputParser{ public: InputParser(){}; InputParser(std::string filename,bool ExitOnError=true) {ReadFile(filename,ExitOnError);} ~InputParser(){}; private: std::vector<InputBlock*> m_Block; std::map<std::string, std::vector<std::string> > m_Aliases; private: int m_verbose; public: void ReadFile(std::string filename,bool ExitOnError=true); void TreatAliases(); void TreatOneAlias(){}; void Dump(); void Print() {Dump();} void Clear(); std::vector<InputBlock*> GetAllBlocksWithToken(std::string Token); std::vector<InputBlock*> GetAllBlocksWithTokenAndValue(std::string Token,std::string Value); std::vector<std::string> GetAllBlocksValues(std::string); std::vector<std::string> GetAllBlocksToken(); private: bool IsNotComment(std::string line); }; } #endif
[ "matta@lpccaen.in2p3.fr" ]
matta@lpccaen.in2p3.fr
64a6dc204d1c390a91084b502c0d7bfe8afb24ac
5175bd24b43d8db699341997df5fecf21cc7afc1
/libs/config/checks/std/cpp_lib_transformation_trait_aliases_14.cpp
1ce92f60a915a8bfdfc1b07dd71fe93456306bdf
[ "BSL-1.0", "LicenseRef-scancode-proprietary-license" ]
permissive
quinoacomputing/Boost
59d1dc5ce41f94bbd9575a5f5d7a05e2b0c957bf
8b552d32489ff6a236bc21a5cf2c83a2b933e8f1
refs/heads/master
2023-07-13T08:03:53.949858
2023-06-28T20:18:05
2023-06-28T20:18:05
38,334,936
0
0
BSL-1.0
2018-04-02T14:17:23
2015-06-30T21:50:37
C++
UTF-8
C++
false
false
840
cpp
// This file was automatically generated on Wed Mar 3 12:23:03 2021 // by libs/config/tools/generate.cpp // Copyright John Maddock 2002-4. // 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) // See http://www.boost.org/libs/config for the most recent version.// // Revision $Id$ // #ifdef __has_include #if __has_include(<version>) #include <version> #endif #endif #include <type_traits> #ifndef __cpp_lib_transformation_trait_aliases #error "Macro << __cpp_lib_transformation_trait_aliases is not set" #endif #if __cpp_lib_transformation_trait_aliases < 201304 #error "Macro __cpp_lib_transformation_trait_aliases had too low a value" #endif int main( int, char *[] ) { return 0; }
[ "apandare@lanl.gov" ]
apandare@lanl.gov
c74f7e5064d2cb0f7572438a9f77b23f226c102c
21e3798e9412ab53811242df51f139d0e62495d5
/examples/1. Iris Classifier/sketch/Eloquent_irisClassifier/Eloquent_irisClassifier.ino
545dbd8f566b469cf424b5b69a6c0122dad3630f
[]
no_license
KU-KOREA/ArduinoMicroML
72ac1615f6fd3fef552d6f16230cc53b4db6b29d
ef554b3ea85f97398567b1cb7c295db8c06eb6db
refs/heads/main
2023-05-26T20:14:36.273372
2021-06-19T04:05:20
2021-06-19T04:05:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
526
ino
#include "model.h" Eloquent::ML::Port::RandomForest classifier; void setup() { Serial.begin(115200); } void loop() { if (Serial.available()) { float features[4]; for (int i = 0; i < 4; i++) { // split features on comma (,) String feature = Serial.readStringUntil(','); features[i] = atof(feature.c_str()); } Serial.print("Detected species: "); Serial.println(classifier.predictLabel(features)); } delay(10); }
[ "noreply@github.com" ]
KU-KOREA.noreply@github.com
ef276fdc3383e673fb992cff9a70b85cfe1e8266
6dacb8f59751c9647685d4b931b2cbef00fcd302
/InterviewPrep/Array _ Strings/majorityElement.cpp
9e67681a83f24553bcbd6048b7e2e4fefae7ecdc
[]
no_license
sudhanshu-t/DSA
88662429514509c3a063d7610db3d32a6854c5c0
042fad26085405f77f159eb08c53555de9fb7732
refs/heads/master
2021-07-19T15:26:34.310444
2020-07-09T11:59:41
2020-07-09T11:59:41
278,350,018
0
0
null
null
null
null
UTF-8
C++
false
false
818
cpp
#include<iostream> #include<vector> using namespace std; int majorityElement(vector<int>& nums) { //Write your code here int pot = nums[0]; int count = 1; for(int i = 1; i < nums.size(); i++){ if(nums[i] != pot){ count--; if(count == 0){ count = 1; pot = nums[i]; } } else { count++; } } count = 0; for(int i = 0; i < nums.size(); i++){ if(nums[i] == pot){ count++; } } if(count > nums.size() / 2){ return pot; } else { return -1; } } int main(int argc,char**argv){ int n; cin>>n; vector<int> v(n); for(int i=0;i<n;i++){ cin>>v[i]; } int res=majorityElement(v); cout<<res<<endl; }
[ "sudhanshu21.st@gmail.com" ]
sudhanshu21.st@gmail.com
a5e8e0bedde0a13d9457445cb670f84bcd30b5e3
4eda5347b1915958143b53d020e43f563372d296
/第4章/Single/Single/MainFrm.cpp
1e2bfa8aafc943bb0b497438eb4817360d980424
[]
no_license
natsuki-Uzu/Windows_Program
40e4380e7d08f764051104a4bbcc99e9b4ff387c
a994ffaa3174e83a7d69f2c7015dac930312afaf
refs/heads/master
2023-04-26T15:53:39.205163
2012-07-31T06:21:23
2012-07-31T06:21:23
null
0
0
null
null
null
null
GB18030
C++
false
false
1,885
cpp
// MainFrm.cpp : CMainFrame 类的实现 // #include "stdafx.h" #include "Single.h" #include "MainFrm.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CMainFrame IMPLEMENT_DYNCREATE(CMainFrame, CFrameWnd) BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd) ON_WM_CREATE() END_MESSAGE_MAP() static UINT indicators[] = { ID_SEPARATOR, // 状态行指示器 ID_INDICATOR_CAPS, ID_INDICATOR_NUM, ID_INDICATOR_SCRL, }; // CMainFrame 构造/析构 CMainFrame::CMainFrame() { // TODO: 在此添加成员初始化代码 } CMainFrame::~CMainFrame() { } int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CFrameWnd::OnCreate(lpCreateStruct) == -1) return -1; if (!m_wndToolBar.CreateEx(this, TBSTYLE_FLAT, WS_CHILD | WS_VISIBLE | CBRS_TOP | CBRS_GRIPPER | CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC) || !m_wndToolBar.LoadToolBar(IDR_MAINFRAME)) { TRACE0("未能创建工具栏\n"); return -1; // 未能创建 } if (!m_wndStatusBar.Create(this) || !m_wndStatusBar.SetIndicators(indicators, sizeof(indicators)/sizeof(UINT))) { TRACE0("未能创建状态栏\n"); return -1; // 未能创建 } // TODO: 如果不需要工具栏可停靠,则删除这三行 m_wndToolBar.EnableDocking(CBRS_ALIGN_ANY); EnableDocking(CBRS_ALIGN_ANY); DockControlBar(&m_wndToolBar); return 0; } BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs) { if( !CFrameWnd::PreCreateWindow(cs) ) return FALSE; // TODO: 在此处通过修改 // CREATESTRUCT cs 来修改窗口类或样式 return TRUE; } // CMainFrame 诊断 #ifdef _DEBUG void CMainFrame::AssertValid() const { CFrameWnd::AssertValid(); } void CMainFrame::Dump(CDumpContext& dc) const { CFrameWnd::Dump(dc); } #endif //_DEBUG // CMainFrame 消息处理程序
[ "Administrator@PRC-20120724DKO.(none)" ]
Administrator@PRC-20120724DKO.(none)
584ef20053e71b2c35bb71683823364f4530998b
0f7a4119185aff6f48907e8a5b2666d91a47c56b
/sstd_utility/windows_boost/boost/interprocess/sync/shm/named_condition_any.hpp
a6fb7baff67d5d57e202696cddb8a65bc2de84b4
[]
no_license
jixhua/QQmlQuickBook
6636c77e9553a86f09cd59a2e89a83eaa9f153b6
782799ec3426291be0b0a2e37dc3e209006f0415
refs/heads/master
2021-09-28T13:02:48.880908
2018-11-17T10:43:47
2018-11-17T10:43:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,511
hpp
////////////////////////////////////////////////////////////////////////////// // // (C) Copyright Ion Gaztanaga 2005-2012. 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) // // See http://www.boost.org/libs/interprocess for documentation. // ////////////////////////////////////////////////////////////////////////////// #ifndef BOOST_INTERPROCESS_SHM_NAMED_CONDITION_ANY_HPP #define BOOST_INTERPROCESS_SHM_NAMED_CONDITION_ANY_HPP #ifndef BOOST_CONFIG_HPP # include <boost/config.hpp> #endif # #if defined(BOOST_HAS_PRAGMA_ONCE) # pragma once #endif #include <boost/interprocess/detail/config_begin.hpp> #include <boost/interprocess/detail/workaround.hpp> #include <boost/static_assert.hpp> #include <boost/interprocess/detail/type_traits.hpp> #include <boost/interprocess/creation_tags.hpp> #include <boost/interprocess/exceptions.hpp> #include <boost/interprocess/shared_memory_object.hpp> #include <boost/interprocess/sync/interprocess_condition.hpp> #include <boost/interprocess/detail/managed_open_or_create_impl.hpp> #include <boost/interprocess/detail/posix_time_types_wrk.hpp> #include <boost/interprocess/sync/shm/named_creation_functor.hpp> #include <boost/interprocess/sync/named_mutex.hpp> #include <boost/interprocess/permissions.hpp> #include <boost/interprocess/sync/interprocess_mutex.hpp> #include <boost/interprocess/sync/scoped_lock.hpp> #include <boost/interprocess/sync/detail/condition_any_algorithm.hpp> //!\file //!Describes process-shared variables interprocess_condition class namespace boost { namespace interprocess { namespace ipcdetail { #if !defined(BOOST_INTERPROCESS_DOXYGEN_INVOKED) class interprocess_tester; #endif //#ifndef BOOST_INTERPROCESS_DOXYGEN_INVOKED //! A global condition variable that can be created by name. //! This condition variable is designed to work with named_mutex and //! can't be placed in shared memory or memory mapped files. class shm_named_condition_any { #if !defined(BOOST_INTERPROCESS_DOXYGEN_INVOKED) //Non-copyable shm_named_condition_any(); shm_named_condition_any(const shm_named_condition_any &); shm_named_condition_any &operator=(const shm_named_condition_any &); #endif //#ifndef BOOST_INTERPROCESS_DOXYGEN_INVOKED public: //!Creates a global condition with a name. //!If the condition can't be created throws interprocess_exception shm_named_condition_any(create_only_t create_only, const char *name, const permissions &perm = permissions()) : m_shmem (create_only ,name ,sizeof(internal_condition) + open_create_impl_t::ManagedOpenOrCreateUserOffset ,read_write ,0 ,construct_func_t(DoCreate) ,perm) {} //!Opens or creates a global condition with a name. //!If the condition is created, this call is equivalent to //!shm_named_condition_any(create_only_t, ... ) //!If the condition is already created, this call is equivalent //!shm_named_condition_any(open_only_t, ... ) //!Does not throw shm_named_condition_any(open_or_create_t open_or_create, const char *name, const permissions &perm = permissions()) : m_shmem (open_or_create ,name ,sizeof(internal_condition) + open_create_impl_t::ManagedOpenOrCreateUserOffset ,read_write ,0 ,construct_func_t(DoOpenOrCreate) ,perm) {} //!Opens a global condition with a name if that condition is previously //!created. If it is not previously created this function throws //!interprocess_exception. shm_named_condition_any(open_only_t open_only, const char *name) : m_shmem (open_only ,name ,read_write ,0 ,construct_func_t(DoOpen)) {} //!Destroys *this and indicates that the calling process is finished using //!the resource. The destructor function will deallocate //!any system resources allocated by the system for use by this process for //!this resource. The resource can still be opened again calling //!the open constructor overload. To erase the resource from the system //!use remove(). ~shm_named_condition_any() {} //!If there is a thread waiting on *this, change that //!thread's state to ready. Otherwise there is no effect.*/ void notify_one() { m_cond.notify_one(); } //!Change the state of all threads waiting on *this to ready. //!If there are no waiting threads, notify_all() has no effect. void notify_all() { m_cond.notify_all(); } //!Releases the lock on the named_mutex object associated with lock, blocks //!the current thread of execution until readied by a call to //!this->notify_one() or this->notify_all(), and then reacquires the lock. template <typename L> void wait(L& lock) { m_cond.wait(lock); } //!The same as: //!while (!pred()) wait(lock) template <typename L, typename Pr> void wait(L& lock, Pr pred) { m_cond.wait(lock, pred); } //!Releases the lock on the named_mutex object associated with lock, blocks //!the current thread of execution until readied by a call to //!this->notify_one() or this->notify_all(), or until time abs_time is reached, //!and then reacquires the lock. //!Returns: false if time abs_time is reached, otherwise true. template <typename L> bool timed_wait(L& lock, const boost::posix_time::ptime &abs_time) { return m_cond.timed_wait(lock, abs_time); } //!The same as: while (!pred()) { //! if (!timed_wait(lock, abs_time)) return pred(); //! } return true; template <typename L, typename Pr> bool timed_wait(L& lock, const boost::posix_time::ptime &abs_time, Pr pred) { return m_cond.timed_wait(lock, abs_time, pred); } //!Erases a named condition from the system. //!Returns false on error. Never throws. static bool remove(const char *name) { return shared_memory_object::remove(name); } #if !defined(BOOST_INTERPROCESS_DOXYGEN_INVOKED) private: class internal_condition_members { public: typedef interprocess_mutex mutex_type; typedef interprocess_condition condvar_type; condvar_type& get_condvar() { return m_cond; } mutex_type& get_mutex() { return m_mtx; } private: mutex_type m_mtx; condvar_type m_cond; }; typedef ipcdetail::condition_any_wrapper<internal_condition_members> internal_condition; internal_condition m_cond; friend class boost::interprocess::ipcdetail::interprocess_tester; void dont_close_on_destruction() { interprocess_tester::dont_close_on_destruction(m_shmem); } typedef ipcdetail::managed_open_or_create_impl<shared_memory_object, 0, true, false> open_create_impl_t; open_create_impl_t m_shmem; template <class T, class Arg> friend class boost::interprocess::ipcdetail::named_creation_functor; typedef boost::interprocess::ipcdetail::named_creation_functor<internal_condition> construct_func_t; #endif //#ifndef BOOST_INTERPROCESS_DOXYGEN_INVOKED }; } //namespace ipcdetail } //namespace interprocess } //namespace boost #include <boost/interprocess/detail/config_end.hpp> #endif // BOOST_INTERPROCESS_SHM_NAMED_CONDITION_ANY_HPP
[ "nanguazhude@vip.qq.com" ]
nanguazhude@vip.qq.com
032c598bddf5520f276318d74a5fb571923dfba1
2906f1a8466c359cada4f2f9ec31c2b24e7c524d
/MIlestone 3/Client/Pkt_Def.h
aa8648d6744ad5de1fd04a856f84351b608acc01
[]
no_license
Minashed/Robot-Controller
7ff60d96d32183f1d9cb201c2ebeeb323f2259b9
01341727aa026333c7c8945274175df1a34b81b3
refs/heads/master
2021-05-05T01:12:00.705226
2018-01-31T05:14:48
2018-01-31T05:14:48
119,632,088
0
0
null
null
null
null
UTF-8
C++
false
false
2,281
h
#ifndef PKTDEF_H #define PKTDEF_H #include <iostream> #include <iomanip> #include <stdio.h> //Globally defined variables #define FORWARD 1 #define BACKWARD 2 #define LEFT 3 #define RIGHT 4 #define UP 5 #define DOWN 6 #define OPEN 7 #define CLOSE 8 //Size of the entire header varies in size #define HEADERSIZE 6 //Enum for flags enum CmdType { DRIVE, STATUS, SLEEP, ARM, CLAW, ACK, NACK}; // 0 1 2 3 4 //Header Struct struct Header { unsigned int PktCount; // 4Bytes 0 unsigned char Drive : 1; unsigned char Status : 1; unsigned char Sleep : 1; unsigned char Arm : 1; unsigned char Claw : 1; unsigned char Ack : 1; unsigned char Padding : 2; // 5Bytes 5 unsigned char Length; //6 Bytes }; //Body Struct struct MotorBody { unsigned char Direction; unsigned char Duration; }; //Telemery Body struct TelBody { unsigned short int Sonar; unsigned short int Arm; unsigned char DriveF : 1; unsigned char ArmUp : 1; unsigned char ArmDown : 1; unsigned char ClawOpen : 1; unsigned char ClawClosed : 1; unsigned char Padding : 3; }; //MAIN CLASS class PktDef { private: struct CmdPacket { Header header; // 6 Bytes char* Data; // 1or2 Bytes? char CRC;// 1 Bytes } CP; // 8 Bytes 9 Bytes? char* RawBuffer; public: //Constructors PktDef(); PktDef(char*); //Setters void SetCmd(CmdType); void SetBodyData(char*, int); void SetPktCount(int); //Getters CmdType GetCmd(); bool GetStatus(); bool GetAck(); int GetLength(); char* GetBodyData(); int GetPktCount(); //a function that takes a pointer to a RAW data buffer, the //size of the buffer in bytes, and calculates the CRC.If the calculated CRC matches the //CRC of the packet in the buffer the function returns TRUE, otherwise FALSE bool CheckCRC(char*, int); //a function that calculates the CRC and sets the objects packet CRC parameter. void CalcCRC(); //a function that allocates the private RawBuffer and transfers the //contents from the objects member variables into a RAW data packet(RawBuffer) for //transmission.The address of the allocated RawBuffer is returned. char* GenPacket(); /* std::string GetCmdStr(); int GetBitsSet(char* pktBuffer); friend std::ostream& operator<<(std::ostream& os, PktDef&); */ }; #endif
[ "mmnashed@myseneca.ca" ]
mmnashed@myseneca.ca
48b34cb562f9847543db971846a85f3646ff984d
1e1b3f702bdf6c0544ae27a321c8ebe605434ee4
/Chapter13/Sample304/UDPSever/StdAfx.cpp
99b68b873f69041b2bf35eadaa8c10b1bcea4c53
[]
no_license
Aque1228556367/Visual_Cpp_By_Example
63e3d67e734b7d95385a329e4a1641e7b1727084
41f903d8c9938e7800d89fcff31b182bfc1c4f45
refs/heads/master
2021-03-12T20:36:56.780300
2015-05-08T02:05:46
2015-05-08T02:05:46
35,171,152
2
2
null
null
null
null
UTF-8
C++
false
false
202
cpp
// stdafx.cpp : source file that includes just the standard includes // UDPSever.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h"
[ "1228556367@qq.com" ]
1228556367@qq.com
ac0c7cb82a86670c60e7f6ec3594b902109ec037
f8cdebfd3bb24190e288eda5ec66401a61e9f38d
/exercise_inschool/getLocalLessIndex/getLocalLessIndex.cpp
2e3cbdb4e90e478149f4b1a2583b7a8380fd20e0
[]
no_license
woaishixiaoxiao/algorithm
fd617d7cf8a5d65c5c14df325e99fd8a62fe4165
e9268975d08d48f3607eeb80e53ca4710b47c9cc
refs/heads/master
2020-04-23T21:23:06.390335
2019-07-21T09:38:32
2019-07-21T09:38:32
171,468,927
1
0
null
null
null
null
GB18030
C++
false
false
1,951
cpp
//定义局部最小的概念。arr长度为1时,arr[0]是局部最小。arr的长度为N(N>1)时,如果arr[0]<arr[1],那么arr[0]是局部最小; //如果arr[N-1]<arr[N-2],那么arr[N-1]是局部最小;如果0<i<N-1,既有arr[i]<arr[i-1]又有arr[i]<arr[i+1],那么arr[i]是局部最小。 //给定无序数组arr,已知arr中任意两个相邻的数都不相等,写一个函数,只需返回arr中任意一个局部最小出现的位置即可。 //解释下为什么第二个数比第一个数小,最后一个数比倒数第二个大,那么就一定会有一个局部最小值 //因为相邻的两个是不相等的,所以相邻三个数的关系,就有这么几种情况,一直降,一直升,先将后升,先升后降, //因为最开始的两个数的趋势是下降,从最后到倒数第二个数的趋势也是下降,反正自己画画也能画出来,不要纠结 //最后结论就是只要两头的趋势都是下降,那么中间必有一个,如果两头有一个不是这样的,那答案就直接有了,所以这道题,一定有解 #include<iostream> #include<vector> using namespace std; bool getLocalLessIndex(vector<int>&ivec,int &pos){ if(ivec.empty())return false; int beg=0; int end=ivec.size()-1; int mid; if(ivec.size()==1||ivec[beg]<ivec[beg+1]){ pos=beg; return true; }else{ if(ivec[end]<ivec[end-1]){ pos=end; return true; } } while(beg<end){//这个里面不用再去判断13-20的那个内容,因为你只要确定了解一定在这个区间范围内就可以了,进而把区间范围减小就行了 mid=(beg+end)/2; if(ivec[mid]>ivec[mid-1]){ end=mid-1; }else{ if(ivec[mid]>ivec[mid+1]){ beg=mid+1; }else{ pos=mid; return true; } } } return beg; //这里返回什么都无所谓,因为上面是一定有解得 } main(){ vector<int>ivec={}; int pos; if(getLocalLessIndex(ivec,pos)){ cout<<pos<<endl; } }
[ "823124073@qq.com" ]
823124073@qq.com
ce1b5a66e31a227f43329fbd78b19bc8ceef6460
b32200d629373216e32fb3423d7c8b3f1d28938d
/RetroSnaker_Colourso/RetroSnaker_0.3/贪吃蛇第三版/Snake.cpp
431a0e706fec50625c671c5517b70eeecfb10bc0
[]
no_license
Colourso/Simple-CPP-project-by-Colourso
3a655cf238960ffad85e338ae63e3270e0fe7e0d
36e22c6ec851bc695bd03c5939695e4afbbc0f39
refs/heads/master
2022-11-23T22:11:50.381102
2020-08-05T04:00:25
2020-08-05T04:00:25
268,247,781
1
1
null
null
null
null
GB18030
C++
false
false
4,176
cpp
#include "Snake.h" #include <stdio.h> #include <ctime> #include <graphics.h> Snake::Snake() { Point pos0(210, 230); Point pos1(190, 230); Point pos2(170, 230); this->m_snakelist.push_back(pos0); this->m_snakelist.push_back(pos1); this->m_snakelist.push_back(pos2); this->m_direction = Dir::DIR_RIGHT; this->m_len = 3; this->m_speed = this->OrgSpeed; } int Snake::getLen() { return this->m_len; } int Snake::getSpeed() { return this->m_speed; } Dir Snake::getDirection() { return this->m_direction; } bool Snake::setSpeed(int speed) { if (speed > this->MaxSpeed) { if (this->m_speed != this->MaxSpeed) { this->m_speed = this->MaxSpeed; return true; } return false; } else if (speed < this->MinSpeed) { if (this->m_speed != this->MinSpeed) { this->m_speed = this->MinSpeed; return true; } return false; } else { this->m_speed = speed; return true; } } void Snake::Move() { this->m_tail = this->m_snakelist.back(); //移除最后一个节点,复制第一个节点两份 this->m_snakelist.pop_back(); Point headPos = this->m_snakelist.front(); this->m_snakelist.push_front(headPos); switch (this->m_direction) { case Dir::DIR_UP: this->m_snakelist.begin()->y -= SNAKE_WIDTH; break; case Dir::DIR_RIGHT: this->m_snakelist.begin()->x += SNAKE_WIDTH; break; case Dir::DIR_DOWN: this->m_snakelist.begin()->y += SNAKE_WIDTH; break; case Dir::DIR_LEFT: this->m_snakelist.begin()->x -= SNAKE_WIDTH; break; } } void Snake::EatFood() { //吃到食物尾部增长 this->m_snakelist.push_back(this->m_tail); this->m_len += 1; } void Snake::ChangeDir(Dir dir) { switch (dir) { case Dir::DIR_UP: case Dir::DIR_DOWN: if (m_direction != Dir::DIR_UP && m_direction != Dir::DIR_DOWN) { m_direction = dir; } break; case Dir::DIR_RIGHT: case Dir::DIR_LEFT: if (m_direction != Dir::DIR_RIGHT && m_direction != Dir::DIR_LEFT) { m_direction = dir; } break; } } void Snake::Dead() { //TODO int x = 0; int y = 0; //x、y表示坐标的该变量 int z = 0; //z表示改变方向 //使用随机函数 srand(time(0)); std::list<Point>::iterator it = this->m_snakelist.begin(); for (; it != this->m_snakelist.end(); ++it) { x = (rand() % 4) * SNAKE_WIDTH; y = (rand() % 4) * SNAKE_WIDTH; z = (rand() % 8); switch (z) { case 0: //右 (*it).x += x; break; case 1: //下 (*it).y += y; break; case 2: //左 (*it).x -= x; break; case 3: //上 (*it).y -= y; break; case 4: //右下 (*it).x += x; (*it).y += y; break; case 5: //左下 (*it).x -= x; (*it).y += y; break; case 6: //左上 (*it).x -= x; (*it).y -= y; break; case 7: //右上 (*it).x += x; (*it).y -= y; break; } } } bool Snake::ColideWall(int left, int top, int right, int bottom) { int x = this->m_snakelist.front().x; int y = this->m_snakelist.front().y; return (x < left || x > right || y < top || y > bottom); } bool Snake::ColideSnake() { if (m_len <= 3) return false; std::list<Point>::iterator it = this->m_snakelist.begin(); Point pos = *it; Point next_pos; it++; while(it != this->m_snakelist.end()) { next_pos = *it; if (pos == next_pos) { return true; } it++; } return false; } bool Snake::ColideFood(Point point) { if (this->m_snakelist.front() == point) { return true; } return false; } void Snake::DrawSnake() { std::list<Point>::iterator it = this->m_snakelist.begin(); for (; it != this->m_snakelist.end(); ++it) { DrawSnakeNode(*it); } DrawSnakeHead(this->m_snakelist.front()); } void Snake::DrawSnakeHead(Point pos) { //紫色,全填充,无边框的正方形 setfillcolor(0xAA00AA); setfillstyle(BS_SOLID); solidrectangle(pos.x - SNAKE_RADIU, pos.y + SNAKE_RADIU, pos.x + SNAKE_RADIU, pos.y - SNAKE_RADIU); } void Snake::DrawSnakeNode(Point pos) { //绿色,全填充,无边框的正方形 setfillcolor(GREEN); setfillstyle(BS_SOLID); solidrectangle(pos.x - SNAKE_RADIU, pos.y + SNAKE_RADIU, pos.x + SNAKE_RADIU, pos.y - SNAKE_RADIU); } std::list<Point> Snake::GetSnakeAllNode() { return this->m_snakelist; }
[ "colourso@outlook.com" ]
colourso@outlook.com
f7c1884f38483346d75894e4496b4bde7bb12bc8
d757d87bfb845a578a92afa272e24abdaf2126dd
/support.cpp
8d3961089b94f3e5378337affef267db710b3ec2
[]
no_license
astachey/cs302
b5f9637010fd2e815e034417134f32b82b0a56a6
2998ce7d2f12ce30644d2f442b345efe2eb2cde5
refs/heads/master
2020-05-20T00:40:51.130783
2014-02-06T05:13:37
2014-02-06T05:13:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,580
cpp
// header files #include <cmath> #include "support.h" using namespace std; //RGB::RGB(uchar _R = 0, uchar _G= 0, uchar _B = 0){ // R = _R; // G = _G; // B = _B; // return; //}/ // RGB::operator<() // RGB::distance() double RGB::distance(const RGB& next){ double dist = sqrt(pow((double)R - next.R, 2)) + (pow((double)G - next.G, 2))+(pow((double)B - next.B, 2)); } RGB RGB::quantize(const int &Q){ RGB tmp; tmp.R = Q*(R/Q); tmp.G = Q*(G/Q); tmp.B = Q*(B/Q); return tmp; } PPM::PPM() { magicid = "P6"; nrows = 0; ncols = 0; maxvalue = 255; } PPM::~PPM() { } void PPM::read(const string & fname) { ifstream fin; if(fname.substr(fname.find_last_of(".")+1) == "ppm"){ fin.open(fname.c_str()); if(!fin.is_open()){ cerr << "Unable to open file."<<endl; } } else{ cerr << "Invalid file name." <<endl; exit (1); } // extract suffix: must be ppm // open fname: check status string magicid; int nrows, ncols, maxval; fin >> magicid >> nrows >> ncols >> maxvalue; if (magicid!= "P6"){ cerr << "Magic Number for ppm file is not P6. Exiting. " << endl; exit(1); } // read magicid: must be P6 // read ncols, nrows: check status // read maxvalue: must be 255 if (maxvalue != 255){ cerr << "Max value does not equal 255. "<< endl; exit(1); } int npixels = (ncols*nrows); int nbytes = 3 * npixels; img.assign(nbytes, RGB()); // allocate space for 3*npixels in img vector // read 3*npixels bytes into img: check status if(img.size()!=nbytes){ cerr<< "Error creating image vector. Exiting."<<endl; exit(1); } fin.read((char* ) img.data(), nbytes); // close input file fin.close(); } void PPM::write(const string & fname) { // open fname: check status ofstream fout; fout.open( fname.c_str()); if(!fout.is_open()){ cerr << "Unable to open output file. Exiting."<<endl; exit (1); } // write header fout << magicid << endl << ncols << " " << nrows << endl << maxvalue << endl; int npixels = ncols*nrows; // write 3*npixels from img vector int nbytes = 3 * npixels; fout.write(( char* ) img.data(), nbytes); // close output file fout.close(); } void PPM::write(const string & fname, const string & addon) { // new_fname: image.ppm -> image_addon.ppm string noext = fname.substr(0, fname.size() - 4); string newfile = noext + "_" + addon + ".ppm"; // call write(new_fname); write(newfile); return; } void PPM::process(pmode_t pmode, const string &fname) { // read qcolors in fname //int _R, _G, _B; //ifstream colsin; //colsin.open(fname.c_str()); //if(!colsin.is_open()){ // cerr << "Could not open filename to process. Exiting now."<<endl; // } // while ( colsin ) { // qcolors.push_back(RGB()); // while (colsin.get()!= '\n' && !colsin.eof()) {} // } // colsin.close(); read_qcolors(fname); // run proper process mode if( pmode == run_process1){ process1(); } else if(pmode == run_process2){ process2(); } else{ cerr<< "No valid process to run. Exiting now." << endl; exit(1); } return; } void PPM::process1() { // for each pixel { for( int i = 0; i < img.size(); i++){ map<int, RGB> colormap; // find closest qcolor for( int j = 0; j< colormap.size(); j++){ // set pixel color to closest qcolor colormap.insert( pair< int, RGB >( img[i].distance ( colormap[j]), colormap[j])); } img[i] = colormap.begin() -> second; } // } } void PPM::process2() { // for each pixel { vector<map<int, RGB> > histo(qcolors.size()); map< int, float> qmap; map< int, float> :: iterator iqmap; for( int i = 0; i < img.size(); i++){ map<int, RGB> colormap; // find closest qcolor for( int j = 0; j< colormap.size(); j++){ qmap[j] = img[i].distance(qcolors[j]); } iqmap = min_element(qmap.begin(), qmap.end()); // update qcolor histogram of pixel color/8 counts RGB tmp; tmp = img[i].quantize(8); // save closest qcolor index //for (int i; i < iqmap.size(); i++){ // if (iqmap[i]==histo[i]){ // iqmap->second++; // } // else{ // histo[iqmap -> first].insert (tmp,1); // } // } // // for each qcolor { // find highest count pixel value/8 // replace qcolor with highest count pixel value/8 // } // // for each pixel { // set pixel color to qcolor[closest qcolor index] // } } } void PPM::read_qcolors(const string &fname) { // open fname: check status RGB tmp; ifstream fin; fin.open(fname.c_str()); if(!fin.is_open()){ cerr<< "Unable to open file. Exiting."<< endl; exit(1); } int r, g, b; string buffer; // // while (more data0 { // read R G B values fin >> r >> g >> b >> buffer >> buffer; while(fin){ tmp.R = r; tmp.G = g; tmp.B = b; // save to qcolors vector qcolors.push_back (tmp); fin >> r >> g >> b >> buffer >> buffer; } // } // // close input file fin.close(); }
[ "astachey@utk.edu" ]
astachey@utk.edu
9b63b4da7f2128aae31f22d53696933b3cdcf8f4
077e2cb43a4435e6bad1db626ccfbec18bd0b3a8
/R1/Week2/xymodn.cpp
a9c7e07eb62cfefadef2ce993dae1c91a0ee3c31
[]
no_license
peter0749/581_Homeworks
e57a4bdac33275c6617286d87009744b94b9be87
f9394c8a71f4eb5991b78f22f4126dc1da94f46e
refs/heads/master
2021-01-18T18:42:21.000721
2017-03-25T07:09:02
2017-03-25T07:09:02
52,514,761
0
0
null
null
null
null
UTF-8
C++
false
false
815
cpp
#include <iostream> #include <iomanip> #include <string> #define MAX 100001 using namespace std; int digit[MAX] = {0}; int book[MAX] = {0}; int modN(int x,long long int y, int N) { long long int i, base(1); if(x==0) return 0; if(y==0) return 1; //getch();cout<<"ok"<<endl; for(i=0;i<N;i++) book[i]=0; //x%=N; for(i=1; i<=y;i++) { base = (base*x)%N; //cout<<base<<endl; if(book[base]!=0) break; book[base] = i; digit[i] = base; } if(i>y) { return base; } //return -1; return digit[book[base]+(y-i)%(i-book[base])]; } int main(void) { int x, N; int term; long long int y; cin>>term; while(term--) { cin>>x>>y>>N; cout<<modN(x,y,N)<<"\n"; } return 0; }
[ "jengku@gmail.com" ]
jengku@gmail.com
48907d779a89ed7c748a9d4ff41c98ed4f0ba65d
60c275f5670d8a509421dbe53a704cdf85289035
/CodeForces/1452B_Toy_Blocks/B_Toy_Blocks.cpp
e50ef640939c244363943ff72f0e25926d8cb409
[ "MIT" ]
permissive
Cutyroach/Solve_Algorithms
f02f03c5ad146550b136e19292a3599b2eff6702
97d9f8bb65055fe5ad62d108a9359b91f0f40c49
refs/heads/master
2023-03-02T21:27:03.214056
2021-02-09T23:58:47
2021-02-09T23:58:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
693
cpp
#include <bits/stdc++.h> using namespace std; int main() { // freopen("input.txt", "r", stdin); ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr); int t; for (cin >> t; t--; ) { int tc; cin >> tc; vector<long long> v(tc); long long max_v = 0, sum = 0; for (int i = 0; i < tc; i++) { cin >> v[i]; sum += v[i]; max_v = max(max_v, v[i]); } long long ans = 0; if (!(sum % (tc - 1))) ans = sum; else ans = sum - sum % (tc - 1) + tc - 1; if (ans < max_v * (tc - 1)) ans = max_v * (tc - 1); cout << ans - sum << '\n'; } return 0; }
[ "spe0678@gmail.com" ]
spe0678@gmail.com
03d77bb0895547892650409cd1fba89b3c0441ec
c21c8cba94f4f73aa23de98e555ef77bcab494f0
/SPOJ/CAPCITY.cpp
e0ca9336e68a8cd8dd0151258090777efa0632a4
[]
no_license
hoatd/Ds-Algos-
fc3ed0c8c1b285fb558f53eeeaea2632e0ed03ae
1e74995433685f32ce75a036cd82460605024c49
refs/heads/master
2023-03-19T05:48:42.595330
2019-04-29T06:20:43
2019-04-29T06:20:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,120
cpp
#include <bits/stdc++.h> #define mp make_pair #define ll long long #define pb push_back #define ss second #define ff first #define si(x) scanf("%d",&x) #define slli(x) scanf("%lld",&x) #define pi(x) printf("%d",x) #define mx5 100005 #define mx6 1000006 #define mod 1000000007 #define rep(i,n) for(int i=0; i<n; i++) #define fast std::ios::sync_with_stdio(false) #define gc() getchar() #define pc(x) putchar(x) using namespace std; typedef pair<int,int> pii; // special value of infinity to take for getting rid of overflows const int inf = 0x3f3f3f3f; /******************* Problem Code *****************/ vector<int> graph[100005]; vector<int> rev[100005]; bool vis[100005]; int ans[100005],comp[100005]; bool has[100005]; int n,m; void dfs1( int u, stack<int>& st ) { vis[u] = true; for(int i=0; i < graph[u].size(); i++) { int to = graph[u][i]; if(vis[to] == false){ dfs1(to, st); } } st.push(u); } void dfs2( int u, int co ) { vis[u] = false; comp[u] = co; for(int i=0; i < rev[u].size(); i++){ int to = rev[u][i]; if(vis[to] == true) { dfs2(to, co); } } } /** top_sort bool top_sort() { memset(vis, false, sizeof(vis)); queue<int> q; for(int i=1; i <= n; i++) { if(indegree[i] == 0) { q.push(i); } } while( !q.empty() ) { int to = q.front(); q.pop(); vis[to] = true; for(int i=0; i < graph[to].size(); i++) { int po=graph[to][i]; indegree[po]--; if(indegree[po] == 0){ q.push(po); } } } for(int i=1; i<=n; i++) { if(vis[i] == false) { } } } **/ int main() { int a , b; while(1) { cin>>n; if( n == 0 ) break; cin>>m; for(int i=1; i<=n; i++) { graph[i].clear(); rev[i].clear(); vis[i]=false; has[i]=false; comp[i]=0; } for(int i=0; i < m; i++) { cin>>a>>b; graph[a].push_back(b); rev[b].push_back(a); } stack<int> st; for(int i=1; i <= n; i++) { if(vis[i] == false) { dfs1(i, st); } } int co = 0; while( !st.empty() ) { int to = st.top(); st.pop(); if( vis[to] == true ) { co++; dfs2( to, co ); has[co] = true; } } for(int i=1; i <= n; i++ ){ for(int j=0; j < graph[i].size(); ++j) { if(comp[i] != comp[graph[i][j]]) { has[ comp[i] ] = false; } } } for(int i = 1; i <= n; i++) { if( has[ comp[i] ] == true ) { cout<<i<<" "; } } cout<<endl; } return 0; }
[ "noreply@github.com" ]
hoatd.noreply@github.com
a902a5f751ab425b27a305baedef0bcc45a338d6
0c95b0e960e0c23e47c9ff953bc60f1003158470
/calculator_controller/calculator_controller.ino
176a56ce1bed445530b7e4b96a7c31ee90fe50d4
[]
no_license
kuzlab/midi_controller_pj
f1a5805de7e56d81fa643e0c567504bf6e300ed2
92612ba747f628e92c348d85fdcfcb7be2bed343
refs/heads/master
2021-01-19T21:52:20.916078
2015-05-18T18:35:04
2015-05-18T18:35:04
33,324,099
0
0
null
null
null
null
UTF-8
C++
false
false
6,519
ino
#include "assign_map.h" #define PIN0 13 #define PIN1 14 #define PIN2 15 #define PIN3 16 #define PIN4 17 #define PIN5 18 #define PIN6 19 #define PIN7 20 #define PIN8 21 #define SW0 2 #define SW1_0 0 #define SW1_1 1 #define LOOP_DELAY 30 #define SEND_MIDI_DELAY 100 //#define _DEBUG_ //#define _COMMAND_MODE_DEBUG_ int inpins[5] = { PIN0, PIN2, PIN4, PIN6, PIN8 }; int outpins[4] = { PIN1, PIN3, PIN5, PIN7, }; uint8_t switch_state[20] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; int8_t keymap[5*4] = { -1, -1, -1, DECREMENT_KEY_VALUE, INCREMENT_KEY_VALUE, -1, 9, 6, 3, SEND_KEY_VALUE, -1, 8, 5, 2, 0, -1, 7, 4, 1, CANCEL_KEY_VALUE }; #define THD 800 void print_inpins_all(){ for(int i=0;i<5;i++){ // Serial.print(digitalRead(inpins[i])); // Serial.print(' '); // Serial.print(analogRead(inpins[i])); if(analogRead(inpins[i]) > THD){ Serial.print("ON "); } else{ Serial.print("OFF"); } Serial.print('('); Serial.print(analogRead(inpins[i])); Serial.print(')'); Serial.print('\t'); } Serial.println(""); } void set_one_pin_high_other_pins_low(int pin){ for(int i=0;i<4;i++){ if(pin == outpins[i]){ digitalWrite(outpins[i], HIGH); } else{ digitalWrite(outpins[i], LOW); } } } void setup(){ Serial.begin(57600); for(int i=0;i<5;i++){ pinMode(inpins[i], INPUT); } for(int i=0;i<4;i++){ pinMode(outpins[i], OUTPUT); digitalWrite(outpins[i], LOW); } pinMode(SW0, INPUT); pinMode(SW1_0, INPUT); pinMode(SW1_1, INPUT); digitalWrite(SW0, HIGH); digitalWrite(SW1_0, HIGH); digitalWrite(SW1_1, HIGH); delay(3000); } void print_SW0(){ if(digitalRead(SW0)){ Serial.println("SW0 : OFF"); } else{ Serial.println("SW0 : ON"); } } void print_SW1(){ if(digitalRead(SW1_0)){ if(digitalRead(SW1_1)){ Serial.println("SW1 : position1"); } else{ Serial.println("SW1 : position2"); } } else{ if(digitalRead(SW1_1)){ Serial.println("SW1 : position4"); } else{ Serial.println("SW1 : position3"); } } } int8_t return_pressed_button_number() { for(uint8_t i=0;i<5;i++){ if(analogRead(inpins[i]) > THD){ return i; } } return -1; } uint8_t return_sw0_state() { if(digitalRead(SW0)){ return 1; } return 0; } uint8_t return_sw1_state(){ if(digitalRead(SW1_0)){ if(digitalRead(SW1_1)){ return 0; } else{ return 1; } } else{ if(digitalRead(SW1_1)){ return 3; } } return 2; } void send_midi(uint8_t sw0_state, uint8_t sw1_state, uint8_t num) { if(sw0_state == 1){ // kaos pad mode uint8_t first_byte = 0xb4; uint8_t second_byte = 0x00 + sw1_state * 16 + num; Serial.print('$'); Serial.print(first_byte); Serial.print(','); Serial.print(second_byte); Serial.print(','); Serial.print(127); Serial.println('%'); } else{ // command mode int temp = num%100; uint8_t first_byte = (0xb6 + (num-temp)/100)&0xff; uint8_t second_byte = 0x00 + temp; Serial.print('$'); Serial.print(first_byte); Serial.print(','); Serial.print(second_byte); Serial.print(','); Serial.print(127); Serial.println('%'); } delay(SEND_MIDI_DELAY); } int return_keynum_if_pressed(){ int8_t num = -1; int8_t res = -1; int8_t temp; for(uint8_t i=0;i<4;i++){ set_one_pin_high_other_pins_low(outpins[i]); temp = return_pressed_button_number(); #ifdef _DEBUG_ print_inpins_all(); Serial.print("pressed ["); Serial.print(i); Serial.print(" , "); Serial.print(temp); Serial.println(" ]"); #endif if(temp >= 0){ num = temp + 5*i; // Serial.println(num); if(switch_state[num] != 1){ res = num; } } #ifdef _DEBUG_ // Serial.println("------------------------------------------------------------------------------------"); Serial.print("switch_state = {"); for(uint8_t i=0;i<20;i++){ Serial.print(switch_state[i]); Serial.print(","); } Serial.println("}"); Serial.println("------------------------------------------------------------------------------------"); #endif for(uint8_t j=0;j<5;j++){ switch_state[5*i+j] = 0; } if(temp >= 0 && num >= 0){ switch_state[num] = 1; } if(res >= 0){ return res; } } return res; } uint8_t command_buff[3] = { 0, 0, 0 }; void loop(){ int num = return_keynum_if_pressed(); if(num >= 0){ #ifdef _COMMAND_MODE_DEBUG_ Serial.print("keynum = "); Serial.println(num); #endif if(return_sw0_state()){ // kaos pad mode send_midi(return_sw0_state(), return_sw1_state(), num); } else{ // command mode int8_t value = keymap[num]; #ifdef _COMMAND_MODE_DEBUG_ Serial.print("-> key value = "); Serial.println(value); #endif if(value == SEND_KEY_VALUE){ uint8_t send_num = command_buff[0] * 100 + command_buff[1] * 10 + command_buff[2]; send_midi(return_sw0_state(), return_sw1_state(), send_num); } else if(value == CANCEL_KEY_VALUE){ command_buff[0] = 0; command_buff[1] = 0; command_buff[2] = 0; } else if(value == INCREMENT_KEY_VALUE){ uint8_t temp = command_buff[0] * 100 + command_buff[1] * 10 + command_buff[2]; temp++; command_buff[2] = temp%10; temp = (temp - command_buff[2])/10; command_buff[1] = temp%10; temp = (temp - command_buff[1])/10; command_buff[0] = temp%10; } else if(value == DECREMENT_KEY_VALUE){ uint8_t temp = command_buff[0] * 100 + command_buff[1] * 10 + command_buff[2]; temp--; if(temp < 0){temp = 0;} command_buff[2] = temp%10; temp = (temp - command_buff[2])/10; command_buff[1] = temp%10; temp = (temp - command_buff[1])/10; command_buff[0] = temp%10; } else if(value >= 0){ command_buff[0] = command_buff[1]; command_buff[1] = command_buff[2]; command_buff[2] = value%10; } #ifdef _COMMAND_MODE_DEBUG_ Serial.print(command_buff[0]); Serial.print(command_buff[1]); Serial.println(command_buff[2]); #endif } } // print_SW0(); // print_SW1(); delay(LOOP_DELAY); #ifdef _DEBUG_ delay(3000); #endif }
[ "qzuryu@gmail.com" ]
qzuryu@gmail.com
ab7f4348b6906422cdcef8a1fc604842a1d25105
ef9a782df42136ec09485cbdbfa8a56512c32530
/branches/Chickens/src/building/storage.h
ac4584fe42ca340bcdc0df10f60b5f0de55068b3
[]
no_license
penghuz/main
c24ca5f2bf13b8cc1f483778e72ff6432577c83b
26d9398309eeacbf24e3c5affbfb597be1cc8cd4
refs/heads/master
2020-04-22T15:59:50.432329
2017-11-23T10:30:22
2017-11-23T10:30:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,866
h
/****************************************************************************\ $URL$ $LastChangedDate$ $LastChangedRevision$ $LastChangedBy$ \****************************************************************************/ //!Basic storage class /*!Basic storage class. Should not be instanced except in inherited form. * */ #ifndef __storage_H //Required for current class #define __storage_H #include "../base/linklist.h" #include "../products/product.h" //Required for include files #include "../products/products.h" class storage: public base { //!The capacity of the storage in appropriate units double theCapacity; //!The product stored product* theProduct; public: //!Constructor without arguments storage ();// :(); //!Constructor with arguments storage (const char* aname,const int aIndex,const base* aOwner,double aCapacity); //!Copy constructor storage(storage& aStore); //!Destructor ~ storage ( ) //Destructor { delete theProduct; } // Get and set functions for attributes //!Return the capacity of the store double GetCapacity() const {return theCapacity;} //!Set the capacity of the store void SetCapacity (double aCapacity){ theCapacity = aCapacity;} //!Return a pointer to the product stored product * GetProductPointer() const {return theProduct;}; //!Set the pointer to the product stored void SetProductPointer(product * aProduct) {theProduct = aProduct;}; //!Return amount of product stored in the appropriate units double Getamountstored(); //!Return true if the stored product is the same as the desired product /*! * \param desiredProduct the product desired * */ bool ProductCompare(const product* desiredProduct); //!Add a product to the store /*! * \param p the product to add * */ virtual void AddToStore(product * p); //!Returns an amount of product from the store /*! * \param RequestedAmount the amount requested * */ virtual product * GetFromStore(double RequestedAmount); //!Returns the name of the stored product string GiveNameStoredProduct(); //!Initialise storage details from a text file void ReadParameters(fstream * file); //!Returned a copy of a stored feed product /*! * \param feedType reference number of the feed product * */ product* GetCopyStoredFeedProduct(int feedType); //!Returned a copy of a stored feed product /*! * \param product1 the feed product to be copied * */ product* GetCopyStoredFeedProduct(const product* product1); //!Returned a pointer to the stored feed product /*! * \param feedType reference number of the feed product * */ product* GetStoredFeedProductPtr(int feedType); /*!Read default parameters * \param file pointer to file containing default information * */ void ReadDefaultParameters(fstream * file); }; #endif
[ "sai@agro.au.dk" ]
sai@agro.au.dk
e5d0a06a5f82cbd114f9c3bf94f4e206560eb637
a11d6802ccb326a4fdcdd32cda309763f732e4d8
/libs/agg23/include/agg_conv_unclose_polygon.h
a92fa45d096245bd3bd45e8f01bd67a398e3affc
[ "LicenseRef-scancode-boost-original" ]
permissive
martindafonte/eosim-fing2014
f14ab03891e4e315a657c9f94f9dcb92b3c43557
9cb9fa777d91b1b90d0c7af4c942b68ab16593b9
refs/heads/master
2021-01-01T20:42:35.068696
2014-11-17T02:04:11
2014-11-17T02:04:11
42,748,038
0
0
null
null
null
null
UTF-8
C++
false
false
1,757
h
//---------------------------------------------------------------------------- // Anti-Grain Geometry - Version 2.3 // Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com) // // Permission to copy, use, modify, sell and distribute this software // is granted provided this copyright notice appears in all copies. // This software is provided "as is" without express or implied // warranty, and with no claim as to its suitability for any purpose. // //---------------------------------------------------------------------------- // Contact: mcseem@antigrain.com // mcseemagg@yahoo.com // http://www.antigrain.com //---------------------------------------------------------------------------- #ifndef AGG_CONV_UNCLOSE_POLYGON_INCLUDED #define AGG_CONV_UNCLOSE_POLYGON_INCLUDED #include "agg_basics.h" namespace agg { //====================================================conv_unclose_polygon template<class VertexSource> class conv_unclose_polygon { public: conv_unclose_polygon(VertexSource& vs) : m_source(&vs) {} void set_source(VertexSource& source) { m_source = &source; } void rewind(unsigned path_id) { m_source->rewind(path_id); } unsigned vertex(double* x, double* y) { unsigned cmd = m_source->vertex(x, y); if(is_end_poly(cmd)) cmd &= ~path_flags_close; return cmd; } private: conv_unclose_polygon(const conv_unclose_polygon<VertexSource>&); const conv_unclose_polygon<VertexSource>& operator = (const conv_unclose_polygon<VertexSource>&); VertexSource* m_source; }; } #endif
[ "martindafonte@gmail.com" ]
martindafonte@gmail.com
475a6d9898821b03d48ee481270dd1e16251a38b
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/rsync/gumtree/rsync_patch_hunk_939.cpp
6f0fdfd187017b4ac37a51e7e0af055c85d0c226
[]
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
839
cpp
* @return a socket which is attached to a subprocess running * "prog". stdin and stdout are attached. stderr is left attached to * the original stderr **/ int sock_exec(const char *prog) { + pid_t pid; int fd[2]; if (socketpair_tcp(fd) != 0) { rsyserr(FERROR, errno, "socketpair_tcp failed"); return -1; } if (verbose >= 2) rprintf(FINFO, "Running socket program: \"%s\"\n", prog); - if (fork() == 0) { + + pid = fork(); + if (pid < 0) { + rsyserr(FERROR, errno, "fork"); + exit_cleanup(RERR_IPC); + } + + if (pid == 0) { close(fd[0]); - close(0); - close(1); - dup(fd[1]); - dup(fd[1]); + if (dup2(fd[1], STDIN_FILENO) < 0 + || dup2(fd[1], STDOUT_FILENO) < 0) { + fprintf(stderr, "Failed to run \"%s\"\n", prog); + exit(1); + } exit(system(prog)); } + close(fd[1]); return fd[0]; }
[ "993273596@qq.com" ]
993273596@qq.com
7d2f25de0cc6fe25e05f63269e71fa0b7c4b70ae
92793f5f381d7b85be8e101d1fb68f3e0e4c17b0
/example/testApp.cpp
de5d3ce1d71256c0e16bcfdb3a005ae4511f152e
[]
no_license
martinbabbels/ofxOMCS
b81c935eaf69ae325615d895c6760bb471b68728
5578a42c98e14855acf5c972b63f273bd3783287
refs/heads/master
2020-04-19T15:48:56.605805
2011-12-26T11:56:02
2011-12-26T11:56:02
2,077,631
1
0
null
null
null
null
UTF-8
C++
false
false
4,993
cpp
#include "testApp.h" //-------------------------------------------------------------- void testApp::setup(){ ofSetFrameRate(60); // Load the predicates omcsnet.loadPredicates(ofToDataPath("predicates.dat")); } //-------------------------------------------------------------- void testApp::update(){ } //-------------------------------------------------------------- void testApp::draw(){ } //-------------------------------------------------------------- void testApp::keyPressed(int key){ } //-------------------------------------------------------------- void testApp::keyReleased(int key){ // Analogous concepts if(key=='a') { string concept = "apollo"; list<AnalogousResult> r; list<AnalogousResult>::iterator result_iterator; list<AnalogousConcept> c; list<AnalogousConcept>::iterator concepts_iterator; omcsnet.findAnalogous(concept, r); printf("*************************************************\n"); printf("Analogous concepts for %s\n", concept.c_str()); printf("*************************************************\n"); result_iterator = r.begin(); while(result_iterator != r.end()) { printf("%s (%s%%) because both:\n", (*result_iterator).concept.c_str(), ofToString((int)(*result_iterator).score).c_str() ); concepts_iterator = (*result_iterator).concepts.begin(); while(concepts_iterator != (*result_iterator).concepts.end()) { printf("\t%s %s\n", (*concepts_iterator).relation.c_str(), (*concepts_iterator).concept.c_str() ); ++concepts_iterator; } printf("\n\n"); ++result_iterator; } } // Path cocept A to B if(key=='p') { string concept_a = "freak"; string concept_b = "day"; printf("*************************************************\n"); printf("Path from %s to %s\n", concept_a.c_str(), concept_b.c_str()); printf("*************************************************\n"); list<PathResults> r; list<PathResults>::iterator result_iterator; list<PathResult>::iterator path_iterator; omcsnet.findPath(concept_a, concept_b, r); result_iterator = r.begin(); while (result_iterator != r.end()) { printf("\n"); path_iterator = (*result_iterator).paths.begin(); while(path_iterator != (*result_iterator).paths.end()) { printf("%s is %s %s\n", (*path_iterator).conceptA.c_str(), (*path_iterator).relation.c_str(), (*path_iterator).conceptB.c_str() ); ++path_iterator; } ++result_iterator; } } // Context concepts if(key=='c') { string concept = "framework"; printf("*************************************************\n"); printf("Context for %s\n", concept.c_str()); printf("*************************************************\n"); list<ContextResult> r; list<ContextResult>::iterator result_iterator; omcsnet.findContext(concept, r); result_iterator = r.begin(); while(result_iterator != r.end()) { printf("%s (%s%%)\n", (*result_iterator).concept.c_str(), ofToString((*result_iterator).score).c_str() ); ++result_iterator; } } // Look up a concept if(key=='l') { string concept = "computer"; printf("*************************************************\n"); printf("Lookup concept %s\n", concept.c_str()); printf("*************************************************\n"); LookUpResult r; list<LookUpResultLinks>::iterator result_iterator; list<LookUpResultLink>::iterator concepts_iterator; omcsnet.lookUp(concept, r); printf("Forward:\n"); result_iterator = r.forward.begin(); while(result_iterator != r.forward.end()) { printf("[%s]\n", (*result_iterator).relation.c_str()); concepts_iterator = (*result_iterator).concepts.begin(); while(concepts_iterator != (*result_iterator).concepts.end()) { printf("\t%s\n", (*concepts_iterator).concept.c_str() ); ++concepts_iterator; } ++result_iterator; } printf("Backward:\n"); result_iterator = r.backward.begin(); while(result_iterator != r.backward.end()) { printf("[%s]\n", (*result_iterator).relation.c_str()); concepts_iterator = (*result_iterator).concepts.begin(); while(concepts_iterator != (*result_iterator).concepts.end()) { printf("\t%s\n", (*concepts_iterator).concept.c_str() ); ++concepts_iterator; } ++result_iterator; } } } //-------------------------------------------------------------- void testApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void testApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::windowResized(int w, int h){ }
[ "martin@apollomedia.nl" ]
martin@apollomedia.nl
4137e85f25a7e3f48a920606316533af6176a890
15b85084ba3a2d9833de12bfc3ba5d8fbca6fed7
/test.cpp
b22bed4a89814f5ad5327dd2f6b1eb7587a5701a
[]
no_license
kryczko/water_simulation_data
52f5d81580f0a4fca71fa701be3f1ec272c6b77b
47e1e98545df69efcec56419c1409195f6fd987a
refs/heads/master
2016-09-03T07:28:44.740603
2013-09-29T20:00:36
2013-09-29T20:00:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
209
cpp
#include <iostream> #include <vector> using namespace std; int main() { vector <int> array; int j = 7; array[0].push_back(j); array[1].push_back(j); cout << array[0][0] << array[1][0] << endl; return 0; }
[ "kevinryczko@me.com" ]
kevinryczko@me.com
d07c0a84586a280b00d8df32660d3e7201cd139f
f862edafff99a383ab7b85f34cc7a060de320922
/core/depthmap.h
64d72eee2ad025575c524d64a4e6bf256962d0ed
[]
no_license
FivestWu/ImageBasedModellingEduV1.0
51387cfdd654108d118b1f883464beb1dc77e37f
ef0f9f086ce641bafb30fb19a1c3ce90ca10a9fe
refs/heads/master
2020-04-04T10:05:06.454977
2019-03-13T08:04:57
2019-03-13T08:04:57
155,842,300
0
0
null
2018-11-02T09:17:48
2018-11-02T09:17:47
null
UTF-8
C++
false
false
6,575
h
/* * Copyright (C) 2015, Simon Fuhrmann * TU Darmstadt - Graphics, Capture and Massively Parallel Computing * All rights reserved. * * This software may be modified and distributed under the terms * of the BSD 3-Clause license. See the LICENSE.txt file for details. */ #ifndef MVE_DEPTHMAP_HEADER #define MVE_DEPTHMAP_HEADER #include "core/defines.h" #include "math/vector.h" #include "math/matrix.h" #include "core/camera.h" #include "core/image.h" #include "core/mesh.h" CORE_NAMESPACE_BEGIN CORE_IMAGE_NAMESPACE_BEGIN /** * Algorithm to clean small confident islands in the depth maps. * Islands that are smaller than 'thres' pixels are removed. * Zero depth values are considered unreconstructed. */ FloatImage::Ptr depthmap_cleanup (FloatImage::ConstPtr dm, std::size_t thres); /** * Removes the backplane according to the confidence map IN-PLACE. * Depth map values are reset to zero where confidence is leq 0. */ void depthmap_confidence_clean (FloatImage::Ptr dm, FloatImage::ConstPtr cm); /** * Filters the given depthmap using a bilateral filter. * * The filter smoothes similar depth values but preserves depth * discontinuities using gaussian weights for both, geometric * closeness in image space and geometric closeness in world space. * * Geometric closeness in image space is controlled by 'gc_sigma' * (useful values in [1, 20]). Photometric closeness is evaluated by * calculating the pixel footprint multiplied with 'pc_factor' to * detect depth discontinuities (useful values in [1, 20]). */ FloatImage::Ptr depthmap_bilateral_filter (FloatImage::ConstPtr dm, math::Matrix3f const& invproj, float gc_sigma, float pc_fator); /** * Converts between depth map conventions IN-PLACE. In one convention, * a depth map with a constant value means a plane, in another convention, * which is what MVE uses, a constant value creates a curved surface. The * difference is whether only the z-value is considered, or the distance * to the camera center is used (MVE). */ template <typename T> void depthmap_convert_conventions (typename Image<T>::Ptr dm, math::Matrix3f const& invproj, bool to_mve); CORE_IMAGE_NAMESPACE_END CORE_NAMESPACE_END /* ---------------------------------------------------------------- */ CORE_NAMESPACE_BEGIN CORE_GEOM_NAMESPACE_BEGIN /** * Function that calculates the pixel footprint (pixel width) * in 3D coordinates for pixel (x,y) and 'depth' for a depth map * with inverse K matrix 'invproj'. */ float pixel_footprint (std::size_t x, std::size_t y, float depth, math::Matrix3f const& invproj); /** * Function that calculates the pixel 3D position in camera coordinates for * pixel (x,y) and 'depth' for a depth map with inverse K matrix 'invproj'. */ math::Vec3f pixel_3dpos (std::size_t x, std::size_t y, float depth, math::Matrix3f const& invproj); /** * \description * Algorithm to triangulate depth maps. * * A factor may be specified that guides depth discontinuity detection. A * depth discontinuity between pixels is assumed if depth difference is * larger than pixel footprint times 'dd_factor'. If 'dd_factor' is zero, * no depth discontinuity detection is performed. The depthmap is * triangulated in the local camera coordinate system. * * If 'vids' is not null, image content is replaced with vertex indices for * each pixel that generated the vertex. Index MATH_MAX_UINT corresponds to * a pixel that did not generate a vertex. * @param dm -- 深度图 * @param invproj -- 投影矩阵的逆矩阵 * @param dd_factor -- 不确定因子 * @param vids --可视图像 * @return */ TriangleMesh::Ptr depthmap_triangulate (FloatImage::ConstPtr dm, math::Matrix3f const& invproj, float dd_factor = 5.0f, core::Image<unsigned int>* vids = nullptr); /** * \description A helper function that triangulates the given depth map with optional * color image (which generates additional per-vertex colors) in local * image coordinates. * @param dm * @param ci * @param invproj * @param dd_factor * @return */ TriangleMesh::Ptr depthmap_triangulate (FloatImage::ConstPtr dm, ByteImage::ConstPtr ci, math::Matrix3f const& invproj, float dd_factor = 5.0f); /** * \description A helper function that triangulates the given depth map with optional * color image (which generates additional per-vertex colors) and transforms * the mesh into the global coordinate system. * @param dm -- 深度图像 * @param ci -- 彩色图像 * @param cam -- 相机参数 * @param dd_factor -- ?? * @return */ TriangleMesh::Ptr depthmap_triangulate (FloatImage::ConstPtr dm, ByteImage::ConstPtr ci, CameraInfo const& cam, float dd_factor = 5.0f); /** * Algorithm to triangulate range grids. * Vertex positions are given in 'mesh' and a grid that contains vertex * indices is specified. Four indices are taken at a time and triangulated * with discontinuity detection. New triangles are added to the mesh. */ void rangegrid_triangulate (Image<unsigned int> const& grid, TriangleMesh::Ptr mesh); /** * Algorithm to assign per-vertex confidence values to vertices of * a triangulated depth map. Confidences are low near boundaries * and small regions. */ void depthmap_mesh_confidences (TriangleMesh::Ptr mesh, int iterations = 3); /** * Algorithm that peels away triangles at the mesh bounary of a * triangulated depth map. The algorithm also works on other mesh * data but is particularly useful for MVS depthmap where the edges * of the real object are extended beyond their correct position. */ void depthmap_mesh_peeling (TriangleMesh::Ptr mesh, int iterations = 1); CORE_GEOM_NAMESPACE_END CORE_NAMESPACE_END /* ------------------------- Implementation ----------------------- */ CORE_NAMESPACE_BEGIN CORE_IMAGE_NAMESPACE_BEGIN template <typename T> inline void depthmap_convert_conventions (typename Image<T>::Ptr dm, math::Matrix3f const& invproj, bool to_mve) { std::size_t w = dm->width(); std::size_t h = dm->height(); std::size_t pos = 0; for (std::size_t y = 0; y < h; ++y) for (std::size_t x = 0; x < w; ++x, ++pos) { // Construct viewing ray for that pixel math::Vec3f px((float)x + 0.5f, (float)y + 0.5f, 1.0f); px = invproj * px; // Measure length of viewing ray double len = px.norm(); // Either divide or multiply with the length dm->at(pos) *= (to_mve ? len : 1.0 / len); } } CORE_IMAGE_NAMESPACE_END CORE_NAMESPACE_END #endif /* MVE_DEPTHMAP_HEADER */
[ "wsui@nl.pr.ia.ac.cn" ]
wsui@nl.pr.ia.ac.cn
ea2bacf2e21728a4e0721f2e796d6df6b700b1e6
36cfac858d066576aa77a26e3040c4d4e66d0097
/lab03/src/main.cpp
05fe348326039ad32a697440afa1b630756ba3e9
[]
no_license
Kotyarich/Algorithm-analysis
3eff8a91c739a33e7a0cf58b36165c9de92f3957
4c8d72c0e6683e25af379f55ba86149c1f415cc4
refs/heads/master
2020-08-13T04:38:38.719464
2020-01-26T23:39:03
2020-01-26T23:39:03
214,907,280
0
0
null
null
null
null
UTF-8
C++
false
false
2,190
cpp
#include <functional> #include <ctime> #include <iomanip> #include <iostream> #include <random> #include "sorts.h" using array = std::vector<double>; double check_time(const std::function<void()> &f) { int n = 5; clock_t start = clock(); for (int i = 0; i < n; i++) { f(); } clock_t end = clock(); return static_cast<double >(end - start) / CLOCKS_PER_SEC / n; } void init_arrays(array &sorted, array &reversed, array &random) { for (int i = 0; i < sorted.size(); i++) { sorted[i] = i; reversed[reversed.size() - 1 - i] = i; random[i] = rand() % 2000 - 1000; } } void check_sort_time(const array &s, const array &r, const array &random_arr) { array sorted(s.size()); array reversed(r.size()); array randomised(random_arr.size()); auto run_check = [&](const std::string &sort_name, const std::function<void(array&)> &sort){ std::copy(s.begin(), s.end(), sorted.begin()); std::copy(r.begin(), r.end(), reversed.begin()); std::copy(random_arr.begin(), random_arr.end(), randomised.begin()); std::cout << sort_name << std::endl; std::cout << "Sorted: " << std::fixed << std::setprecision(8) << check_time( [&](){ sort(sorted); }) << "s" << std::endl; std::cout << "Reversed: " << std::fixed << std::setprecision(8) << check_time( [&](){ sort(reversed); }) << "s" << std::endl; std::cout << "Randomised: " << std::fixed << std::setprecision(8) << check_time( [&](){ sort(randomised); }) << "s" << std::endl << std::endl; }; run_check("Bubble", bubble_sort); run_check("Insertion", insertion_sort); run_check("Choice", choice_sort); } int main() { srand(static_cast<unsigned int>(time(nullptr))); std::vector<size_t> sizes{10, 50, 100, 500, 1000, 5000, 20000, 50000}; for (auto i: sizes) { array sorted(i); array reversed(i); array random(i); init_arrays(sorted, reversed, random); std ::cout << "Number: " << i << std::endl; check_sort_time(sorted, reversed, random); std::cout << std::endl << std::endl; } }
[ "ndkotov@gmail.com" ]
ndkotov@gmail.com
c3c04ba93b620c5ee1a080a1be76fe09275e800f
38616fa53a78f61d866ad4f2d3251ef471366229
/3rdparty/RobustGNSS/gtsam/gtsam/3rdparty/GeographicLib/dotnet/examples/ManagedCPP/example-TransverseMercatorExact.cpp
2f41fa616f3b1d2221448963adf5cf677c87da2e
[ "BSD-3-Clause", "LGPL-2.1-only", "MPL-2.0", "LGPL-2.0-or-later", "BSD-2-Clause", "MIT" ]
permissive
wuyou33/Enabling-Robust-State-Estimation-through-Measurement-Error-Covariance-Adaptation
3b467fa6d3f34cabbd5ee59596ac1950aabf2522
2f1ff054b7c5059da80bb3b2f80c05861a02cc36
refs/heads/master
2020-06-08T12:42:31.977541
2019-06-10T15:04:33
2019-06-10T15:04:33
193,229,646
1
0
MIT
2019-06-22T12:07:29
2019-06-22T12:07:29
null
UTF-8
C++
false
false
940
cpp
using namespace System; using namespace NETGeographicLib; int main(array<System::String ^> ^/*args*/) { try { TransverseMercatorExact^ proj = gcnew TransverseMercatorExact(); // WGS84 double lon0 = -75; // Central meridian for UTM zone 18 { // Sample forward calculation double lat = 40.3, lon = -74.7; // Princeton, NJ double x, y; proj->Forward(lon0, lat, lon, x, y); Console::WriteLine(String::Format("{0} {1}", x, y)); } { // Sample reverse calculation double x = 25e3, y = 4461e3; double lat, lon; proj->Reverse(lon0, x, y, lat, lon); Console::WriteLine(String::Format("{0} {1}", lat, lon)); } } catch (GeographicErr^ e) { Console::WriteLine(String::Format("Caught exception: {0}", e->Message)); return -1; } return 0; }
[ "rwatso12@gmail.com" ]
rwatso12@gmail.com
89dcb5363571615a6f7c5b3598a4fa8e4ba9cd66
4db10784476fc3c322153e001b50484c1172abad
/prog.cpp
fc84439617f20770fc6e682ac333e87b0232839d
[]
no_license
Ne-ki-tos/hello-world
cea4be79baf8543f3e292aa21a26e50a31e16504
809d36dbe8da079e8989b542565e8b2dd5ce1ae2
refs/heads/master
2021-09-14T21:42:23.435125
2018-05-20T05:41:55
2018-05-20T05:41:55
104,358,364
0
0
null
2017-09-21T14:37:42
2017-09-21T14:26:50
null
UTF-8
C++
false
false
927
cpp
#include <iostream> #include <vector> #include <cassert> using namespace std; class Row{ public: Row(int l = 0, double *v = nullptr){ len = l; vector = v; } ~Row(){} const double operator[](int i) const{ if (i >= len) assert(!"index out of range"); return vector[i]; } double operator[](int i){ if (i >= len) assert(!"index out of range"); return vector[i]; } private: int len; double *vector; }; class Matrix{ public: Matrix(int r, int c){ rows = r; cols = c; matrix = new double[r*c]; } ~Matrix(){ delete[] matrix; } const Row& operator[](int i) const{ if (i >= rows) assert(!"index out of range"); col = Row(cols, &matrix[i*cols]); return col; } Row& operator[](int i){ if (i >= rows) assert(!"index out of range"); col = Row(cols, &matrix[i*cols]); return col; } private: int rows; int cols; double *matrix; mutable Row col; }; int main(){ return 0; }
[ "noreply@github.com" ]
Ne-ki-tos.noreply@github.com
f392e806ea3cf53d469b3320dbea1fd8fa61d625
db65b946860b5d6168f641bf49d177384410b61b
/src/colorChannel.h
9b8e051f368da0bd8466304385f422717b38957f
[]
no_license
jhpoelen/ofPooks
eb63b3f2cd45b7c2d69aef3b3870a4276bf76590
2163da93fac5c415a0b5cabe9d8c166aedb74c46
refs/heads/master
2021-01-22T11:55:58.680795
2020-11-01T03:16:59
2020-11-01T03:16:59
3,616,835
0
0
null
null
null
null
UTF-8
C++
false
false
255
h
#pragma once #include "ofMain.h" const int MAX_COLORS = 8; class ColorChannel { public: virtual ofColor nextColor(); virtual void loadColors(); virtual ofColor selectColor(int colorIndex); private: ofColor colors[MAX_COLORS]; };
[ "jhpoelen@gmail.com" ]
jhpoelen@gmail.com
a99d8aa96c755bc9901a8c3fa09090cfd86e1808
ac65ef0e0e29a20a27ea22634a71275d4e51b519
/SnakeGame/Settings.cpp
c8fbe6ed6c3832fee10845088576d94d4e83181d
[]
no_license
kartovitskayaa/CourseWork
68c564c54d6f633046216ed5913fd523acf291c2
fd6bac6cc5985e91ef8b7bb745d332e25493fa69
refs/heads/main
2023-01-24T17:22:25.442869
2020-12-14T22:56:53
2020-12-14T22:56:53
321,491,512
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
381
cpp
#include "stdafx.h" #include "Settings.h" const float Settings::SNAKE_STEP_TIME = 0.25; // Количество времени, потраченное на один шаг (в секунду) const Position Settings::SNAKE_START_POSITION = {1,0}; // Стартовая головы позиция змейки (-1 - т.к. сразу происходит первый шаг)
[ "noreply@github.com" ]
kartovitskayaa.noreply@github.com
bb24c2149f49154995e7ea4fd2ed5e270701a8b8
9b71acc34bbe0805c5d3e85f0040ccad3a76322a
/carCounter.h
fe4884fae49a5d09066e62a39606d4a904a37e1b
[]
no_license
BeyondDreamers93/Car-Counter
3638e7ea0a798f71af9168609ccd97e8c0f5a6a5
e545c64e06e2f5fda6b000a0d40f3e97d487e9a9
refs/heads/master
2022-04-26T16:52:37.678770
2020-04-23T22:52:03
2020-04-23T22:52:03
258,342,869
0
0
null
null
null
null
UTF-8
C++
false
false
214
h
#pragma once #include <stdio.h> #include <opencv2/opencv.hpp> using namespace cv; class carCounter { private: int carCount = 0; public: bool countCars(float ReferencePt, float lineReferencePtY); };
[ "noreply@github.com" ]
BeyondDreamers93.noreply@github.com
65c445a87703e13176476f3745d2004fb7ce7560
3624cb3da18011d62c2d4ddba35b26b1e9520e1f
/record.cpp
4c212966baa46eeb4bca9fe95e82210b35a880da
[]
no_license
zRrrGet/qbook
76841e67ab08c99e338071ce5e2c6868f0098f1b
832f8c1a1e137473c5a6801274942bb217e7d7cf
refs/heads/master
2023-03-21T10:49:33.381765
2021-03-12T11:26:00
2021-03-12T11:26:00
337,120,378
0
0
null
null
null
null
UTF-8
C++
false
false
831
cpp
#include "record.h" Record::Record(QString name, int num, QDate date, QTime startTime, QTime endTime) : userName(name), num(num), date(date), startTime(startTime), endTime(endTime) { } QString Record::getUserName() const { return userName; } void Record::setUserName(const QString &value) { userName = value; } QDate Record::getDate() const { return date; } void Record::setDate(const QDate &value) { date = value; } int Record::getNum() const { return num; } void Record::setNum(int value) { num = value; } QTime Record::getStartTime() const { return startTime; } void Record::setStartTime(const QTime &value) { startTime = value; } QTime Record::getEndTime() const { return endTime; } void Record::setEndTime(const QTime &value) { endTime = value; } Record::Record() { }
[ "misha02.00@mail.ru" ]
misha02.00@mail.ru
2e857525ec729de02671ef02df0d92152b8240a2
ee5c13e2219d5b5196f779074c972c230a778e0d
/DP/fib.cpp
42993c032021076da3c9fc3074f8e295f5f7d337
[]
no_license
Malay-Acharya/CPP
2b27f2f6557ad27036a41c9280f716fa0cfae05a
48bfa883720b832688e2b387a114b90fa69a7b88
refs/heads/master
2023-06-29T09:50:49.902474
2021-08-02T11:36:02
2021-08-02T11:36:02
391,924,846
0
0
null
null
null
null
UTF-8
C++
false
false
316
cpp
#include <iostream> #define int long long using namespace std; const int N = 1e5; int dp[N] = {0}; int fib(int n) { if(n==0) return 0; if(n==1 || n==2) return 1; if(dp[n]!=0) return dp[n]; dp[n] = fib(n-1) + fib(n-2); return dp[n]; } signed main() { int n; cin >> n; cout<<fib(n)<<endl; }
[ "malayacharya21@gmail.com" ]
malayacharya21@gmail.com
f9d4c1617a90cd157cb8832feac79236bfdbccf3
499ecfe8fdc4317fa565317081a9434a89a1da95
/NavComData.cpp
f8c2c2b7ca532e314b3155c56ccc2647f78469ce
[ "MIT" ]
permissive
magic-mouse/NavComData
9c338c48157f77254f57893bed7ca9d2237cae27
8d5ff83cdfa844de201c0126f3ce71dc367217ad
refs/heads/master
2020-09-26T21:09:13.655875
2019-12-06T14:23:12
2019-12-06T14:23:12
226,344,190
0
0
null
null
null
null
UTF-8
C++
false
false
818
cpp
/* NavComData - Library for controlling information for flight simulation navigation and communication. Created by Peter Nielsen, December, 2019 Released into the public domain. */ #include "Arduino.h" #include "NavComData.h" NavComData::NavComData(String id){ _name = id; } void NavComData::setMhz(short mhz){ _mhz = mhz; } void NavComData::stepUpMhz(){ _mhz++; } void NavComData::stepDownMhz(){ _mhz--; } void NavComData::setKhz(short khz){ _khz = khz; } void NavComData::stepUpKhz(){ _khz++; } void NavComData::stepDownKhz(){ _khz--; } unsigned short NavComData::getKhz(){ return _khz; } unsigned short NavComData::getMhz(){ return _mhz; }
[ "noreply@github.com" ]
magic-mouse.noreply@github.com
1f092df0d49d197f47eda874f303cb040813fa2c
9088eb860e84d53f22e639a5af1dd71f45859ab1
/_Binary_Search_tress/3. Delete.cpp
a80eb8c8485a24b84d372c31ea8119f6a639e408
[]
no_license
kritika2611/Algorithms-and-Datastructures
e6c547e5a1228401f73bb25a629779215bfdf2df
71b3361cb9d106d72629402e6cb66f70e96da75a
refs/heads/master
2023-01-11T04:20:22.582800
2020-10-23T16:22:23
2020-10-23T16:22:23
292,896,359
0
0
null
null
null
null
UTF-8
C++
false
false
2,077
cpp
//INPUT: 8 5 15 4 7 13 3 5 6 11 14 9 12 -1 #include <bits/stdc++.h> using namespace std; class node{ public: int data; node* left; node* right; node(int d){ this->data=d; this->left=NULL; this->right=NULL; } }; node* insert_(node* root, int d){ if(root==NULL){ node *n=new node(d); return n; } if(d<=root->data) root->left=insert_(root->left,d); else root->right=insert_(root->right,d); return root; } node* BST_Tree(){ int d; cin>>d; if(d==-1) return NULL; node* root=NULL; while(d!=-1){ root=insert_(root,d); cin>>d; } return root; } void print_BFS(node* root){ if(root==NULL){ return; } queue <node*> q; q.push(root); q.push(NULL); while(!q.empty()){ node* f=q.front(); q.pop(); if(f==NULL){ cout<<endl; if(!q.empty()) q.push(NULL); continue; } cout<<f->data<<" "; if(f->left!=NULL) q.push(f->left); if(f->right!=NULL) q.push(f->right); } } int max_(node* root){ //base case if(root->right==NULL) return root->data; //recursive case return max_(root->right); } node* delete_(node* root, int d){ //base case if(root==NULL) return NULL; if(root->data==d){ if(root->left==NULL && root->right==NULL) return NULL; //leaf node if(root->left==NULL || root->right==NULL){ //1 child if(root->left!=NULL) return root->left; else if(root->right!=NULL) return root->right; } //both children int e=max_(root->left); root->data=e; root->left=delete_(root->left,e); return root; } //recursive case if(d<=root->data) root->left=delete_(root->left,d); else root->right=delete_(root->right,d); return root; } int main(){ node* root=BST_Tree(); print_BFS(root); cout<<endl; delete_(root,13); print_BFS(root); cout<<endl; delete_(root,15); print_BFS(root); return 0; }
[ "sainikritika46@gmail.com" ]
sainikritika46@gmail.com
bb9eadca4492ac8a7313922886ed09db34579457
b6607ecc11e389cc56ee4966293de9e2e0aca491
/acm.kbtu.kz/KBTU OPEN/2014 Fall/E/copy.cpp
52bab8f8ac9e4aec776f71e2bad3fa66131c910f
[]
no_license
BekzhanKassenov/olymp
ec31cefee36d2afe40eeead5c2c516f9bf92e66d
e3013095a4f88fb614abb8ac9ba532c5e955a32e
refs/heads/master
2022-09-21T10:07:10.232514
2021-11-01T16:40:24
2021-11-01T16:40:24
39,900,971
5
0
null
null
null
null
UTF-8
C++
false
false
1,971
cpp
/**************************************** ** Solution by NU #2 ** ****************************************/ #include <bits/stdc++.h> using namespace std; #define F first #define S second #define MP make_pair #define all(x) (x).begin(), (x).end() #define File "growingtree" typedef long long ll; typedef unsigned long long ull; typedef long double ld; const double EPS = 1e-9; const double PI = acos(-1.0); const int MOD = 1000 * 1000 * 1000 + 7; const int INF = 2000 * 1000 * 1000; template <typename T> inline T sqr(T n) { return n * n; } int n, k; long long T; void mul(long long a[3][3], long long b[3][3], long long c[3][3]) { for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { c[i][j] = 0; for (int k = 0; k < 3; k++) { c[i][j] += (a[i][k] * b[k][j]) % MOD; c[i][j] %= MOD; } } } } void cpy(long long dest[3][3], long long source[3][3]) { for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) dest[i][j] = source[i][j]; } void binpow(long long a[3][3], long long p) { long long result[3][3] = {{k, 0, 0}, {n, 1, (-1 + MOD)}, {k, 0, 0}}; long long temp[3][3]; while (p) { if (p & 1) { mul(result, a, temp); cpy(result, temp); } mul(a, a, temp); cpy(a, temp); p >>= 1; } cpy(a, result); } int main() { freopen(File".in", "r", stdin); freopen(File".out", "w", stdout); scanf("%d%d%I64d", &n, &k, &T); long long a[3][3] = {{k, 0, 0}, {n, 1, (-1 + MOD)}, {k, 0, 0}}; binpow(a, T); for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { printf("%11I64d", a[i][j]); } puts(""); } printf("%I64d\n", a[1][0]); return 0; }
[ "bekzhan.kassenov@nu.edu.kz" ]
bekzhan.kassenov@nu.edu.kz
36cf3f31186671af260d124cf59cb08fcb5ef0ae
2d01e812589588edcaeb7d8c1802f3ee7aa17909
/GamePage/p2phash/seed.cpp
b0be8d3be88899ae4b78ab93af9fde9d412312d4
[]
no_license
N2oBeef/vc_scan
0c7b2e7f646e504aa4e14e2f53721ee8df7b6cf5
e249381fd25ce1d63c10039cf27e0f5cfa5cf440
refs/heads/master
2020-12-29T00:25:38.652076
2016-04-13T22:22:44
2016-04-13T22:22:49
56,185,892
2
0
null
null
null
null
GB18030
C++
false
false
21,567
cpp
/************************************************************** * FileName : seed.cpp * Description : * Version : 1.0 * Author : chenmingxiang * History : 1. 2009-11-17 Create this file. **************************************************************/ #include "stdafx.h" #include "seed.h" #include <algorithm> #include <iostream> #include <string> #include <time.h> #include <math.h> #include <sys/types.h> #include <sys/stat.h> #include <stdio.h> #include <errno.h> #if 1 // becode编码函数组 size_t bencode_begin_dict(FILE *fp) { return (EOF == fputc('d',fp)) ? 0 : 1; } size_t bencode_begin_list(FILE *fp) { return (EOF == fputc('l',fp)) ? 0 : 1; } size_t bencode_end_dict_list(FILE *fp) { return (EOF == fputc('e',fp)) ? 0 : 1; } size_t bencode_buf(const char *buf, size_t len, FILE *fp) { fprintf(fp, "%u:", (UINT32)len); return fwrite(buf, len, 1, fp) == 1 ? 1 : 0; } size_t bencode_blk(const char *buf, size_t len, FILE *fp) { return fwrite(buf, len, 1, fp) == 1 ? 1 : 0; } size_t bencode_str(const char *str, FILE *fp) { return bencode_buf(str, strlen(str), fp); } size_t bencode_int(const int integer, FILE *fp) { if( EOF == fputc('i', fp)) return 0; fprintf(fp, "%u", (UINT32)integer); return (EOF == fputc('e', fp)) ? 0: 1; } size_t bencode_int64(const UINT64 integer, FILE *fp) { if( EOF == fputc('i', fp)) return 0; fprintf(fp, "%lld", (UINT64)integer); return (EOF == fputc('e', fp)) ? 0: 1; } #endif /**************************************** * Function : WrapUnrecogChar * Description : 转换字符串中的不可识别字符为'_' * Parameters : * Return : null ****************************************/ void WrapUnrecogChar(std::string& strpath) { std::replace(strpath.begin(),strpath.end(),'?' ,'_'); std::replace(strpath.begin(),strpath.end(),'/' ,'_'); std::replace(strpath.begin(),strpath.end(),'|' ,'_'); std::replace(strpath.begin(),strpath.end(),':' ,'_'); std::replace(strpath.begin(),strpath.end(),'*' ,'_'); std::replace(strpath.begin(),strpath.end(),'<' ,'_'); std::replace(strpath.begin(),strpath.end(),'>' ,'_'); std::replace(strpath.begin(),strpath.end(),'\\' ,'_'); std::replace(strpath.begin(),strpath.end(),'\"' ,'_'); std::replace(strpath.begin(),strpath.end(),'\'' ,'_'); } /**************************************** * Function : CTORRENT::__initialize * Description : 初始化成员变量(清空) * Parameters : null * Return : null ****************************************/ void CTORRENT::__initialize() { _m_single = true; _m_pathlevel = 0; _m_encoding = T_ENCODING_GBK; _m_filenum = 0; _m_filelength = 0; _m_piecenum = 0; _m_piecelength = 0; _m_filename = ""; _m_tracker = ""; } /**************************************** * Function : CTORRENT::__clearup * Description : 释放成员变量 * Parameters : null * Return : null ****************************************/ void CTORRENT::__clearup() { if(_m_vct_piece.size() > 0) _m_vct_piece.clear(); if(_m_vct_filelist.size() > 0) _m_vct_filelist.clear(); if(_m_vct_filesize.size() > 0) _m_vct_filesize.clear(); } /**************************************** * Function : CTORRENT::__create * Description : 从源文件创建种子文件属性 * Parameters : file - 源文件名 * filesz - 源文件大小 * Return : 成功 - true * 失败 - false ****************************************/ bool CTORRENT::__create(const char* file, UINT64 filesz) { if(file == NULL) return false; if(filesz == 0 ) { printf("Error. file(%s) size zero\r\n", file); return false; // 不处理大小为0的文件 } _m_tracker = TORRENT_DEFAULT_TRACKER; _m_filename = file; _m_filenum = 1; _m_single = true; _m_filelength = filesz; _m_vct_filelist.push_back(file); _m_vct_filesize.push_back(filesz); _m_piecelength = __calc_piecesize(_m_filelength); __calc_hash(file); _m_piecenum = _m_vct_piece.size(); return true; } /**************************************** * Function : CTORRENT::__create * Description : 从源目录创建种子文件属性 * Parameters : dir - 源目录名 * vtrlist - 源目录下的文件名称列表 * vtrsize - 源目录下的文件大小列表 * Return : 成功 - true * 失败 - false ****************************************/ bool CTORRENT::__create(const char* dir, VCTSTR& vtrlist, VCTINT64& vtrsize) { if(dir == NULL) return false; _m_tracker = TORRENT_DEFAULT_TRACKER; _m_filename = dir; _m_filenum = 0; _m_single = false; VCTINT64::iterator it_size = vtrsize.begin(); VCTSTR::iterator it_list = vtrlist.begin(); while(it_size != vtrsize.end()) { if(*it_size != 0) // 不处理大小为0的文件 { _m_filenum++; _m_filelength += *it_size; _m_vct_filelist.push_back(*it_list); _m_vct_filesize.push_back(*it_size); } it_size++; it_list++; } if(_m_filelength == 0) return false; // 不处理大小为0的目录 _m_piecelength = __calc_piecesize(_m_filelength); VCTSTR::iterator it = _m_vct_filelist.begin(); while(it != _m_vct_filelist.end()) { __calc_hash((*it).c_str()); // 每个文件产生独立hash,不采用文件拼接 it++; } _m_piecenum = _m_vct_piece.size(); return true; } /**************************************** * Function : CTORRENT::__output * Description : 根据属性,生成bencode格式的种子文件 * Parameters : trnfile - 种子文件名 * Return : 成功 - true * 失败 - false ****************************************/ bool CTORRENT::__output(const char* trnfile) { FILE* fp = fopen(trnfile, "wb"); if(fp == NULL) { printf("Error! open trt file(%s) fail\r\n", trnfile); return false; } bencode_begin_dict(fp); // Begin首字典序 //bencode_str("announce",fp); // Tracker Url //bencode_str(_m_tracker.c_str(),fp); bencode_str("encoding",fp); // 编码格式 bencode_str("GBK",fp); bencode_str("creation date",fp); // 文件时间 time_t tm; time(&tm); bencode_str(ctime(&tm),fp); bencode_str("info",fp); // Info信息(嵌套字典) bencode_begin_dict(fp); // Info Begin字典序 bencode_str("name",fp); // 文件名 WrapUnrecogChar(_m_filename); bencode_str(_m_filename.c_str(),fp); if(_m_single) { bencode_str("length",fp); // 单文件长度 bencode_int64(_m_filelength,fp); } else { bencode_str("files",fp); // 多文件列表 bencode_begin_list(fp); UINT32 idx; VCTSTR::iterator it_list = _m_vct_filelist.begin(); VCTINT64::iterator it_size = _m_vct_filesize.begin(); for(idx = 0; idx < _m_filenum; idx++) { bencode_begin_dict(fp); bencode_str("length", fp); bencode_int64(*it_size, fp); bencode_str("path", fp); bencode_begin_list(fp); WrapUnrecogChar(*it_list); bencode_str((*it_list).c_str(), fp); bencode_end_dict_list(fp); bencode_end_dict_list(fp); it_list++; it_size++; } bencode_end_dict_list(fp); } bencode_str("piece length",fp); // 分片长度 bencode_int(_m_piecelength,fp); bencode_str("pieces",fp); // 分片hash列表 char buf[256]; sprintf(buf, "%lu:", _m_vct_piece.size() * 20); bencode_blk(buf, strlen(buf), fp); VCTPIECE::iterator it = _m_vct_piece.begin(); while(it != _m_vct_piece.end()) { bencode_blk((*it).hash, 20, fp); it++; } bencode_end_dict_list(fp); // Info End字典序。 bencode_end_dict_list(fp); // End首字典序。 fclose(fp); return true; } /**************************************** * Function : CTORRENT::__parse_dictionary * Description : * Parameters : * Return : ****************************************/ char* CTORRENT::__parse_dictionary(const char* start) { UINT64 num; char* buf = (char*)start; if (*buf++ != 'd') return NULL; while(*buf != 'e') { //嵌套字典 if (buf[0] == 'd'||buf[0] == 'l'||buf[0]=='i') return NULL; std::string paraname; std::string paravalue; char* pcolon = buf; while((*buf != ':') && (*buf!='e')) buf++; if (*buf == 'e') return NULL; //结束 num = atoi(pcolon); paraname.append(++buf, num); buf += num; if (buf[0] == 'd') { if((buf = __parse_dictionary(buf)) == NULL) return NULL; } else if(buf[0] == 'l') { if (paraname == "files") _m_single = false; if (paraname == "path") _m_pathlevel++; if((buf = __parse_list(buf)) == NULL) return NULL; if (paraname == "path") _m_pathlevel--; } else if (buf[0] == 'i')//数值 { num = atoi(++buf); while( *buf != 'e' ) buf++; buf++; if (paraname == "piece length") { _m_piecelength = num; } if (paraname == "length") { if(_m_single) { _m_filelength = num; _m_filenum = 1; } else { _m_filelength += num; _m_filenum++; _m_vct_filesize.push_back(num); } } } else { pcolon = buf; while(*buf != ':' && *buf!='e') buf++; if (*buf == 'e') return NULL; //结束 num = atoi(pcolon); paravalue.append(++buf, num); buf += num; if (paraname == "pieces") { if ((_m_piecenum = num/20) == 0) return NULL; } if (paraname == "announce") { _m_tracker = paravalue; } if (paraname == "name") { _m_filename = paravalue; } if (paraname == "encoding") { if(paravalue == "GBK") _m_encoding = T_ENCODING_GBK; else if(paravalue == "UTF-8") _m_encoding = T_ENCODING_UTF8; else _m_encoding = T_ENCODING_BUTT; } } } return ++buf; } /**************************************** * Function : CTORRENT::__parse_list * Description : * Parameters : * Return : ****************************************/ char* CTORRENT::__parse_list(const char* start) { char* buf = (char*)start; if(*buf++ != 'l') return NULL; bool _b_multi_path = false; std::string path; while(*buf != 'e') { if(*buf == 'l') { buf = __parse_list(buf); if(!buf) return NULL; } else if(*buf == 'd') { buf = __parse_dictionary(buf); if(!buf) return NULL; } else if(*buf == 'i') { while(*buf!= 'e') buf++; buf++; } else { char* pcolon = buf; while(*buf != ':' && *buf!= 'e') buf++; if (*buf == 'e') return NULL; //结束 UINT32 num = atoi(pcolon); buf++; if(_m_pathlevel > 0) { if(_b_multi_path) path += '\\'; path.append(buf, num); _b_multi_path = true; } buf += num; } } if(_m_pathlevel > 0) _m_vct_filelist.push_back(path); return ++buf; } /**************************************** * Function : CTORRENT::__calc_hash * Description : 根据文件,初始化成员变量 * Parameters : file - 源文件名 * Return : 成功 - true * 失败 - false ****************************************/ bool CTORRENT::__calc_hash(const char* file) { FILE* fp = fopen(file, "rb"); if(fp == NULL) return false; char readbuf[512*1024]; // piece最大为512KB while(1) { Piece piece; UINT32 size = fread(readbuf, 1, _m_piecelength, fp); if(size == 0) break; //CSha1 sha(readbuf, size); //sha.read(piece.hash); hash_function::CSha1::HashBuffer(readbuf, size, (BYTE *)&piece); _m_vct_piece.push_back(piece); } fclose(fp); return true; } /**************************************** * Function : CTORRENT::__calc_piecesize * Description : 根据文件大小计算分片长度 * 文件大小 分片长度 * ---------- ---------- * 0 - 4194303 16384 * 4194304-16777215 32768 * 16777216-67108863 65536 * 67108864-268435455 131072 * 268435456-1073741823 262144 * 1073741824-4G 524288 * 4G -- 524288 * ---------- ---------- * Parameters : filesz - 文件大小 * Return : 分片长度 ****************************************/ UINT32 CTORRENT::__calc_piecesize(UINT64 filesz) { if (filesz <= 2 * 1024 * 1024) return 16 * 1024; if (filesz >= (UINT64)4 * 1024 * 1024 * 1024) return 512 * 1024; float f = sqrt( (float)filesz/4096); unsigned short n = (unsigned short)f; int i = 3; while(n && i < 16) { if( n & (0x8000>>i)) return (0x8000 >> i) * 1024; i++; } return 16 * 1024; } /**************************************** * Function : CTORRENT::__get_filesz * Description : 计算文件大小 * Parameters : file - 文件名 * Return : 文件大小(Bytes) ****************************************/ UINT64 CTORRENT::__calc_filesize(const char* file) { struct _stati64 sb; if(_stati64(file, &sb) != 0) return 0; return sb.st_size; } /**************************************** * Function : CTORRENT::ShowTorrentInfo * Description : 显示种子文件信息 * Parameters : null * Return : null ****************************************/ void CTORRENT::ShowTorrentInfo() { printf("------------ global info ------------\r\n"); if(_m_single) printf("file name : %s \r\ntracker list: %s\r\n", _m_filename.c_str(), _m_tracker.c_str()); else printf("directory : %s \r\ntracker list: %s\r\n", _m_filename.c_str(), _m_tracker.c_str()); printf("total length: %u KB\r\ntotal number: %u\r\n", (int)(_m_filelength/1024), _m_filenum); printf("piece length: %u KB\r\npiece number: %u\r\n", _m_piecelength/1024, _m_piecenum); if(!_m_single) { printf("------------ detail info ------------\r\n"); VCTSTR::iterator it_list = _m_vct_filelist.begin(); VCTINT64::iterator it_size = _m_vct_filesize.begin(); for(UINT32 idx = 0; idx < _m_filenum; idx++, it_list++, it_size++) { UINT32 size = *it_size; if(size > 4096) printf("[%03d] file length: %u KB\r\n", idx + 1, size/1024); else printf("[%03d] file length: %u B\r\n", idx + 1, size); switch(_m_encoding) { case T_ENCODING_GBK: printf(" file name : %s\r\n", (*it_list).c_str()); break; default: break; } } } } /**************************************** * Function : CTORRENT::LoadTorrentFromFile * Description : 解析.torrent种子文件 * Parameters : trnfile - 种子文件名 * Return : 成功 - true * 失败 - false ****************************************/ bool CTORRENT::LoadTorrent(const char* trnfile) { if(trnfile == NULL) return false; FILE* fp = fopen(trnfile, "rb"); if(fp == NULL) return false; char buf[TORRENT_MAX_SIZE]; int totallen = fread(buf, sizeof(char), TORRENT_MAX_SIZE, fp); fclose(fp); if((totallen <= 0) || (totallen >= TORRENT_MAX_SIZE)) return false; return LoadTorrent(buf, totallen); } /**************************************** * Function : CTORRENT::LoadTorrentFromBuffer * Description : 解析.torrent种子文件 * Parameters : buffer - torrent文件内容 * length - torrent文件长度 * Return : 成功 - true * 失败 - false ****************************************/ bool CTORRENT::LoadTorrent(const char* buffer, UINT32 length) { if(buffer == NULL) return false; if(length == 0) return false; if((buffer[0] != 'd') || (buffer[length - 1] != 'e')) return false; return __parse_dictionary(buffer) == NULL ? false : true; } /**************************************** * Function : CTORRENT::CreateTorrent * Description : 制作.torrent种子文件 * Parameters : srcfile - 源文件名 * Return : 成功 - true * 失败 - false ****************************************/ bool CTORRENT::CreateTorrent(const char* srcfile, const char* optdir) { if(srcfile == NULL) return false; if(optdir == NULL) return false; if(strlen(optdir) == 0) return false; if(__create(srcfile, __calc_filesize(srcfile)) != true) return false; char* pbuf = (char*)malloc(_m_piecenum * SHA1_HASH_SIZE); memset(pbuf, 0, _m_piecenum * SHA1_HASH_SIZE); char* pcur = pbuf; VCTPIECE::iterator it = _m_vct_piece.begin(); while(it != _m_vct_piece.end()) { memcpy(pcur, (*it).hash, SHA1_HASH_SIZE); pcur += SHA1_HASH_SIZE; it++; } char hash[SHA1_HASH_SIZE]; //CSha1 sha(pbuf, _m_piecenum * SHA1_HASH_SIZE); // sha.read(hash); hash_function::CSha1::HashBuffer(pbuf, _m_piecenum * SHA1_HASH_SIZE, (BYTE *)&hash); free(pbuf); std::string str = optdir; if(optdir[strlen(optdir) - 1] != '\\') str += '\\'; for(UINT32 idx = 0; idx < SHA1_HASH_SIZE; idx++) { char code[16]; sprintf(code, "%02X", (UINT8)hash[idx]); str += code; } str += ".trt"; // 文件后缀trt bool _i_res = __output(str.c_str()); if(_i_res == true) printf("%s\r\n", strrchr(str.c_str(), '\\') + 1); return _i_res; } /**************************************** * Function : CTORRENT::CreateTorrent * Description : 制作.torrent种子文件 * Parameters : srcfile - 源文件名 trnfile - 种子文件名 * Return : 成功 - true * 失败 - false ****************************************/ bool CTORRENT::CreateTorrent(const char* srcdir, VCTSTR& vtrlist, VCTINT64& vtrsize, const char* optdir) { if(srcdir == NULL) return false; VCTINT64::iterator it_size = vtrsize.begin(); VCTSTR::iterator it_list = vtrlist.begin(); while(it_size != vtrsize.end()) { if(*it_size != 0) // 不处理大小为0的文件 { __clearup(); __initialize(); if(CreateTorrent((*it_list).c_str(), optdir) != true) return false; } it_size++; it_list++; } return true; } /**************************************** * Function : CTORRENT::CalcTorrent * Description : 显示文件Hash值 * Parameters : srcfile - 源文件名 * Return : 成功 - true * 失败 - false ****************************************/ bool CTORRENT::CalcTorrentHash(const char* srcfile) { if(srcfile == NULL) return false; if(__create(srcfile, __calc_filesize(srcfile)) != true) return false; char* pbuf = (char*)malloc(_m_piecenum * SHA1_HASH_SIZE); memset(pbuf, 0, _m_piecenum * SHA1_HASH_SIZE); char* pcur = pbuf; VCTPIECE::iterator it = _m_vct_piece.begin(); while(it != _m_vct_piece.end()) { memcpy(pcur, (*it).hash, SHA1_HASH_SIZE); pcur += SHA1_HASH_SIZE; it++; } char hash[SHA1_HASH_SIZE]; //CSha1 sha(pbuf, _m_piecenum * SHA1_HASH_SIZE); //sha.read(hash); hash_function::CSha1::HashBuffer(pbuf, _m_piecenum * SHA1_HASH_SIZE, (BYTE *)&hash); free(pbuf); std::string str = ""; for(UINT32 idx = 0; idx < SHA1_HASH_SIZE; idx++) { char code[16]; sprintf(code, "%02X", (UINT8)hash[idx]); str += code; } printf("%s\r\n", str.c_str()); return true; }
[ "460955584@qq.com" ]
460955584@qq.com
9159ae0cce2025921a4f32141fdc20870172a76a
81302ee42c1b3c25ce1566d70a782ab5525c7892
/daq/TDC/TDC Software/xerawdp-0.3.3_alpha04_test_tdc/src/XmlConfig.cpp
a9096f978cdadf4eedc3bf385570dc66bdcc3925
[]
no_license
mdanthony17/neriX
5dd8ce673cd340888d3d5e4d992f7296702c6407
2c4ddbb0b64e7ca54f30333ba4fb8f601bbcc32e
refs/heads/master
2020-04-04T06:01:25.200835
2018-06-05T00:37:08
2018-06-05T00:46:11
49,095,961
0
0
null
null
null
null
UTF-8
C++
false
false
54,611
cpp
#include "XmlConfig.h" #include <iostream> #include <sstream> #include <fstream> #include <algorithm> #include <libxml++/libxml++.h> using std::string; using std::stringstream; using std::ostringstream; using std::vector; using std::map; using std::cout; using std::endl; using std::ifstream; using std::min; using std::max; using std::getline; XmlConfig::XmlConfig() { // default values m_hConfigFileContents = ""; m_iProcessingLevel = 0; m_iUseTDC = 0; m_iFirstTopPmt = -1; m_iFirstBottomPmt = -1; m_iFirstTopVetoPmt = -1; m_iFirstBottomVetoPmt = -1; m_iFirstUnusedChannel = -1; m_iLastTopPmt = -1; m_iLastBottomPmt = -1; m_iLastTopVetoPmt = -1; m_iLastBottomVetoPmt = -1; m_iLastUnusedChannel = -1; m_fExternalGainTopPmts = 10.; m_fExternalGainBottomPmts = 10.; m_fExternalGainVetoPmts = 10.; #ifdef ENABLE_LIQ_SCI m_iFirstLiqSciChannel = -1; m_iLastLiqSciChannel = -1; m_iLiqSciMultiplexingStart = -1; #endif #ifdef ENABLE_NAI m_iFirstNaiChannel = -1; m_iLastNaiChannel = -1; #endif #ifdef ENABLE_HPGE m_iFirstGeChannel = -1; m_iLastGeChannel = -1; #endif #ifdef ENABLE_TAC m_iFirstTacChannel = -1; m_iLastTacChannel = -1; #endif m_iSingleNbBaselineSamples = -1; m_iSingleWindowStart = -1; m_iSingleWindowWidth = -1; m_iSinglePrePeakSamples = -1; m_iSinglePostPeakSamples = -1; m_bUseMaxPmtAlgorithm = false; m_bUseSvmAlgorithm = false; m_bUseNnAlgorithm = false; m_bUseChi2Algorithm = false; m_bCorrectForS1SpatialDependence = false; m_bCorrectForS2AxialDependence = false; m_fElectronLifetime = -1.; } XmlConfig::~XmlConfig() { } bool XmlConfig::readConfigFile(const string &hConfigFileName) { ifstream hConfigFile(hConfigFileName.c_str(), std::ios::binary); ostringstream hStream(std::ios::binary); hStream << hConfigFile.rdbuf(); m_hConfigFileContents = hStream.str(); hConfigFile.close(); xmlpp::DomParser hXmlParser; hXmlParser.parse_memory(m_hConfigFileContents); const xmlpp::Node* pRootNode = hXmlParser.get_document()->get_root_node(); readGlobalSettings(pRootNode); if(!readPmtSettings(pRootNode)) return false; readTriggerEfficiencySettings(pRootNode); #ifdef ENABLE_LIQ_SCI if(!readLiqSciSettings(pRootNode)) return false; #endif #ifdef ENABLE_NAI readNaiSettings(pRootNode); #endif #ifdef ENABLE_HPGE readGeSettings(pRootNode); #endif #ifdef ENABLE_TAC readTacSettings(pRootNode); #endif readSinglePhotoelectronSettings(pRootNode); readRawDataSettings(pRootNode); readPeakFindingSettings(pRootNode); readSignalsSettings(pRootNode); readPositionReconstructionSettings(pRootNode); if(!readSignalCorrectionsSettings(pRootNode)) return false; return true; } void XmlConfig::printSettings() { // print everything cout << " XmlConfig" << endl << " Global" << endl << " DatasetNameFormat: " << m_hDatasetNameFormat << endl << " RawDataDir: " << m_hRawDataDir << endl << " ProcessedDataDir: " << m_hProcessedDataDir << endl << " MergedDataDir: " << m_hMergedDataDir << endl << " ProcessingLevel: " << m_iProcessingLevel << endl << " Pmts" << endl << " TopPmts: " << m_hTopPmts << endl << " BottomPmts: " << m_hBottomPmts << endl << " TopVetoPmts: " << m_hTopVetoPmts << endl << " BottomVetoPmts: " << m_hBottomVetoPmts << endl << " UnusedChannels: " << m_hUnusedChannels << endl; if(m_hExternalGains.size()) { cout << " ExternalGains: " << m_hExternalGains << endl; } else { cout << " ExternalGain " << endl << " TopPmts: " << m_fExternalGainTopPmts << endl << " BottomPmts: " << m_fExternalGainBottomPmts << endl << " VetoPmts: " << m_fExternalGainVetoPmts << endl; } if(m_iProcessingLevel == 0) { cout << " SinglePhotoelectron:" << endl << " NbBaselineSamples: " << m_iSingleNbBaselineSamples << endl << " WindowStart: " << m_iSingleWindowStart << endl << " WindowWidth: " << m_iSingleWindowWidth << endl << " PrePeakSamples: " << m_iSinglePrePeakSamples << endl << " PostPeakSamples: " << m_iSinglePostPeakSamples << endl; } if(m_iProcessingLevel > 0) { cout << " CalibrationSource: " << m_hPmtCalibrationSource << endl; cout << " TriggerEfficiency" << endl << " NbTriggerSignals: " << m_iNbTriggerSignals << endl << " Channels: " << m_hTriggerEfficiencyChannels << endl << " TriggerWindowStart: " << m_iTriggerWindowStart << endl << " TriggerWindowWidth: " << m_iTriggerWindowWidth << endl << " TriggerSignalHeightThreshold: " << m_fTriggerSignalHeightThreshold << endl; #ifdef ENABLE_LIQ_SCI cout << " LiquidScintillators" << endl << " NbLiquidScintillators: " << m_iNbLiqScis << endl << " Channels: " << m_hLiqSciChannels << endl << " TailStart: " << m_iLiqSciTailStart << endl << " Multiplexed: " << m_bLiqSciMultiplexed << endl; if(m_bLiqSciMultiplexed) { cout << " MultiplexingStart: " << m_iLiqSciMultiplexingStart << endl << " MultiplexingWindows: " << m_hLiqSciMultiplexingWindows << endl << " MultiplexingSignalHeightThreshold: " << m_fLiqSciMultiplexingSignalHeightThreshold << endl << " MultiplexingSignalWidthThreshold: " << m_iLiqSciMultiplexingSignalWidthThreshold << endl; } #endif #ifdef ENABLE_NAI cout << " SodiumIodideDetectors" << endl << " NbSodiumIodideDetectors: " << m_iNbNaiDetectors << endl << " Channels: " << m_hNaiChannels << endl; #endif #ifdef ENABLE_HPGE cout << " GermaniumDetectors" << endl << " NbGermaniumDetectors: " << m_iNbGeDetectors << endl << " Channels: " << m_hGeChannels << endl; #endif #ifdef ENABLE_TAC cout << " TimeToAmplitudeConverters" << endl << " NbTimeToAmplitudeConverters: " << m_iNbTacs << endl << " Channels: " << m_hTacChannels << endl << " WindowStart: " << m_iTacWindowStart << endl << " WindowWidth: " << m_iTacWindowWidth << endl << " Calibration: " << m_hTacCalibration << endl; #endif cout << " RawData" << endl << " NbBaselineSamples: " << m_iNbBaselineSamples << endl << " PeakFinding" << endl << " S1: " << endl << " ExcludedPmts: " << m_hS1PeakFindingExcludedPmts << endl; if(m_bS1Filter) { cout << " Filter: " << endl << " Type: " << m_hS1FilterType << endl; if(m_hS1FilterType == "RaisedCosine") { cout << " LowPass: " << m_bS1RaisedCosineLowPass << endl << " Limit: " << m_fS1RaisedCosineLimit << endl << " RollOff: " << m_fS1RaisedCosineRollOff << endl << " Length: " << m_iS1RaisedCosineLength << endl; } else if(m_hS1FilterType == "Custom") { cout << " Coefficients: " << m_hS1CustomFilterCoefficientList << endl; } } cout << " MaxNbPeaks: " << m_iS1MaxNbPeaks << endl << " RightLimitHeightThreshold: " << m_fS1RightLimitHeightThreshold << endl << " SignalThreshold: " << m_fS1SignalThreshold << endl << " PeakWindow: " << m_iS1PeakWindow << endl << " PrePeakSamples: " << m_iS1PrePeakSamples << endl << " MaxLength: " << m_iS1MaxLength << endl << " PrePeakAvgWindow: " << m_iS1PrePeakAvgWindow << endl << " PostPeakAvgWindow: " << m_iS1PostPeakAvgWindow << endl << " PrePeakAvgThreshold: " << m_fS1PrePeakAvgThreshold << endl << " PostPeakAvgThreshold: " << m_fS1PostPeakAvgThreshold << endl << " FilteredWidthThreshold: " << m_fS1FilteredWidthThreshold << endl << " NegativeExcursionFractionThreshold: " << m_fS1NegativeExcursionFractionThreshold << endl << " HeightFractionThreshold: " << m_fS1HeightFractionThreshold << endl << " SamplesBelowThreshold: " << m_iS1SamplesBelowThreshold << endl; cout << " S2" << endl << " ExcludedPmts: " << m_hS2PeakFindingExcludedPmts << endl << " MaxNbPeaks: " << m_iS2MaxNbPeaks << endl; cout << " LargePeaks" << endl; if(m_bS2LargePeakFilter) { cout << " Filter" << endl << " Type: " << m_hS2LargePeakFilterType << endl; if(m_hS2LargePeakFilterType == "RaisedCosine") { cout << " LowPass: " << m_bS2LargePeakRaisedCosineLowPass << endl << " Limit: " << m_fS2LargePeakRaisedCosineLimit << endl << " RollOff: " << m_fS2LargePeakRaisedCosineRollOff << endl << " Length: " << m_iS2LargePeakRaisedCosineLength << endl; } } cout << " SignalThreshold: " << m_fS2LargePeakSignalThreshold << endl << " DynamicFractionSignalThreshold: " << m_fS2LargePeakDynamicFractionSignalThreshold << endl << " MinWidth: " << m_iS2LargePeakMinWidth << endl << " MinIntervalWidth: " << m_iS2LargePeakMinIntervalWidth << endl << " PreIntervalAvgWindow: " << m_iS2LargePeakPreIntervalAvgWindow << endl << " PostIntervalAvgWindow: " << m_iS2LargePeakPostIntervalAvgWindow << endl << " PreTopLevelIntervalAvgThreshold: " << m_fS2LargePeakPreTopLevelIntervalAvgThreshold << endl << " PostTopLevelIntervalAvgThreshold: " << m_fS2LargePeakPostTopLevelIntervalAvgThreshold << endl << " PreIntervalAvgThreshold: " << m_fS2LargePeakPreIntervalAvgThreshold << endl << " PostIntervalAvgThreshold: " << m_fS2LargePeakPostIntervalAvgThreshold << endl << " OverlappingPeaksThreshold: " << m_fS2LargePeakOverlappingPeaksThreshold << endl << " LeftHeightFractionThreshold: " << m_fS2LargePeakLeftHeightFractionThreshold << endl << " RightHeightFractionThreshold: " << m_fS2LargePeakRightHeightFractionThreshold << endl << " LargePeakSlopeThreshold: " << m_fS2LargePeakSlopeThreshold << endl << " SmallPeakSlopeThreshold: " << m_fS2SmallPeakSlopeThreshold << endl << " SmallPeakThreshold: " << m_fS2SmallPeakThreshold << endl; cout << " TinyPeaks" << endl; if(m_bS2TinyPeakFilter) { cout << " Filter" << endl << " Type: " << m_hS2TinyPeakFilterType << endl; if(m_hS2TinyPeakFilterType == "RaisedCosine") { cout << " LowPass: " << m_bS2TinyPeakRaisedCosineLowPass << endl << " Limit: " << m_fS2TinyPeakRaisedCosineLimit << endl << " RollOff: " << m_fS2TinyPeakRaisedCosineRollOff << endl << " Length: " << m_iS2TinyPeakRaisedCosineLength << endl; } else if(m_hS2TinyPeakFilterType == "Custom") { cout << " Coefficients: " << m_hS2TinyPeakCustomFilterCoefficientList << endl; } } cout << " RightLimitHeightThreshold: " << m_fS2TinyPeakRightLimitHeightThreshold << endl << " SignalThreshold: " << m_fS2TinyPeakSignalThreshold << endl << " MinIntervalWidth: " << m_iS2TinyPeakMinIntervalWidth << endl << " MaxIntervalWidth: " << m_iS2TinyPeakMaxIntervalWidth << endl << " PrePeakAvgWindow: " << m_iS2TinyPeakPrePeakAvgWindow << endl << " PostPeakAvgWindow: " << m_iS2TinyPeakPostPeakAvgWindow << endl << " PrePeakAvgThreshold: " << m_fS2TinyPeakPrePeakAvgThreshold << endl << " PostPeakAvgThreshold: " << m_fS2TinyPeakPostPeakAvgThreshold << endl << " AspectRatioThreshold: " << m_fS2TinyPeakAspectRatioThreshold << endl << " HeightFractionThreshold: " << m_fS2TinyPeakHeightFractionThreshold << endl; cout << " Signals" << endl << " SignalThreshold: " << m_fSignalThreshold << endl << " SaturationThreshold: " << m_fSaturationThreshold << endl << " S1" << endl << " CoincidenceExcludedPmts: " << m_hS1CoincidenceExcludedPmts << endl << " TotalSignalExcludedPmts: " << m_hS1TotalSignalExcludedPmts << endl << " CoincidenceWindow: " << m_iS1CoincidenceWindow << endl << " S2" << endl << " CoincidenceExcludedPmts: " << m_hS2CoincidenceExcludedPmts << endl << " TotalSignalExcludedPmts: " << m_hS2TotalSignalExcludedPmts << endl << " CoincidenceWindow: " << m_iS2CoincidenceWindow << endl; cout << " PositionReconstruction " << endl << " RelativeEfficiencies: " << m_hRelativeEfficiencies << endl; if(m_bUseMaxPmtAlgorithm) { cout << " MaxPmt: " << endl; } if(m_bUseSvmAlgorithm) { cout << " Svm: " << endl << " RModelFileName: " << m_hSvmRModelFileName << endl << " XModelFileName: " << m_hSvmXModelFileName << endl << " YModelFileName: " << m_hSvmYModelFileName << endl; } if(m_bUseNnAlgorithm) { cout << " Nn: " << endl << " XYModelName: " << m_hNnXYModelName << endl; } if(m_bUseChi2Algorithm) { cout << " Chi2: " << endl << " LceMapFileName: " << m_hChi2LceMapFileName << endl; } if(m_bUseFannAlgorithm) { cout << " Fann: " << endl << " XYModelFileName: " << m_hFannXYModelFileName << endl; } cout << " SignalCorrections " << endl; if(m_bCorrectForS1SpatialDependence) { cout << " S1: " << endl << " SpatialCorrection: " << endl; } if(m_bCorrectForS2AxialDependence) { cout << " S2: " << endl << " AxialCorrection: " << endl << " ElectronLifetime: " << m_fElectronLifetime << endl; } } } bool XmlConfig::readGlobalSettings(const xmlpp::Node* pRootNode) { stringstream hStream; // get global settings const xmlpp::NodeSet hGlobalNodeSet = pRootNode->find("/xerawdp/global/*"); for(int i = 0; i < (int) hGlobalNodeSet.size(); i++) { string hName = hGlobalNodeSet[i]->get_name(); hStream.str(((xmlpp::ContentNode *) hGlobalNodeSet[i]->get_children().front())->get_content()); if(hName == "verbosity") hStream >> m_iVerbosity; else if(hName == "dataset_name_format") m_hDatasetNameFormat = hStream.str(); else if(hName == "raw_data_dir") m_hRawDataDir = hStream.str(); else if(hName == "processed_data_dir") m_hProcessedDataDir = hStream.str(); else if(hName == "merged_data_dir") m_hMergedDataDir = hStream.str(); else if(hName == "processing_level") hStream >> m_iProcessingLevel; else if(hName == "use_tdc") hStream >> m_iUseTDC; hStream.clear(); } } bool XmlConfig::readSinglePhotoelectronSettings(const xmlpp::Node* pRootNode) { stringstream hStream; // get global settings const xmlpp::NodeSet hSinglePhotoelectronNodeSet = pRootNode->find("/xerawdp/single_photoelectron/*"); for(int i = 0; i < (int) hSinglePhotoelectronNodeSet.size(); i++) { string hName = hSinglePhotoelectronNodeSet[i]->get_name(); hStream.str(((xmlpp::ContentNode *) hSinglePhotoelectronNodeSet[i]->get_children().front())->get_content()); if(hName == "nb_baseline_samples") hStream >> m_iSingleNbBaselineSamples; else if(hName == "window_start") hStream >> m_iSingleWindowStart; else if(hName == "window_width") hStream >> m_iSingleWindowWidth; else if(hName == "pre_peak_samples") hStream >> m_iSinglePrePeakSamples; else if(hName == "post_peak_samples") hStream >> m_iSinglePostPeakSamples; hStream.clear(); } } bool XmlConfig::readPmtSettings(const xmlpp::Node* pRootNode) { stringstream hStream; // get pmt number settings const xmlpp::NodeSet hPmtsNodeSet = pRootNode->find("/xerawdp/pmts/*"); for(int i = 0; i < (int) hPmtsNodeSet.size(); i++) { string hName = hPmtsNodeSet[i]->get_name(); hStream.str(((xmlpp::ContentNode *) hPmtsNodeSet[i]->get_children().front())->get_content()); if(hName == "top_pmts") { m_hTopPmts = hStream.str(); parsePmtString(m_hTopPmts, m_iFirstTopPmt, m_iLastTopPmt); } else if(hName == "bottom_pmts") { m_hBottomPmts = hStream.str(); parsePmtString(m_hBottomPmts, m_iFirstBottomPmt, m_iLastBottomPmt); } else if(hName == "top_veto_pmts") { m_hTopVetoPmts = hStream.str(); parsePmtString(m_hTopVetoPmts, m_iFirstTopVetoPmt, m_iLastTopVetoPmt); } else if(hName == "bottom_veto_pmts") { m_hBottomVetoPmts = hStream.str(); parsePmtString(m_hBottomVetoPmts, m_iFirstBottomVetoPmt, m_iLastBottomVetoPmt); } else if(hName == "unused_channels") { m_hUnusedChannels = hStream.str(); parsePmtString(m_hUnusedChannels, m_iFirstUnusedChannel, m_iLastUnusedChannel); } hStream.clear(); } // get pmt external gains settings const xmlpp::NodeSet hPmtExternalGainsNodeSet = pRootNode->find("/xerawdp/pmts/*"); for(int i = 0; i < (int) hPmtExternalGainsNodeSet.size(); i++) { string hName = hPmtExternalGainsNodeSet[i]->get_name(); hStream.str(((xmlpp::ContentNode *) hPmtExternalGainsNodeSet[i]->get_children().front())->get_content()); if(hName == "external_gains") { m_hExternalGains = hStream.str(); parsePmtExternalGainsString(m_hExternalGains, m_hExternalGainsTable); } hStream.clear(); } // get pmt external gain settings const xmlpp::NodeSet hPmtExternalGainNodeSet = pRootNode->find("/xerawdp/pmts/external_gain/*"); for(int i = 0; i < (int) hPmtExternalGainNodeSet.size(); i++) { string hName = hPmtExternalGainNodeSet[i]->get_name(); hStream.str(((xmlpp::ContentNode *) hPmtExternalGainNodeSet[i]->get_children().front())->get_content()); if(hName == "top_pmts") hStream >> m_fExternalGainTopPmts; else if(hName == "bottom_pmts") hStream >> m_fExternalGainBottomPmts; else if(hName == "veto_pmts") hStream >> m_fExternalGainVetoPmts; hStream.clear(); } // fill the external gains table if it is empty if(!m_hExternalGainsTable.size()) { for(int iPmt = m_iFirstTopPmt; iPmt <= m_iLastTopPmt; iPmt++) m_hExternalGainsTable[iPmt] = m_fExternalGainTopPmts; for(int iPmt = m_iFirstBottomPmt; iPmt <= m_iLastBottomPmt; iPmt++) m_hExternalGainsTable[iPmt] = m_fExternalGainBottomPmts; for(int iPmt = m_iFirstTopVetoPmt; iPmt <= m_iLastTopVetoPmt; iPmt++) m_hExternalGainsTable[iPmt] = m_fExternalGainVetoPmts; for(int iPmt = m_iFirstBottomVetoPmt; iPmt <= m_iLastBottomVetoPmt; iPmt++) m_hExternalGainsTable[iPmt] = m_fExternalGainVetoPmts; } // get pmt calibration source settings const xmlpp::NodeSet hPmtCalibrationSourceNodeSet = pRootNode->find("/xerawdp/pmts/calibration_source/*"); for(int i = 0; i < (int) hPmtCalibrationSourceNodeSet.size(); i++) { string hName = hPmtCalibrationSourceNodeSet[i]->get_name(); hStream.str(((xmlpp::ContentNode *) hPmtCalibrationSourceNodeSet[i]->get_children().front())->get_content()); if(hName == "file") { m_hPmtCalibrationSource = "file"; m_hPmtCalibrationFileName = hStream.str(); } else if(hName == "here") m_hPmtCalibrationSource = "here"; else if(hName == "database") m_hPmtCalibrationSource = "database"; hStream.clear(); } // get pmt calibration source here settings const xmlpp::NodeSet hPmtHereNodeSet = pRootNode->find("/xerawdp/pmts/calibration_source/here/*"); for(int i = 0; i < (int) hPmtHereNodeSet.size(); i++) { string hName = hPmtHereNodeSet[i]->get_name(); hStream.str(((xmlpp::ContentNode *) hPmtHereNodeSet[i]->get_children().front())->get_content()); if(hName == "header") m_hPmtCalibrationHeader = hStream.str(); else if(hName == "values") m_hPmtCalibrationValues = hStream.str(); hStream.clear(); } // get pmt calibration source database settings const xmlpp::NodeSet hPmtDatabaseNodeSet = pRootNode->find("/xerawdp/pmts/calibration_source/database/*"); for(int i = 0; i < (int) hPmtDatabaseNodeSet.size(); i++) { string hName = hPmtDatabaseNodeSet[i]->get_name(); hStream.str(((xmlpp::ContentNode *) hPmtDatabaseNodeSet[i]->get_children().front())->get_content()); if(hName == "files") m_hPmtCalibrationFiles = hStream.str(); else if(hName == "header") m_hPmtCalibrationHeader = hStream.str(); else if(hName == "values") m_hPmtCalibrationValues = hStream.str(); hStream.clear(); } if(!fillPmtCalibrationTable()) return false; else return true; } bool XmlConfig::readTriggerEfficiencySettings(const xmlpp::Node* pRootNode) { stringstream hStream; // get trigger efficiency settings const xmlpp::NodeSet hTriggerEfficiencyNodeSet = pRootNode->find("/xerawdp/trigger_efficiency/*"); for(int i = 0; i < (int) hTriggerEfficiencyNodeSet.size(); i++) { string hName = hTriggerEfficiencyNodeSet[i]->get_name(); hStream.str(((xmlpp::ContentNode *) hTriggerEfficiencyNodeSet[i]->get_children().front())->get_content()); if(hName == "nb_trigger_signals") hStream >> m_iNbTriggerSignals; else if(hName == "channels") { m_hTriggerEfficiencyChannels = hStream.str(); parsePmtString(m_hTriggerEfficiencyChannels, m_iFirstTriggerEfficiencyChannel, m_iLastTriggerEfficiencyChannel); } else if(hName == "trigger_window_start") hStream >> m_iTriggerWindowStart; else if(hName == "trigger_window_width") hStream >> m_iTriggerWindowWidth; else if(hName == "trigger_signal_height_threshold") hStream >> m_fTriggerSignalHeightThreshold; hStream.clear(); } } #ifdef ENABLE_LIQ_SCI bool XmlConfig::readLiqSciSettings(const xmlpp::Node* pRootNode) { stringstream hStream; // get liquid scintillator settings const xmlpp::NodeSet hLiquidScintillatorsNodeSet = pRootNode->find("/xerawdp/liquid_scintillators/*"); for(int i = 0; i < (int) hLiquidScintillatorsNodeSet.size(); i++) { string hName = hLiquidScintillatorsNodeSet[i]->get_name(); hStream.str(((xmlpp::ContentNode *) hLiquidScintillatorsNodeSet[i]->get_children().front())->get_content()); if(hName == "nb_liquid_scintillators") hStream >> m_iNbLiqScis; else if(hName == "channels") { m_hLiqSciChannels = hStream.str(); parsePmtString(m_hLiqSciChannels, m_iFirstLiqSciChannel, m_iLastLiqSciChannel); } else if(hName == "tail_start") hStream >> m_iLiqSciTailStart; else if(hName == "multiplexed") hStream >> m_bLiqSciMultiplexed; else if(hName == "multiplexing_start") hStream >> m_iLiqSciMultiplexingStart; else if(hName == "multiplexing_windows") { m_hLiqSciMultiplexingWindows = hStream.str(); parseLiqSciMultiplexingWindowsString(m_hLiqSciMultiplexingWindows, m_hLiqSciMultiplexingTable); } else if(hName == "multiplexing_signal_height_threshold") hStream >> m_fLiqSciMultiplexingSignalHeightThreshold; else if(hName == "multiplexing_signal_width_threshold") hStream >> m_iLiqSciMultiplexingSignalWidthThreshold; hStream.clear(); } // verify liquid scintillator mutliplexing table return verifyLiqSciMultiplexingTable(); } #endif #ifdef ENABLE_NAI bool XmlConfig::readNaiSettings(const xmlpp::Node* pRootNode) { stringstream hStream; // get sodium iodide detector settings const xmlpp::NodeSet hNaiNodeSet = pRootNode->find("/xerawdp/sodium_iodide_detectors/*"); for(int i = 0; i < (int) hNaiNodeSet.size(); i++) { string hName = hNaiNodeSet[i]->get_name(); hStream.str(((xmlpp::ContentNode *) hNaiNodeSet[i]->get_children().front())->get_content()); if(hName == "nb_sodium_iodide_detectors") hStream >> m_iNbNaiDetectors; else if(hName == "channels") { m_hNaiChannels = hStream.str(); parsePmtString(m_hNaiChannels, m_iFirstNaiChannel, m_iLastNaiChannel); } hStream.clear(); } } #endif #ifdef ENABLE_HPGE bool XmlConfig::readGeSettings(const xmlpp::Node* pRootNode) { stringstream hStream; // get germanium detector settings const xmlpp::NodeSet hGeNodeSet = pRootNode->find("/xerawdp/germanium_detectors/*"); for(int i = 0; i < (int) hGeNodeSet.size(); i++) { string hName = hGeNodeSet[i]->get_name(); hStream.str(((xmlpp::ContentNode *) hGeNodeSet[i]->get_children().front())->get_content()); if(hName == "nb_germanium_detectors") hStream >> m_iNbGeDetectors; else if(hName == "channels") { m_hGeChannels = hStream.str(); parsePmtString(m_hGeChannels, m_iFirstGeChannel, m_iLastGeChannel); } hStream.clear(); } } #endif #ifdef ENABLE_TAC bool XmlConfig::readTacSettings(const xmlpp::Node* pRootNode) { stringstream hStream; // get tac settings const xmlpp::NodeSet hTimeToAmplitudeConvertersNodeSet = pRootNode->find("/xerawdp/time_to_amplitude_converters/*"); for(int i = 0; i < (int) hTimeToAmplitudeConvertersNodeSet.size(); i++) { string hName = hTimeToAmplitudeConvertersNodeSet[i]->get_name(); hStream.str(((xmlpp::ContentNode *) hTimeToAmplitudeConvertersNodeSet[i]->get_children().front())->get_content()); if(hName == "nb_time_to_amplitude_converters") hStream >> m_iNbTacs; else if(hName == "channels") { m_hTacChannels = hStream.str(); parsePmtString(m_hTacChannels, m_iFirstTacChannel, m_iLastTacChannel); } else if(hName == "window_start") hStream >> m_iTacWindowStart; else if(hName == "window_width") hStream >> m_iTacWindowWidth; else if(hName == "calibration") { m_hTacCalibration = hStream.str(); parseTacCalibrationString(m_hTacCalibration, m_hTacCalibrationTable); } hStream.clear(); } } #endif bool XmlConfig::readRawDataSettings(const xmlpp::Node* pRootNode) { stringstream hStream; // get raw data settings const xmlpp::NodeSet hRawDataNodeSet = pRootNode->find("/xerawdp/raw_data/*"); for(int i = 0; i < (int) hRawDataNodeSet.size(); i++) { string hName = hRawDataNodeSet[i]->get_name(); hStream.str(((xmlpp::ContentNode *) hRawDataNodeSet[i]->get_children().front())->get_content()); if(hName == "nb_baseline_samples") hStream >> m_iNbBaselineSamples; hStream.clear(); } return true; } bool XmlConfig::readPeakFindingSettings(const xmlpp::Node* pRootNode) { stringstream hStream; // get s1 peak finding raised cosine filter settings const xmlpp::NodeSet hS1RaisedCosineNodeSet = pRootNode->find("/xerawdp/peak_finding/s1/filter/raised_cosine/*"); if(hS1RaisedCosineNodeSet.size()) { m_bS1Filter = true; m_hS1FilterType = "RaisedCosine"; } for(int i = 0; i < (int) hS1RaisedCosineNodeSet.size(); i++) { string hName = hS1RaisedCosineNodeSet[i]->get_name(); hStream.str(((xmlpp::ContentNode *) hS1RaisedCosineNodeSet[i]->get_children().front())->get_content()); if(hName == "low_pass") hStream >> m_bS1RaisedCosineLowPass; else if(hName == "limit") hStream >> m_fS1RaisedCosineLimit; else if(hName == "roll_off") hStream >> m_fS1RaisedCosineRollOff; else if(hName == "length") hStream >> m_iS1RaisedCosineLength; hStream.clear(); } // get s1 custom filter settings const xmlpp::NodeSet hS1CustomFilterNodeSet = pRootNode->find("/xerawdp/peak_finding/s1/filter/custom/*"); if(hS1CustomFilterNodeSet.size()) { m_bS1Filter = true; m_hS1FilterType = "Custom"; } for(int i = 0; i < (int) hS1CustomFilterNodeSet.size(); i++) { string hName = hS1CustomFilterNodeSet[i]->get_name(); hStream.str(((xmlpp::ContentNode *) hS1CustomFilterNodeSet[i]->get_children().front())->get_content()); if(hName == "coefficients") { m_hS1CustomFilterCoefficientList = hStream.str(); parseValueList(m_hS1CustomFilterCoefficientList, m_hS1CustomFilterCoefficients); } hStream.clear(); } // get s1 peak finding settings const xmlpp::NodeSet hS1NodeSet = pRootNode->find("/xerawdp/peak_finding/s1/*"); for(int i = 0; i < (int) hS1NodeSet.size(); i++) { string hName = hS1NodeSet[i]->get_name(); hStream.str(((xmlpp::ContentNode *) hS1NodeSet[i]->get_children().front())->get_content()); if(hName == "excluded_pmts") { m_hS1PeakFindingExcludedPmts = hStream.str(); parsePmtEnumerationString(m_hS1PeakFindingExcludedPmts, m_hS1PeakFindingExcludedPmtSet); } else if(hName == "max_nb_peaks") hStream >> m_iS1MaxNbPeaks; else if(hName == "right_limit_height_threshold") hStream >> m_fS1RightLimitHeightThreshold; else if(hName == "signal_threshold") hStream >> m_fS1SignalThreshold; else if(hName == "peak_window") hStream >> m_iS1PeakWindow; else if(hName == "pre_peak_samples") hStream >> m_iS1PrePeakSamples; else if(hName == "max_length") hStream >> m_iS1MaxLength; else if(hName == "pre_peak_avg_window") hStream >> m_iS1PrePeakAvgWindow; else if(hName == "post_peak_avg_window") hStream >> m_iS1PostPeakAvgWindow; else if(hName == "pre_peak_avg_threshold") hStream >> m_fS1PrePeakAvgThreshold; else if(hName == "post_peak_avg_threshold") hStream >> m_fS1PostPeakAvgThreshold; else if(hName == "filtered_width_threshold") hStream >> m_fS1FilteredWidthThreshold; else if(hName == "negative_excursion_fraction_threshold") hStream >> m_fS1NegativeExcursionFractionThreshold; else if(hName == "height_fraction_threshold") hStream >> m_fS1HeightFractionThreshold; else if(hName == "samples_below_threshold") hStream >> m_iS1SamplesBelowThreshold; else if(hName == "coincidence_threshold") hStream >> m_fS1CoincidenceThreshold; hStream.clear(); } // get s2 peak finding settings const xmlpp::NodeSet hS2NodeSet = pRootNode->find("/xerawdp/peak_finding/s2/*"); for(int i = 0; i < (int) hS2NodeSet.size(); i++) { string hName = hS2NodeSet[i]->get_name(); hStream.str(((xmlpp::ContentNode *) hS2NodeSet[i]->get_children().front())->get_content()); if(hName == "excluded_pmts") { m_hS2PeakFindingExcludedPmts = hStream.str(); parsePmtEnumerationString(m_hS2PeakFindingExcludedPmts, m_hS2PeakFindingExcludedPmtSet); } else if(hName == "max_nb_peaks") hStream >> m_iS2MaxNbPeaks; hStream.clear(); } // get s2 large peak raised cosine filter settings const xmlpp::NodeSet hS2LargePeakRaisedCosineNodeSet = pRootNode->find("/xerawdp/peak_finding/s2/large_peaks/filter/raised_cosine/*"); if(hS2LargePeakRaisedCosineNodeSet.size()) { m_bS2LargePeakFilter = true; m_hS2LargePeakFilterType = "RaisedCosine"; } for(int i = 0; i < (int) hS2LargePeakRaisedCosineNodeSet.size(); i++) { string hName = hS2LargePeakRaisedCosineNodeSet[i]->get_name(); hStream.str(((xmlpp::ContentNode *) hS2LargePeakRaisedCosineNodeSet[i]->get_children().front())->get_content()); if(hName == "low_pass") hStream >> m_bS2LargePeakRaisedCosineLowPass; else if(hName == "limit") hStream >> m_fS2LargePeakRaisedCosineLimit; else if(hName == "roll_off") hStream >> m_fS2LargePeakRaisedCosineRollOff; else if(hName == "length") hStream >> m_iS2LargePeakRaisedCosineLength; hStream.clear(); } // get s2 large peak settings const xmlpp::NodeSet hS2LargePeaksNodeSet = pRootNode->find("/xerawdp/peak_finding/s2/large_peaks/*"); for(int i = 0; i < (int) hS2LargePeaksNodeSet.size(); i++) { string hName = hS2LargePeaksNodeSet[i]->get_name(); hStream.str(((xmlpp::ContentNode *) hS2LargePeaksNodeSet[i]->get_children().front())->get_content()); if(hName == "signal_threshold") hStream >> m_fS2LargePeakSignalThreshold; else if(hName == "dynamic_fraction_signal_threshold") hStream >> m_fS2LargePeakDynamicFractionSignalThreshold; else if(hName == "min_width") hStream >> m_iS2LargePeakMinWidth; else if(hName == "min_interval_width") hStream >> m_iS2LargePeakMinIntervalWidth; else if(hName == "pre_interval_avg_window") hStream >> m_iS2LargePeakPreIntervalAvgWindow; else if(hName == "post_interval_avg_window") hStream >> m_iS2LargePeakPostIntervalAvgWindow; else if(hName == "pre_top_level_interval_avg_threshold") hStream >> m_fS2LargePeakPreTopLevelIntervalAvgThreshold; else if(hName == "post_top_level_interval_avg_threshold") hStream >> m_fS2LargePeakPostTopLevelIntervalAvgThreshold; else if(hName == "pre_interval_avg_threshold") hStream >> m_fS2LargePeakPreIntervalAvgThreshold; else if(hName == "post_interval_avg_threshold") hStream >> m_fS2LargePeakPostIntervalAvgThreshold; else if(hName == "overlapping_peaks_threshold") hStream >> m_fS2LargePeakOverlappingPeaksThreshold; else if(hName == "left_height_fraction_threshold") hStream >> m_fS2LargePeakLeftHeightFractionThreshold; else if(hName == "right_height_fraction_threshold") hStream >> m_fS2LargePeakRightHeightFractionThreshold; else if(hName == "large_peak_slope_threshold") hStream >> m_fS2LargePeakSlopeThreshold; else if(hName == "small_peak_slope_threshold") hStream >> m_fS2SmallPeakSlopeThreshold; else if(hName == "small_peak_threshold") hStream >> m_fS2SmallPeakThreshold; hStream.clear(); } // get s2 tiny peak raised cosine filter settings const xmlpp::NodeSet hS2TinyPeakRaisedCosineNodeSet = pRootNode->find("/xerawdp/peak_finding/s2/tiny_peaks/filter/raised_cosine/*"); if(hS2TinyPeakRaisedCosineNodeSet.size()) { m_bS2TinyPeakFilter = true; m_hS2TinyPeakFilterType = "RaisedCosine"; } for(int i = 0; i < (int) hS2TinyPeakRaisedCosineNodeSet.size(); i++) { string hName = hS2TinyPeakRaisedCosineNodeSet[i]->get_name(); hStream.str(((xmlpp::ContentNode *) hS2TinyPeakRaisedCosineNodeSet[i]->get_children().front())->get_content()); if(hName == "low_pass") hStream >> m_bS2TinyPeakRaisedCosineLowPass; else if(hName == "limit") hStream >> m_fS2TinyPeakRaisedCosineLimit; else if(hName == "roll_off") hStream >> m_fS2TinyPeakRaisedCosineRollOff; else if(hName == "length") hStream >> m_iS2TinyPeakRaisedCosineLength; hStream.clear(); } // get s2 tiny peak custom filter settings const xmlpp::NodeSet hS2TinyPeakCustomFilterNodeSet = pRootNode->find("/xerawdp/peak_finding/s2/tiny_peaks/filter/custom/*"); if(hS2TinyPeakCustomFilterNodeSet.size()) { m_bS2TinyPeakFilter = true; m_hS2TinyPeakFilterType = "Custom"; } for(int i = 0; i < (int) hS2TinyPeakCustomFilterNodeSet.size(); i++) { string hName = hS2TinyPeakCustomFilterNodeSet[i]->get_name(); hStream.str(((xmlpp::ContentNode *) hS2TinyPeakCustomFilterNodeSet[i]->get_children().front())->get_content()); if(hName == "coefficients") { m_hS2TinyPeakCustomFilterCoefficientList = hStream.str(); parseValueList(m_hS2TinyPeakCustomFilterCoefficientList, m_hS2TinyPeakCustomFilterCoefficients); } hStream.clear(); } // get s2 tiny peak settings const xmlpp::NodeSet hS2TinyPeaksNodeSet = pRootNode->find("/xerawdp/peak_finding/s2/tiny_peaks/*"); for(int i = 0; i < (int) hS2TinyPeaksNodeSet.size(); i++) { string hName = hS2TinyPeaksNodeSet[i]->get_name(); hStream.str(((xmlpp::ContentNode *) hS2TinyPeaksNodeSet[i]->get_children().front())->get_content()); if(hName == "right_limit_height_threshold") hStream >> m_fS2TinyPeakRightLimitHeightThreshold; else if(hName == "signal_threshold") hStream >> m_fS2TinyPeakSignalThreshold; else if(hName == "min_interval_width") hStream >> m_iS2TinyPeakMinIntervalWidth; else if(hName == "max_interval_width") hStream >> m_iS2TinyPeakMaxIntervalWidth; else if(hName == "pre_peak_avg_window") hStream >> m_iS2TinyPeakPrePeakAvgWindow; else if(hName == "post_peak_avg_window") hStream >> m_iS2TinyPeakPostPeakAvgWindow; else if(hName == "pre_peak_avg_threshold") hStream >> m_fS2TinyPeakPrePeakAvgThreshold; else if(hName == "post_peak_avg_threshold") hStream >> m_fS2TinyPeakPostPeakAvgThreshold; else if(hName == "aspect_ratio_threshold") hStream >> m_fS2TinyPeakAspectRatioThreshold; else if(hName == "height_fraction_threshold") hStream >> m_fS2TinyPeakHeightFractionThreshold; hStream.clear(); } return true; } bool XmlConfig::readSignalsSettings(const xmlpp::Node* pRootNode) { stringstream hStream; // get signals settings const xmlpp::NodeSet hSignalsNodeSet = pRootNode->find("/xerawdp/signals/*"); for(int i = 0; i < (int) hSignalsNodeSet.size(); i++) { string hName = hSignalsNodeSet[i]->get_name(); hStream.str(((xmlpp::ContentNode *) hSignalsNodeSet[i]->get_children().front())->get_content()); if(hName == "signal_threshold") hStream >> m_fSignalThreshold; else if(hName == "saturation_threshold") hStream >> m_fSaturationThreshold; hStream.clear(); } // get s1 signals settings const xmlpp::NodeSet hS1SignalsNodeSet = pRootNode->find("/xerawdp/signals/s1/*"); for(int i = 0; i < (int) hS1SignalsNodeSet.size(); i++) { string hName = hS1SignalsNodeSet[i]->get_name(); hStream.str(((xmlpp::ContentNode *) hS1SignalsNodeSet[i]->get_children().front())->get_content()); if(hName == "coincidence_excluded_pmts") { m_hS1CoincidenceExcludedPmts = hStream.str(); parsePmtEnumerationString(m_hS1CoincidenceExcludedPmts, m_hS1CoincidenceExcludedPmtSet); } else if(hName == "total_signal_excluded_pmts") { m_hS1TotalSignalExcludedPmts = hStream.str(); parsePmtEnumerationString(m_hS1TotalSignalExcludedPmts, m_hS1TotalSignalExcludedPmtSet); } else if(hName == "coincidence_window") hStream >> m_iS1CoincidenceWindow; hStream.clear(); } // get s2 signals settings const xmlpp::NodeSet hS2SignalsNodeSet = pRootNode->find("/xerawdp/signals/s2/*"); for(int i = 0; i < (int) hS2SignalsNodeSet.size(); i++) { string hName = hS2SignalsNodeSet[i]->get_name(); hStream.str(((xmlpp::ContentNode *) hS2SignalsNodeSet[i]->get_children().front())->get_content()); if(hName == "coincidence_excluded_pmts") { m_hS2CoincidenceExcludedPmts = hStream.str(); parsePmtEnumerationString(m_hS2CoincidenceExcludedPmts, m_hS2CoincidenceExcludedPmtSet); } else if(hName == "total_signal_excluded_pmts") { m_hS2TotalSignalExcludedPmts = hStream.str(); parsePmtEnumerationString(m_hS2TotalSignalExcludedPmts, m_hS2TotalSignalExcludedPmtSet); } else if(hName == "coincidence_window") hStream >> m_iS2CoincidenceWindow; hStream.clear(); } } bool XmlConfig::readPositionReconstructionSettings(const xmlpp::Node* pRootNode) { stringstream hStream; // get position reconstruction settings const xmlpp::NodeSet hPositionReconstructionNodeSet = pRootNode->find("/xerawdp/position_reconstruction/*"); for(int i = 0; i < (int) hPositionReconstructionNodeSet.size(); i++) { string hName = hPositionReconstructionNodeSet[i]->get_name(); hStream.str(((xmlpp::ContentNode *) hPositionReconstructionNodeSet[i]->get_children().front())->get_content()); if(hName == "relative_efficiencies") { m_hRelativeEfficiencies = hStream.str(); parseRelativeEfficienciesString(m_hRelativeEfficiencies, m_hRelativeEfficienciesTable); } hStream.clear(); } // get max pmt algorithm settings const xmlpp::NodeSet hMaxPmtAlgorithmNodeSet = pRootNode->find("/xerawdp/position_reconstruction/max_pmt/*"); for(int i = 0; i < (int) hMaxPmtAlgorithmNodeSet.size(); i++) { string hName = hMaxPmtAlgorithmNodeSet[i]->get_name(); hStream.str(((xmlpp::ContentNode *) hMaxPmtAlgorithmNodeSet[i]->get_children().front())->get_content()); if(hName == "use_algorithm") hStream >> m_bUseMaxPmtAlgorithm; hStream.clear(); } // get svm algorithm settings const xmlpp::NodeSet hSvmAlgorithmNodeSet = pRootNode->find("/xerawdp/position_reconstruction/svm/*"); for(int i = 0; i < (int) hSvmAlgorithmNodeSet.size(); i++) { string hName = hSvmAlgorithmNodeSet[i]->get_name(); hStream.str(((xmlpp::ContentNode *) hSvmAlgorithmNodeSet[i]->get_children().front())->get_content()); if(hName == "use_algorithm") hStream >> m_bUseSvmAlgorithm; else if(hName == "r_model_file_name") m_hSvmRModelFileName = hStream.str(); else if(hName == "x_model_file_name") m_hSvmXModelFileName = hStream.str(); else if(hName == "y_model_file_name") m_hSvmYModelFileName = hStream.str(); hStream.clear(); } // get neural network algorithm settings const xmlpp::NodeSet hNnAlgorithmNodeSet = pRootNode->find("/xerawdp/position_reconstruction/nn/*"); for(int i = 0; i < (int) hNnAlgorithmNodeSet.size(); i++) { string hName = hNnAlgorithmNodeSet[i]->get_name(); hStream.str(((xmlpp::ContentNode *) hNnAlgorithmNodeSet[i]->get_children().front())->get_content()); if(hName == "use_algorithm") hStream >> m_bUseNnAlgorithm; else if(hName == "xy_model_name") m_hNnXYModelName = hStream.str(); hStream.clear(); } // get chi^2 algorithm settings const xmlpp::NodeSet hChi2AlgorithmNodeSet = pRootNode->find("/xerawdp/position_reconstruction/chi2/*"); for(int i = 0; i < (int) hChi2AlgorithmNodeSet.size(); i++) { string hName = hChi2AlgorithmNodeSet[i]->get_name(); hStream.str(((xmlpp::ContentNode *) hChi2AlgorithmNodeSet[i]->get_children().front())->get_content()); if(hName == "use_algorithm") hStream >> m_bUseChi2Algorithm; else if(hName == "lce_map_file_name") m_hChi2LceMapFileName = hStream.str(); hStream.clear(); } // get fann algorithm settings const xmlpp::NodeSet hFannAlgorithmNodeSet = pRootNode->find("/xerawdp/position_reconstruction/fann/*"); for(int i = 0; i < (int) hFannAlgorithmNodeSet.size(); i++) { string hName = hFannAlgorithmNodeSet[i]->get_name(); hStream.str(((xmlpp::ContentNode *) hFannAlgorithmNodeSet[i]->get_children().front())->get_content()); if(hName == "use_algorithm") hStream >> m_bUseFannAlgorithm; else if(hName == "xy_model_file_name") m_hFannXYModelFileName = hStream.str(); hStream.clear(); } } bool XmlConfig::readSignalCorrectionsSettings(const xmlpp::Node* pRootNode) { stringstream hStream; // get s1 spatial correction settings const xmlpp::NodeSet hS1SpatialCorrectionNodeSet = pRootNode->find("/xerawdp/signal_corrections/s1/spatial_correction/*"); for(int i = 0; i < (int) hS1SpatialCorrectionNodeSet.size(); i++) { string hName = hS1SpatialCorrectionNodeSet[i]->get_name(); hStream.str(((xmlpp::ContentNode *) hS1SpatialCorrectionNodeSet[i]->get_children().front())->get_content()); if(hName == "apply_correction") hStream >> m_bCorrectForS1SpatialDependence; if(hName == "electron_lifetime") hStream >> m_fElectronLifetime; hStream.clear(); } // get s2 axial correction settings const xmlpp::NodeSet hS2AxialCorrectionNodeSet = pRootNode->find("/xerawdp/signal_corrections/s2/axial_correction/*"); for(int i = 0; i < (int) hS2AxialCorrectionNodeSet.size(); i++) { string hName = hS2AxialCorrectionNodeSet[i]->get_name(); hStream.str(((xmlpp::ContentNode *) hS2AxialCorrectionNodeSet[i]->get_children().front())->get_content()); if(hName == "apply_correction") hStream >> m_bCorrectForS2AxialDependence; else if(hName == "electron_lifetime") hStream >> m_fElectronLifetime; hStream.clear(); } if(m_bCorrectForS2AxialDependence && m_fElectronLifetime <= 0.) { cout << "xml config error: electron lifetime value required for s2 axial signal correction!" << endl; return false; } return true; } bool XmlConfig::parsePmtString(const string &hString, int &iFirstPmt, int &iLastPmt) { stringstream hTmp(hString); hTmp >> iFirstPmt; hTmp.ignore(); hTmp >> iLastPmt; return true; } bool XmlConfig::parsePmtExternalGainsString(const std::string &hString, ExternalGainsTable &hExternalGainsTable) { stringstream hTmp(hString); string::size_type hNextDigit = hTmp.str().find_first_of("0123456789"); hTmp.seekg(hNextDigit); hExternalGainsTable.clear(); while(!hTmp.eof() && hTmp.good()) { // get the pmt range int iFirstPmt, iLastPmt; hTmp >> iFirstPmt; if(hTmp.peek() == '-') { hTmp.ignore(); hTmp >> iLastPmt; } else iLastPmt = iFirstPmt; // get the external gain float fExternalGain; hTmp.ignore(); hTmp >> fExternalGain; for(int iPmt = iFirstPmt; iPmt <= iLastPmt; iPmt++) hExternalGainsTable[iPmt] = fExternalGain; // find the next digit hTmp.seekg(hTmp.str().find_first_of("0123456789", hTmp.tellg())); } return true; } bool XmlConfig::parsePmtEnumerationString(const std::string &hString, PmtSet &hPmtSet) { stringstream hTmp(hString); string::size_type hNextDigit = hTmp.str().find_first_of("0123456789"); hTmp.seekg(hNextDigit); hPmtSet.clear(); while(!hTmp.eof() && hTmp.good()) { // get the pmt range int iFirstPmt, iLastPmt; hTmp >> iFirstPmt; if(hTmp.peek() == '-') { hTmp.ignore(); hTmp >> iLastPmt; } else iLastPmt = iFirstPmt; for(int iPmt = iFirstPmt; iPmt <= iLastPmt; iPmt++) hPmtSet.insert(iPmt); // find the next digit hTmp.seekg(hTmp.str().find_first_of("0123456789", hTmp.tellg())); } return true; } bool XmlConfig::parsePmtCalibrationHeader(const std::string &hHeader) { stringstream hStream(hHeader); string hTmp; while(!hStream.eof()) { hStream >> hTmp; m_hPmtCalibrationTableHeader.push_back(hTmp); } // if this is the header of a calibration file if(m_hPmtCalibrationSource == "file") { // the pmt column is required if(count(m_hPmtCalibrationTableHeader.begin(), m_hPmtCalibrationTableHeader.end(), "pmt") == 0) { cout << "xml config error: the pmt calibration file needs to contain the pmt number column!" << endl; return false; } } // verify that at least the gain is there if(count(m_hPmtCalibrationTableHeader.begin(), m_hPmtCalibrationTableHeader.end(), "gain") == 0) { cout << "xml config error: the pmt calibration needs to contain at least the gain!" << endl; return false; } return true; } bool XmlConfig::parsePmtCalibrationFile(const string &hFile) { ifstream hIn(hFile.c_str()); if(hIn.fail()) { cout << "xml config error: cannot open file " << hFile << "!" << endl; return false; } // parse the header string hHeader; getline(hIn, hHeader); if(!parsePmtCalibrationHeader(hHeader)) return false; m_hPmtCalibrationTable.clear(); // read the pmt calibration values as described by the calibration table header int iExpectedPmt = 1; while(!hIn.eof()) { map<string, float> hCalibration; PmtCalibrationTableHeader::iterator pColumn; for(pColumn = m_hPmtCalibrationTableHeader.begin(); pColumn != m_hPmtCalibrationTableHeader.end(); pColumn++) { float fValue = 0.; hIn >> fValue; if(hIn.fail()) break; hCalibration[*pColumn] = fValue; } if(!hIn.fail()) { int iPmt = (int) hCalibration["pmt"]; // store them in the pmt calibration table m_hPmtCalibrationTable[iPmt] = hCalibration; iExpectedPmt++; } } // verify pmt calibration table return verifyPmtCalibrationTable(); } bool XmlConfig::parsePmtCalibrationValues(const string &hValues) { // parse the header if(!parsePmtCalibrationHeader(m_hPmtCalibrationHeader)) return false; m_hPmtCalibrationTable.clear(); string::size_type hPos = 0; string::size_type hColonPos; // find the next colon while((hColonPos = hValues.find(":", hPos)) != string::npos) { stringstream hTmp; hTmp.clear(); hTmp.str(hValues.substr(hPos, hColonPos-hPos)); // get the pmt range int iFirstPmt, iLastPmt; hTmp >> iFirstPmt; if(hTmp.peek() == '-') { hTmp.ignore(); hTmp >> iLastPmt; } else iLastPmt = iFirstPmt; hPos = hColonPos+1; string::size_type hCommaPos; hTmp.clear(); if((hCommaPos = hValues.find(",", hPos)) != string::npos) hTmp.str(hValues.substr(hPos+1, hCommaPos-hPos-2)); else hTmp.str(hValues.substr(hPos+1, hValues.size()-hPos-2)); // get the pmt calibration parameters while(!hTmp.eof()) { map<string, float> hCalibration; PmtCalibrationTableHeader::iterator pColumn; for(pColumn = m_hPmtCalibrationTableHeader.begin(); pColumn != m_hPmtCalibrationTableHeader.end(); pColumn++) { float fValue = 0.; hTmp >> fValue; if(hTmp.fail()) break; hCalibration[*pColumn] = fValue; } if(!hTmp.fail()) { // store them in the pmt calibration table for(int iPmt = iFirstPmt; iPmt <= iLastPmt; iPmt++) m_hPmtCalibrationTable[iPmt] = hCalibration; } } hPos = hCommaPos+1; if(hCommaPos == string::npos) break; } // verify pmt calibration table return verifyPmtCalibrationTable(); } bool XmlConfig::fillPmtCalibrationTable() { if(m_hPmtCalibrationSource == "file") return parsePmtCalibrationFile(m_hPmtCalibrationFileName); else if(m_hPmtCalibrationSource == "here" || m_hPmtCalibrationSource == "database") return parsePmtCalibrationValues(m_hPmtCalibrationValues); } bool XmlConfig::verifyPmtCalibrationTable() { int iFirstPmt = INT_MAX, iLastPmt = 1; if(m_iFirstTopPmt != -1) { iFirstPmt = min(iFirstPmt, m_iFirstTopPmt); iLastPmt = max(iLastPmt, m_iFirstTopPmt); } if(m_iFirstBottomPmt != -1) { iFirstPmt = min(iFirstPmt, m_iFirstBottomPmt); iLastPmt = max(iLastPmt, m_iFirstBottomPmt); } if(m_iFirstTopVetoPmt != -1) { iFirstPmt = min(iFirstPmt, m_iFirstTopVetoPmt); iLastPmt = max(iLastPmt, m_iFirstTopVetoPmt); } if(m_iFirstBottomVetoPmt != -1) { iFirstPmt = min(iFirstPmt, m_iFirstBottomVetoPmt); iLastPmt = max(iLastPmt, m_iFirstBottomVetoPmt); } for(int iPmt = iFirstPmt; iPmt <= iLastPmt; iPmt++) { if(m_hPmtCalibrationTable.count(iPmt) != 1) { cout << "xml config error: pmt calibration table failed sanity check!" << endl; return false; } } return true; } bool XmlConfig::parseValueList(const std::string &hString, std::vector<float> &hValues) { stringstream hTmp(hString); string::size_type hNextDigit = hTmp.str().find_first_of("-0123456789"); hTmp.seekg(hNextDigit); hValues.clear(); float fValue; while(!hTmp.eof() && hTmp.good()) { hTmp >> fValue; hValues.push_back(fValue); // find the next digit hTmp.seekg(hTmp.str().find_first_of("-0123456789", hTmp.tellg())); } return true; } bool XmlConfig::parseRelativeEfficienciesString(const std::string &hString, RelativeEfficienciesTable &hRelativeEfficienciesTable) { stringstream hTmp(hString); string::size_type hNextDigit = hTmp.str().find_first_of("0123456789"); hTmp.seekg(hNextDigit); hRelativeEfficienciesTable.clear(); while(!hTmp.eof() && hTmp.good()) { // get the pmt range int iFirstPmt, iLastPmt; hTmp >> iFirstPmt; if(hTmp.peek() == '-') { hTmp.ignore(); hTmp >> iLastPmt; } else iLastPmt = iFirstPmt; // get the external gain float fRelativeSensitivity; hTmp.ignore(); hTmp >> fRelativeSensitivity; for(int iPmt = iFirstPmt; iPmt <= iLastPmt; iPmt++) hRelativeEfficienciesTable[iPmt] = fRelativeSensitivity; // find the next digit hTmp.seekg(hTmp.str().find_first_of("0123456789", hTmp.tellg())); } return true; } #ifdef ENABLE_LIQ_SCI void XmlConfig::parseLiqSciMultiplexingWindowsString(const string &hString, LiqSciMultiplexingTable &hLiqSciMultiplexingTable) { // create the header m_hLiqSciMultiplexingTableHeader.clear(); m_hLiqSciMultiplexingTableHeader.push_back("window_start"); m_hLiqSciMultiplexingTableHeader.push_back("window_width"); m_hLiqSciMultiplexingTable.clear(); string::size_type hPos = 0; string::size_type hColonPos; // find the next colon while((hColonPos = hString.find(":", hPos)) != string::npos) { stringstream hTmp; hTmp.clear(); hTmp.str(hString.substr(hPos, hColonPos-hPos)); // get the liquid scintillator channel range int iFirstLiqSciChannel, iLastLiqSciChannel; hTmp >> iFirstLiqSciChannel; if(hTmp.peek() == '-') { hTmp.ignore(); hTmp >> iLastLiqSciChannel; } else iLastLiqSciChannel = iFirstLiqSciChannel; hPos = hColonPos+1; string::size_type hCommaPos; hTmp.clear(); if((hCommaPos = hString.find(",", hPos)) != string::npos) hTmp.str(hString.substr(hPos+1, hCommaPos-hPos-2)); else hTmp.str(hString.substr(hPos+1, hString.size()-hPos-2)); // get the liquid scintillator multiplexing parameters while(!hTmp.eof()) { LiqSciMultiplexingTableEntry hLiqSciMultiplexingTableEntry; LiqSciMultiplexingTableHeader::iterator pColumn; for(pColumn = m_hLiqSciMultiplexingTableHeader.begin(); pColumn != m_hLiqSciMultiplexingTableHeader.end(); pColumn++) { int iValue = 0; hTmp >> iValue; if(hTmp.fail()) break; hLiqSciMultiplexingTableEntry.push_back(iValue); } if(!hTmp.fail()) { // store them in the pmt calibration table for(int iLiqSciChannel = iFirstLiqSciChannel; iLiqSciChannel <= iLastLiqSciChannel; iLiqSciChannel++) m_hLiqSciMultiplexingTable.push_back(hLiqSciMultiplexingTableEntry); } } hPos = hCommaPos+1; if(hCommaPos == string::npos) break; } } bool XmlConfig::verifyLiqSciMultiplexingTable() { if(m_bLiqSciMultiplexed && (m_hLiqSciMultiplexingTable.size() != m_iNbLiqScis)) { cout << "xml config error: liquid scintillator multiplexing table failed sanity check!" << endl; return false; } return true; } #endif #ifdef ENABLE_TAC void XmlConfig::parseTacCalibrationString(const std::string &hString, TacCalibrationTable &hTacCalibrationTable) { // create the header m_hTacCalibrationTableHeader.clear(); m_hTacCalibrationTableHeader.push_back("intercept"); m_hTacCalibrationTableHeader.push_back("slope"); m_hTacCalibrationTable.clear(); string::size_type hPos = 0; string::size_type hColonPos; // find the next colon while((hColonPos = hString.find(":", hPos)) != string::npos) { stringstream hTmp; hTmp.clear(); hTmp.str(hString.substr(hPos, hColonPos-hPos)); // get the channel range int iFirstChannel, iLastChannel; hTmp >> iFirstChannel; if(hTmp.peek() == '-') { hTmp.ignore(); hTmp >> iLastChannel; } else iLastChannel = iFirstChannel; hPos = hColonPos+1; string::size_type hCommaPos; hTmp.clear(); if((hCommaPos = hString.find(",", hPos)) != string::npos) hTmp.str(hString.substr(hPos+1, hCommaPos-hPos-2)); else hTmp.str(hString.substr(hPos+1, hString.size()-hPos-2)); // get the time to amplitude converter calibration parameters while(!hTmp.eof()) { TacCalibrationTableEntry hTacCalibrationTableEntry; TacCalibrationTableHeader::iterator pColumn; for(pColumn = m_hTacCalibrationTableHeader.begin(); pColumn != m_hTacCalibrationTableHeader.end(); pColumn++) { float fValue = 0.; hTmp >> fValue; if(hTmp.fail()) break; hTacCalibrationTableEntry.push_back(fValue); } if(!hTmp.fail()) { // store them in the pmt calibration table for(int iChannel = iFirstChannel; iChannel <= iLastChannel; iChannel++) m_hTacCalibrationTable.push_back(hTacCalibrationTableEntry); } } hPos = hCommaPos+1; if(hCommaPos == string::npos) break; } } bool XmlConfig::verifyTacCalibrationTable() { #ifdef ENABLE_LIQ_SCI if(m_hTacCalibrationTable.size() != (m_bLiqSciMultiplexed)?(m_iNbLiqScis):(m_iNbTacs)) { cout << "xml config error: time to amplitude converter calibration table failed sanity check!" << endl; return false; } #else if(m_hTacCalibrationTable.size() != m_iNbTacs) { cout << "xml config error: time to amplitude converter calibration table failed sanity check!" << endl; return false; } #endif return true; } #endif
[ "mda2149@columbia.edu" ]
mda2149@columbia.edu
ed878a123ed7de3787f8817c4e04db6368d7d043
0a1fb9fcfcbff0482dbbb4094d0ef00a3ccc6b05
/SoundBoard/SoundBoard/SoundButtonGroup.cpp
6f7df74968d52bbb4bc72851e1d5e49ca3161481
[ "LicenseRef-scancode-other-permissive", "LicenseRef-scancode-unknown-license-reference" ]
permissive
honky/SoftwareProjektTUBAF2013
4bd9f844e29d417059a8b4886afa8d233bb45200
1687ba77fa417fde7aa36477da4070bf9d3efa8d
refs/heads/master
2021-01-22T23:26:02.752793
2014-01-10T15:35:17
2014-01-10T15:35:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
623
cpp
#include "StdAfx.h" #include "SoundButtonGroup.h" namespace SoundBoard { SoundButtonGroup::SoundButtonGroup(String^ name) { this->name = name; this->Text = System::IO::Path::GetFileName(name); this->buttons = gcnew List<SoundButton^>(); this->Anchor = Windows::Forms::AnchorStyles::Right; this->flPanel = gcnew Windows::Forms::FlowLayoutPanel(); this->flPanel->Dock = Windows::Forms::DockStyle::Fill; this->Controls->Add(flPanel); this->Width = 375; this->Height= 50; } void SoundButtonGroup::addSoundButton(SoundButton^ sb) { this->buttons->Add(sb); this->flPanel->Controls->Add(sb); } }
[ "plotterhairy@googlemail.com" ]
plotterhairy@googlemail.com
2322795c69447304f98a125f432021f19d987086
7277d930b74618a0e09a5f5c345c0237bc092bb0
/VirtualContest/20200521/abc137/c/main.cpp
914fec8dd98e34bd856fa0df8309e1f242f6d451
[]
no_license
fhiroki/atcoder
78bccbdc10e2ca94543c965cc53874c2e99f32af
aaf50382f3c4008cd48183a06f480a103c623a7b
refs/heads/master
2022-03-13T04:21:16.570731
2022-02-13T01:20:33
2022-02-13T01:20:33
245,597,349
0
0
null
null
null
null
UTF-8
C++
false
false
403
cpp
#include <bits/stdc++.h> #define rep(i, n) for (int i = 0; i < n; i++) typedef long long ll; using namespace std; int main() { int n; cin >> n; map<string, ll> a; rep(i, n) { string s; cin >> s; sort(s.begin(), s.end()); a[s]++; } ll ans = 0; for (auto c : a) ans += c.second * (c.second - 1) / 2; cout << ans << endl; return 0; }
[ "hiroki976@gmail.com" ]
hiroki976@gmail.com
14e79e4cf861dd7412ad71586386eacd4e80a20f
b99f7ba8dbe2c6a43edf510066c76df0d4980b60
/Maths3D/Sommet.hpp
84840b3379d11831b5e67275a2d19377f9af7f72
[]
no_license
anthonybazelle/VoronoiAndDelaunay
860900d38a79c0b726fc8cbc892c84546984b746
98cb9efa27af3c107a9f634b6e0737def0519c8b
refs/heads/master
2021-08-28T15:18:43.050791
2017-12-12T15:20:25
2017-12-12T15:20:25
111,926,526
0
0
null
null
null
null
UTF-8
C++
false
false
824
hpp
#include "Cote.hpp" class Sommet { // each point connected to edges private: Point point; std::vector<Cote*> * edgesConnected; Couleur color; public: Sommet() { edgesConnected = new std::vector<Cote*>(); } Sommet(Point p) { point = p; edgesConnected = new std::vector<Cote*>(); } Sommet(Couleur c, Point p) { color = c; point = p; } Sommet(Couleur c, std::vector<Cote*> *e, Point p) { color = c; edgesConnected = e; point = p; } void setPoint(const Point & p) { point = p; } Point getPoint() { return point; } void setColor(const Couleur & c) { color = c; } const Couleur & getColor() const { return color; } void setEdgesConnected(std::vector<Cote*> * f) { edgesConnected = f; } std::vector<Cote*> * getEdgesConnected() { return edgesConnected; } };
[ "pourrier789@gmail.com" ]
pourrier789@gmail.com
752c20ba2f29905548f6f1a935dfbbe14986d34d
505446850988c792bc5d13bc0252b4a74c5eb7a3
/p1.cpp
3cce7f39f15720f47f8701e87ffe5cb2a6cfaca3
[]
no_license
CED-9/Temp
c67691b7a06b2f46aecb7aae8fa7ff62ea9a1638
3a49433ebbeaa50a1e6976009c17a6c1c1a01630
refs/heads/master
2018-12-29T20:44:02.870165
2015-01-17T04:07:35
2015-01-17T04:07:35
29,379,263
0
0
null
null
null
null
UTF-8
C++
false
false
1,522
cpp
#include <iostream> #include"thread.h" #include<vector> #include<ifstream> #include<string> using namespace std; struct Requester{ int id; string name; }; mutex mutex1; //cv cv1; vector <int> done; // global variable; shared between the all threads. //vector <Requester> rqs; vector <int> waitQueue; void sentRq(int track){ waitQueue.push_back(track); } void requester(void *id) { int * message = (int *) id; vector<int> input; ifstream fin; fin.open(argv[i+2]); while(line = fin.getline()){ input.push_back(atoi(line)); } fin.close(); // enter critical section mutex1.lock(); for (int i = 0; i < input.size(); i++) { sentRq(input[i]); cout << "requester " << id << " track " << input[i] << endl; } done[id] = 1; cv1.signal(); mutex1.unlock(); } void service(void *numRq) { mutex1.lock(); while (!child_done) { cout << "parent waiting for child to run\n"; cv1.wait(mutex1); } cout << "parent finishing" << endl; mutex1.unlock(); } int main(int argc, char* argv[]) { int numRq = argc - 2; // initialize the global record for (int i = 0; i < numRq; i++) { done.push_back(0); } // Trigger service's thread cpu::boot((thread_startfunc_t) service, (void *) numRq, 0); // Trigger requesters' threads ifstream fin; for(int i = 0; i < numRq; i++){ Requester rq; rq.id = i; rq.name = (string)argv[i+2]; //rqs.push_back(rq); thread requester_t ((thread_startfunc_t) requester, (void *) rq ); } for (int i = 0; i < numRq; i++) { //join(); } return 0; }
[ "liujm@umich.edu" ]
liujm@umich.edu
e08b701ec1a743f08718743ae56b168b60903372
a30af10abb2abe1ab4894f6513eee96e9f7b72e7
/lab5/assignment2/src/kernel/setup.cpp
7f1f68b716af4694c70b0849a4b656bf2d0b4d9b
[]
no_license
avarpow/OS_lab
740a2fe4801e049332fda3d11285101fd5303293
af61a11fad855607fac8879bdfa8827ae9078339
refs/heads/main
2023-06-24T21:43:08.612078
2021-07-16T16:39:11
2021-07-16T16:39:11
348,664,354
1
0
null
null
null
null
UTF-8
C++
false
false
2,184
cpp
#include "asm_utils.h" #include "interrupt.h" #include "stdio.h" #include "program.h" #include "thread.h" // 屏幕IO处理器 STDIO stdio; // 中断管理器 InterruptManager interruptManager; // 程序管理器 ProgramManager programManager; void third_thread(void *arg) { printf("pid %d name \"%s\": Hello third World!\n", programManager.running->pid, programManager.running->name); int k=10; while(k--) { printf("pid %d name \"%s\": Hello third World!\n", programManager.running->pid, programManager.running->name); for(int i=0;i<100000000;i++); } } void second_thread(void *arg) { printf("pid %d name \"%s\": Hello second World!\n", programManager.running->pid, programManager.running->name); int k=10; while(k--) { printf("pid %d name \"%s\": Hello second World!\n", programManager.running->pid, programManager.running->name); for(int i=0;i<100000000;i++); } } void first_thread(void *arg) { // 第1个线程不可以返回 printf("pid %d name \"%s\": Hello first World!\n", programManager.running->pid, programManager.running->name); if (!programManager.running->pid) { programManager.executeThread(second_thread, nullptr, "second thread", 3); programManager.executeThread(third_thread, nullptr, "third thread", 20); } asm_halt(); } extern "C" void setup_kernel() { // 中断管理器 interruptManager.initialize(); interruptManager.enableTimeInterrupt(); interruptManager.setTimeInterrupt((void *)asm_time_interrupt_handler); // 输出管理器 stdio.initialize(); // 进程/线程管理器 programManager.initialize(); // 创建第一个线程 int pid = programManager.executeThread(first_thread, nullptr, "first thread", 1); if (pid == -1) { printf("can not execute thread\n"); asm_halt(); } ListItem *item = programManager.readyPrograms.front(); PCB *firstThread = ListItem2PCB(item, tagInGeneralList); firstThread->status = RUNNING; programManager.readyPrograms.pop_front(); programManager.running = firstThread; asm_switch_thread(0, firstThread); asm_halt(); }
[ "648120201@qq.com" ]
648120201@qq.com
42b7a4beaa0aa7c72a3c602c78798b17139c55ba
3f7ec296f05234f6a2dbcfa0611771f789e9535d
/secsymboldescription.h
3212c3b8e2e6ad63866c338c9c6a1aaa69b8311f
[]
no_license
NikolayKuksa/stock
b12a4ba5c2d3d89e8e1196521817d75638da17e0
5beddd9f467b3254b1f0fa7e3b208e65f7ccc95e
refs/heads/master
2021-01-19T23:25:46.024404
2017-06-10T09:12:40
2017-06-10T09:12:40
88,982,716
0
0
null
null
null
null
UTF-8
C++
false
false
585
h
#ifndef SECSYMBOLDESCRIPTION_H #define SECSYMBOLDESCRIPTION_H #include <QVector> #include "securitytype.h" #include "miscdef.h" class SecSymbolDescription { private: QVector<QString> securitySymbols; QVector<QString> indexSymbols; QVector<QString> securityDescriptions; QVector<QString> indexDescriptions; public: SecSymbolDescription(); QString getSymbol(int ix, SecurityType secType); int addSecurity(QString symbol, QString description,SecurityType); QStringList getAllDescriptions(SecurityType secType); }; #endif // SECSYMBOLDESCRIPTION_H
[ "nick.k@i.ua" ]
nick.k@i.ua
bdd0077d572c713ce9f19ee63c024a8e07e8d5f9
40db2023c173aebe109d3d0804b1cf09b38ec8a0
/min_max_sum.cpp
58007f00c328f6b0cb24f9e69ce1efcd78b89c81
[]
no_license
kumarmeet/competative-programming-CPP-mysirg
905de091d176665f50824673da97deee0890e0dd
80e5d0b7c7d0048db56c05a082d6211923463a19
refs/heads/main
2023-07-30T20:14:05.064066
2021-09-20T17:19:08
2021-09-20T17:19:08
403,526,301
0
0
null
null
null
null
UTF-8
C++
false
false
667
cpp
#include <bits/stdc++.h> using namespace std; class DataSet { private: int *p; int n; public: DataSet(int n) { this->n = n; this->p = new int[this->n]; int val; for(int i = 0; i < n; i++){ cin>>val; p[i] = val; } } int operator[](string s){ if(s == "min"){ return *min_element(p, p + this->n); } else if(s == "max"){ return *max_element(p, p + this->n); } else if(s == "sum"){ int sum{0}; for(int i = 0; i < n; i++) sum += p[i]; return sum; } } };
[ "noreply@github.com" ]
kumarmeet.noreply@github.com
d4f476118e01ebfc2197b656538e071111bbb5ed
be3167504c0e32d7708e7d13725c2dbc9232f2cb
/mameppk/src/osd/sdl/osdsdl.h
61136a6680b38e6e93c02684c85a89b5f7dcbd4f
[]
no_license
sysfce2/MAME-Plus-Plus-Kaillera
83b52085dda65045d9f5e8a0b6f3977d75179e78
9692743849af5a808e217470abc46e813c9068a5
refs/heads/master
2023-08-10T06:12:47.451039
2016-08-01T09:44:21
2016-08-01T09:44:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,063
h
// license:BSD-3-Clause // copyright-holders:Olivier Galibert, R. Belmont #ifndef _osdsdl_h_ #define _osdsdl_h_ #include "sdlinc.h" #include "watchdog.h" #include "clifront.h" #include "modules/lib/osdobj_common.h" #include "modules/osdmodule.h" #include "modules/font/font_module.h" //============================================================ // System dependent defines //============================================================ #if defined(SDLMAME_WIN32) #if (SDLMAME_SDL2) #define SDLMAME_EVENTS_IN_WORKER_THREAD (0) #define SDLMAME_INIT_IN_WORKER_THREAD (0) #define SDL13_COMBINE_RESIZE (0) //(1) no longer needed #else #define SDLMAME_EVENTS_IN_WORKER_THREAD (0) #define SDLMAME_INIT_IN_WORKER_THREAD (1) #define SDL13_COMBINE_RESIZE (0) #endif #else #define SDLMAME_EVENTS_IN_WORKER_THREAD (0) #define SDLMAME_INIT_IN_WORKER_THREAD (0) #define SDL13_COMBINE_RESIZE (0) #endif //============================================================ // Defines //============================================================ #define SDLOPTION_INIPATH "inipath" #define SDLOPTION_SDLVIDEOFPS "sdlvideofps" #define SDLOPTION_USEALLHEADS "useallheads" #define SDLOPTION_CENTERH "centerh" #define SDLOPTION_CENTERV "centerv" #define SDLOPTION_SCALEMODE "scalemode" #define SDLOPTION_WAITVSYNC "waitvsync" #define SDLOPTION_SYNCREFRESH "syncrefresh" #define SDLOPTION_KEYMAP "keymap" #define SDLOPTION_KEYMAP_FILE "keymap_file" #define SDLOPTION_SIXAXIS "sixaxis" #define SDLOPTION_JOYINDEX "joy_idx" #define SDLOPTION_KEYBINDEX "keyb_idx" #define SDLOPTION_MOUSEINDEX "mouse_index" #if (USE_XINPUT) #define SDLOPTION_LIGHTGUNINDEX "lightgun_index" #endif #define SDLOPTION_AUDIODRIVER "audiodriver" #define SDLOPTION_VIDEODRIVER "videodriver" #define SDLOPTION_RENDERDRIVER "renderdriver" #define SDLOPTION_GL_LIB "gl_lib" #define SDLOPTVAL_OPENGL "opengl" #define SDLOPTVAL_SOFT "soft" #define SDLOPTVAL_SDL2ACCEL "accel" #define SDLOPTVAL_BGFX "bgfx" #define SDLMAME_LED(x) "led" #x // read by sdlmame #define SDLENV_DESKTOPDIM "SDLMAME_DESKTOPDIM" #define SDLENV_VMWARE "SDLMAME_VMWARE" // set by sdlmame #define SDLENV_VISUALID "SDL_VIDEO_X11_VISUALID" #define SDLENV_VIDEODRIVER "SDL_VIDEODRIVER" #define SDLENV_AUDIODRIVER "SDL_AUDIODRIVER" #define SDLENV_RENDERDRIVER "SDL_VIDEO_RENDERER" #define SDLMAME_SOUND_LOG "sound.log" #ifdef SDLMAME_MACOSX /* Vas Crabb: Default GL-lib for MACOSX */ #define SDLOPTVAL_GLLIB "/System/Library/Frameworks/OpenGL.framework/Libraries/libGL.dylib" #else #define SDLOPTVAL_GLLIB OSDOPTVAL_AUTO #endif //============================================================ // TYPE DEFINITIONS //============================================================ class sdl_options : public osd_options { public: // construction/destruction sdl_options(); // performance options bool video_fps() const { return bool_value(SDLOPTION_SDLVIDEOFPS); } // video options bool centerh() const { return bool_value(SDLOPTION_CENTERH); } bool centerv() const { return bool_value(SDLOPTION_CENTERV); } const char *scale_mode() const { return value(SDLOPTION_SCALEMODE); } // full screen options #ifdef SDLMAME_X11 bool use_all_heads() const { return bool_value(SDLOPTION_USEALLHEADS); } #endif // keyboard mapping bool keymap() const { return bool_value(SDLOPTION_KEYMAP); } const char *keymap_file() const { return value(SDLOPTION_KEYMAP_FILE); } // joystick mapping const char *joy_index(int index) const { std::string temp; return value(strformat(temp, "%s%d", SDLOPTION_JOYINDEX, index).c_str()); } bool sixaxis() const { return bool_value(SDLOPTION_SIXAXIS); } #if (SDLMAME_SDL2) const char *mouse_index(int index) const { std::string temp; return value(strformat(temp, "%s%d", SDLOPTION_MOUSEINDEX, index).c_str()); } const char *keyboard_index(int index) const { std::string temp; return value(strformat(temp, "%s%d", SDLOPTION_KEYBINDEX, index).c_str()); } #endif const char *video_driver() const { return value(SDLOPTION_VIDEODRIVER); } const char *render_driver() const { return value(SDLOPTION_RENDERDRIVER); } const char *audio_driver() const { return value(SDLOPTION_AUDIODRIVER); } #if USE_OPENGL const char *gl_lib() const { return value(SDLOPTION_GL_LIB); } #endif private: static const options_entry s_option_entries[]; }; class sdl_osd_interface : public osd_common_t { public: // construction/destruction sdl_osd_interface(sdl_options &options); virtual ~sdl_osd_interface(); // general overridables virtual void init(running_machine &machine); virtual void update(bool skip_redraw); // input overridables virtual void customize_input_type_list(simple_list<input_type_entry> &typelist); virtual void video_register(); virtual bool video_init(); virtual bool window_init(); virtual bool input_init(); virtual void input_pause(); virtual void input_resume(); virtual bool output_init(); //virtual bool midi_init(); virtual void video_exit(); virtual void window_exit(); virtual void input_exit(); virtual void output_exit(); //virtual void midi_exit(); sdl_options &options() { return m_options; } private: virtual void osd_exit(); void extract_video_config(); sdl_options &m_options; watchdog *m_watchdog; }; //============================================================ // sdlwork.c //============================================================ extern int osd_num_processors; #endif
[ "mameppk@199a702f-54f1-4ac0-8451-560dfe28270b" ]
mameppk@199a702f-54f1-4ac0-8451-560dfe28270b
2b7804a1324a969f005552394f8167f5320aff47
ab1c643f224197ca8c44ebd562953f0984df321e
/wmi/wbem/providers/snmpprovider/provider/instclas/include/clasprov.h
4b3e2af7e419f8a7f31d1786fe11382193054b60
[]
no_license
KernelPanic-OpenSource/Win2K3_NT_admin
e162e0452fb2067f0675745f2273d5c569798709
d36e522f16bd866384bec440517f954a1a5c4a4d
refs/heads/master
2023-04-12T13:25:45.807158
2021-04-13T16:33:59
2021-04-13T16:33:59
357,613,696
0
1
null
null
null
null
UTF-8
C++
false
false
9,901
h
//*************************************************************************** // // PropertyProvider.H // // Module: Sample Mini Server for Ole MS // // Purpose: Genral purpose include file. // // Copyright (c) 1996-2001 Microsoft Corporation, All Rights Reserved // //*************************************************************************** #ifndef _SNMPClassProvider_H_ #define _SNMPClassProvider_H_ extern CRITICAL_SECTION s_ProviderCriticalSection ; class SnmpClassDefaultThreadObject : public SnmpThreadObject { private: protected: public: SnmpClassDefaultThreadObject ( const char *threadName = NULL ) : SnmpThreadObject ( threadName ) {} ; ~SnmpClassDefaultThreadObject () {} ; void Initialise () ; void Uninitialise () { CoUninitialize () ; } } ; class CImpClasProv : public IWbemServices , public IWbemProviderInit { private: LONG m_referenceCount ; //Object reference count private: BOOL initialised ; IWbemServices *propertyProvider ; IWbemServices *server ; IWbemServices *parentServer ; IWbemProviderInitSink *m_InitSink ; char *ipAddressString ; char *ipAddressValue ; wchar_t *thisNamespace ; WbemNamespacePath namespacePath ; CCriticalSection m_notificationLock; CCriticalSection m_snmpNotificationLock; IWbemClassObject *m_notificationClassObject ; IWbemClassObject *m_snmpNotificationClassObject ; BOOL m_getNotifyCalled ; BOOL m_getSnmpNotifyCalled ; private: HRESULT SetServer ( IWbemServices *serverArg ) ; HRESULT SetParentServer ( IWbemServices *parentServerArg ) ; BOOL AttachParentServer ( WbemSnmpErrorObject &a_errorObject , BSTR ObjectPath, IWbemContext *pCtx ) ; BOOL ObtainCachedIpAddress ( WbemSnmpErrorObject &a_errorObject ) ; protected: public: CImpClasProv () ; ~CImpClasProv () ; void SetProvider ( IWbemServices *provider ) ; IWbemServices *GetParentServer () ; IWbemServices *GetServer () ; WbemNamespacePath *GetNamespacePath () ; wchar_t *GetThisNamespace () ; void SetThisNamespace ( wchar_t *thisNamespaceArg ) ; char *GetIpAddressString () { return ipAddressString ; } char *GetIpAddressValue () { return ipAddressValue ; } BOOL FetchSnmpNotificationObject ( WbemSnmpErrorObject &a_errorObject , IWbemContext *a_Ctx ) ; BOOL FetchNotificationObject ( WbemSnmpErrorObject &a_errorObject , IWbemContext *a_Ctx ) ; IWbemClassObject *GetNotificationObject ( WbemSnmpErrorObject &a_errorObject ) ; IWbemClassObject *GetSnmpNotificationObject ( WbemSnmpErrorObject &a_errorObject ) ; public: static BOOL s_Initialised ; //Non-delegating object IUnknown STDMETHODIMP QueryInterface ( REFIID , LPVOID FAR * ) ; STDMETHODIMP_( ULONG ) AddRef () ; STDMETHODIMP_( ULONG ) Release () ; public: /* IWbemServices methods */ HRESULT STDMETHODCALLTYPE OpenNamespace( /* [in] */ const BSTR Namespace, /* [in] */ long lFlags, /* [in] */ IWbemContext __RPC_FAR *pCtx, /* [unique][in][out] */ IWbemServices __RPC_FAR *__RPC_FAR *ppWorkingNamespace, /* [unique][in][out] */ IWbemCallResult __RPC_FAR *__RPC_FAR *ppResult) ; HRESULT STDMETHODCALLTYPE CancelAsyncCall( /* [in] */ IWbemObjectSink __RPC_FAR *pSink) ; HRESULT STDMETHODCALLTYPE QueryObjectSink( /* [in] */ long lFlags, /* [out] */ IWbemObjectSink __RPC_FAR *__RPC_FAR *ppResponseHandler) ; HRESULT STDMETHODCALLTYPE GetObject( /* [in] */ const BSTR ObjectPath, /* [in] */ long lFlags, /* [in] */ IWbemContext __RPC_FAR *pCtx, /* [unique][in][out] */ IWbemClassObject __RPC_FAR *__RPC_FAR *ppObject, /* [unique][in][out] */ IWbemCallResult __RPC_FAR *__RPC_FAR *ppCallResult) ; HRESULT STDMETHODCALLTYPE GetObjectAsync( /* [in] */ const BSTR ObjectPath, /* [in] */ long lFlags, /* [in] */ IWbemContext __RPC_FAR *pCtx, /* [in] */ IWbemObjectSink __RPC_FAR *pResponseHandler) ; HRESULT STDMETHODCALLTYPE PutClass( /* [in] */ IWbemClassObject __RPC_FAR *pObject, /* [in] */ long lFlags, /* [in] */ IWbemContext __RPC_FAR *pCtx, /* [unique][in][out] */ IWbemCallResult __RPC_FAR *__RPC_FAR *ppCallResult) ; HRESULT STDMETHODCALLTYPE PutClassAsync( /* [in] */ IWbemClassObject __RPC_FAR *pObject, /* [in] */ long lFlags, /* [in] */ IWbemContext __RPC_FAR *pCtx, /* [in] */ IWbemObjectSink __RPC_FAR *pResponseHandler) ; HRESULT STDMETHODCALLTYPE DeleteClass( /* [in] */ const BSTR Class, /* [in] */ long lFlags, /* [in] */ IWbemContext __RPC_FAR *pCtx, /* [unique][in][out] */ IWbemCallResult __RPC_FAR *__RPC_FAR *ppCallResult) ; HRESULT STDMETHODCALLTYPE DeleteClassAsync( /* [in] */ const BSTR Class, /* [in] */ long lFlags, /* [in] */ IWbemContext __RPC_FAR *pCtx, /* [in] */ IWbemObjectSink __RPC_FAR *pResponseHandler) ; HRESULT STDMETHODCALLTYPE CreateClassEnum( /* [in] */ const BSTR Superclass, /* [in] */ long lFlags, /* [in] */ IWbemContext __RPC_FAR *pCtx, /* [out] */ IEnumWbemClassObject __RPC_FAR *__RPC_FAR *ppEnum) ; HRESULT STDMETHODCALLTYPE CreateClassEnumAsync( /* [in] */ const BSTR Superclass, /* [in] */ long lFlags, /* [in] */ IWbemContext __RPC_FAR *pCtx, /* [in] */ IWbemObjectSink __RPC_FAR *pResponseHandler) ; HRESULT STDMETHODCALLTYPE PutInstance( /* [in] */ IWbemClassObject __RPC_FAR *pInst, /* [in] */ long lFlags, /* [in] */ IWbemContext __RPC_FAR *pCtx, /* [unique][in][out] */ IWbemCallResult __RPC_FAR *__RPC_FAR *ppCallResult) ; HRESULT STDMETHODCALLTYPE PutInstanceAsync( /* [in] */ IWbemClassObject __RPC_FAR *pInst, /* [in] */ long lFlags, /* [in] */ IWbemContext __RPC_FAR *pCtx, /* [in] */ IWbemObjectSink __RPC_FAR *pResponseHandler) ; HRESULT STDMETHODCALLTYPE DeleteInstance( /* [in] */ const BSTR ObjectPath, /* [in] */ long lFlags, /* [in] */ IWbemContext __RPC_FAR *pCtx, /* [unique][in][out] */ IWbemCallResult __RPC_FAR *__RPC_FAR *ppCallResult) ; HRESULT STDMETHODCALLTYPE DeleteInstanceAsync( /* [in] */ const BSTR ObjectPath, /* [in] */ long lFlags, /* [in] */ IWbemContext __RPC_FAR *pCtx, /* [in] */ IWbemObjectSink __RPC_FAR *pResponseHandler) ; HRESULT STDMETHODCALLTYPE CreateInstanceEnum( /* [in] */ const BSTR Class, /* [in] */ long lFlags, /* [in] */ IWbemContext __RPC_FAR *pCtx, /* [out] */ IEnumWbemClassObject __RPC_FAR *__RPC_FAR *ppEnum) ; HRESULT STDMETHODCALLTYPE CreateInstanceEnumAsync( /* [in] */ const BSTR Class, /* [in] */ long lFlags, /* [in] */ IWbemContext __RPC_FAR *pCtx, /* [in] */ IWbemObjectSink __RPC_FAR *pResponseHandler) ; HRESULT STDMETHODCALLTYPE ExecQuery( /* [in] */ const BSTR QueryLanguage, /* [in] */ const BSTR Query, /* [in] */ long lFlags, /* [in] */ IWbemContext __RPC_FAR *pCtx, /* [out] */ IEnumWbemClassObject __RPC_FAR *__RPC_FAR *ppEnum) ; HRESULT STDMETHODCALLTYPE ExecQueryAsync( /* [in] */ const BSTR QueryLanguage, /* [in] */ const BSTR Query, /* [in] */ long lFlags, /* [in] */ IWbemContext __RPC_FAR *pCtx, /* [in] */ IWbemObjectSink __RPC_FAR *pResponseHandler) ; HRESULT STDMETHODCALLTYPE ExecNotificationQuery( /* [in] */ const BSTR QueryLanguage, /* [in] */ const BSTR Query, /* [in] */ long lFlags, /* [in] */ IWbemContext __RPC_FAR *pCtx, /* [out] */ IEnumWbemClassObject __RPC_FAR *__RPC_FAR *ppEnum) ; HRESULT STDMETHODCALLTYPE ExecNotificationQueryAsync( /* [in] */ const BSTR QueryLanguage, /* [in] */ const BSTR Query, /* [in] */ long lFlags, /* [in] */ IWbemContext __RPC_FAR *pCtx, /* [in] */ IWbemObjectSink __RPC_FAR *pResponseHandler) ; HRESULT STDMETHODCALLTYPE ExecMethod( /* [in] */ const BSTR ObjectPath, /* [in] */ const BSTR MethodName, /* [in] */ long lFlags, /* [in] */ IWbemContext __RPC_FAR *pCtx, /* [in] */ IWbemClassObject __RPC_FAR *pInParams, /* [unique][in][out] */ IWbemClassObject __RPC_FAR *__RPC_FAR *ppOutParams, /* [unique][in][out] */ IWbemCallResult __RPC_FAR *__RPC_FAR *ppCallResult) ; HRESULT STDMETHODCALLTYPE ExecMethodAsync( /* [in] */ const BSTR ObjectPath, /* [in] */ const BSTR MethodName, /* [in] */ long lFlags, /* [in] */ IWbemContext __RPC_FAR *pCtx, /* [in] */ IWbemClassObject __RPC_FAR *pInParams, /* [in] */ IWbemObjectSink __RPC_FAR *pResponseHandler) ; /* IWbemProviderInit methods */ HRESULT STDMETHODCALLTYPE Initialize ( /* [in] */ LPWSTR pszUser, /* [in] */ LONG lFlags, /* [in] */ LPWSTR pszNamespace, /* [in] */ LPWSTR pszLocale, /* [in] */ IWbemServices *pCIMOM, // For anybody /* [in] */ IWbemContext *pCtx, /* [in] */ IWbemProviderInitSink *pInitSink // For init signals ); } ; #endif
[ "polarisdp@gmail.com" ]
polarisdp@gmail.com
7eb154e0971736f90fd8e1624a9f14a56af7a73b
83421eb1258fdbf93289d57b11a4160794664d7a
/src/general/mapa/Cubo.h
47043b7289a413dadfb3c96aafe11a95b6907c41
[]
no_license
BlenderCN-Org/nature
2511efdb56e0a1b61c363f7e6caf5f29a6a820a2
c7976a533e299baf1473775a592c892feefba853
refs/heads/master
2020-05-23T21:29:00.591053
2015-07-11T06:20:39
2015-07-11T06:20:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
516
h
#ifndef _CUBO_H_ #define _CUBO_H_ #include "includeglm.h" #include <iostream> class Cubo{ public: glm::vec3 p1;//punto glm::vec3 p2;//tamanio glm::vec3 t;//tamanio glm::vec3 c;//centro Cubo(glm::vec3 p1,glm::vec3 t){ set(p1,t); } void set(glm::vec3 p1,glm::vec3 t){ this->p1=p1; this->t=t; this->p2=p1+t; c=p1+(t*0.5f); } }; std::ostream& operator<<(std::ostream& o,Cubo c); #endif
[ "forestmedina@gmail.com" ]
forestmedina@gmail.com
a13af8fb866b898e201b39f960149a23b793e1ae
9be246df43e02fba30ee2595c8cec14ac2b355d1
/game_shared/tf2/tf_obj_base_manned_gun.h
4e2a72abc1d43f9ce90b2f6ece51b0fdc47ea795
[]
no_license
Clepoy3/LeakNet
6bf4c5d5535b3824a350f32352f457d8be87d609
8866efcb9b0bf9290b80f7263e2ce2074302640a
refs/heads/master
2020-05-30T04:53:22.193725
2019-04-12T16:06:26
2019-04-12T16:06:26
189,544,338
18
5
null
2019-05-31T06:59:39
2019-05-31T06:59:39
null
WINDOWS-1252
C++
false
false
5,003
h
//========= Copyright © 1996-2002, Valve LLC, All rights reserved. ============ // // Purpose: A stationary gun that players can man // // $NoKeywords: $ //============================================================================= #ifndef TF_OBJ_BASE_MANNED_GUN_H #define TF_OBJ_BASE_MANNED_GUN_H #ifdef _WIN32 #pragma once #endif #include "basetfvehicle.h" #include "tf_obj_manned_plasmagun_shared.h" #include "env_laserdesignation.h" #include "beam_shared.h" class CMoveData; #if defined( CLIENT_DLL ) #define CObjectBaseMannedGun C_ObjectBaseMannedGun #define CBaseTFVehicle C_BaseTFVehicle #endif // ------------------------------------------------------------------------ // // A stationary gun that players can man that's built by the player // ------------------------------------------------------------------------ // class CObjectBaseMannedGun : public CBaseTFVehicle { public: DECLARE_NETWORKCLASS(); DECLARE_PREDICTABLE(); DECLARE_CLASS( CObjectBaseMannedGun, CBaseTFVehicle ); CObjectBaseMannedGun(); virtual void Spawn(); virtual void Precache(); virtual void UpdateOnRemove( void ); virtual void GetControlPanelInfo( int nPanelIndex, const char *&pPanelName ); virtual bool CanTakeEMPDamage( void ) { return true; } virtual void OnGoInactive( void ); // Vehicle overrides #ifndef CLIENT_DLL virtual void SetPassenger( int nRole, CBasePlayer *pEnt ); #endif virtual bool IsPassengerVisible( int nRole = VEHICLE_DRIVER ) { return true; } // Returns the eye position virtual void GetVehicleViewPosition( int nRole, Vector *pOrigin, QAngle *pAngles ); // Manned plasma passengers aren't damagable //virtual bool IsPassengerDamagable( int nRole = VEHICLE_DRIVER ) { return false; } virtual void ProcessMovement( CBasePlayer *pPlayer, CMoveData *pMove ); virtual void SetupMove( CBasePlayer *player, CUserCmd *ucmd, IMoveHelper *pHelper, CMoveData *move ); virtual void FinishMove( CBasePlayer *player, CUserCmd *ucmd, CMoveData *move ); virtual bool ShouldAttachToParent( void ) { return true; } virtual bool MustNotBeBuiltInConstructionYard( void ) const { return true; } virtual bool ShouldUseThirdPersonVehicleView( void ); virtual void BaseMannedGunThink( void ); float GetGunYaw() const; float GetGunPitch() const; // Buff bool CanBeHookedToBuffStation( void ); #if defined ( CLIENT_DLL ) // IClientVehicle overrides. public: virtual void DrawHudElements( void ); virtual void UpdateViewAngles( C_BasePlayer *pLocalPlayer, CUserCmd *pCmd ); virtual QAngle GetPassengerAngles( QAngle angCurrent, int nRole ); // C_BaseEntity overrides. public: virtual void OnDataChanged( DataUpdateType_t updateType ); virtual void GetBoneControllers(float controllers[MAXSTUDIOBONECTRLS], float dadt); private: void DrawCrosshair( void ); #endif protected: // Sets up various attachment points once the model is selected // Derived classes should call this from within their SetTeamModel call void OnModelSelected(); // Can we get into the vehicle? virtual bool CanGetInVehicle( CBaseTFPlayer *pPlayer ); // Here's where we deal with weapons virtual void OnItemPostFrame( CBaseTFPlayer *pPassenger ); // Fire the weapon virtual void Fire( void ) {} void StopDesignating( void ); void UpdateDesignator( void ); virtual void SetupAttachedVersion( void ); virtual void SetupUnattachedVersion( void ); // Sets the movement style void SetMovementStyle( MovementStyle_t style ); // Calculate the max range of this gun void CalculateMaxRange( float flDefensiveRange, float flOffensiveRange ); protected: // Movement... CObjectMannedPlasmagunMovement m_Movement; float m_flMaxRange; // attachment points int m_nBarrelAttachment; int m_nBarrelPivotAttachment; int m_nStandAttachment; int m_nEyesAttachment; // Movement style CNetworkVar( MovementStyle_t, m_nMoveStyle ); // Barrel height... float m_flBarrelHeight; CNetworkVar( int, m_nAmmoType ); CNetworkVar( int, m_nAmmoCount ); CNetworkVar( float, m_flGunYaw ); // 0 = front, 90 = left, 180 = back, 270 = right CNetworkVar( float, m_flGunPitch ); // 0 = forward, -90 = pointing down, 90 = pointing up.. CNetworkVar( float, m_flBarrelPitch ); float m_flReturnToInitialTime; // Laser designation CNetworkHandle( CBeam, m_hBeam ); CNetworkHandle( CEnvLaserDesignation, m_hLaserDesignation ); #if defined( CLIENT_DLL ) CHudTexture *iconCrosshair; private: CObjectBaseMannedGun( const CObjectBaseMannedGun & ); // not defined, not accessible #endif }; //----------------------------------------------------------------------------- // Inline methods //----------------------------------------------------------------------------- inline bool CObjectBaseMannedGun::CanBeHookedToBuffStation( void ) { return true; } #endif // TF_OBJ_BASE_MANNED_GUN_H
[ "uavxp29@gmail.com" ]
uavxp29@gmail.com
2a7d15c6c28a4b52ac528ded4bf1d16ddbf3f85f
614369bd9a9452f6b48b9c667b12daacf153d6b8
/Minji/Programmers/QUEUE,STACK/쇠막대기.cpp
126652a90616bd71dbe8c1debb3400d5e6ce45c2
[]
no_license
minji0320/Algorithm_for_CodingTest
339ad05a81a89b2645dfab73d7bcbc2df9775d77
7fc091f93693d549fa1975044f4b4ff5ee056520
refs/heads/master
2022-06-26T05:14:27.149435
2021-06-30T00:16:38
2021-06-30T00:16:38
242,951,278
2
0
null
2020-02-25T08:43:49
2020-02-25T08:43:48
null
UTF-8
C++
false
false
544
cpp
#include <string> #include <vector> using namespace std; int solution(string arrangement) { int len = arrangement.size(); int stick = 0; int new_stick = 0; int answer = 0; for(int i = 0; i < len; i++) { if(arrangement.substr(i,2) == "()"){ answer += stick + new_stick; new_stick = 0; i++; continue; } if(arrangement[i] == '('){ stick++; new_stick++; } else stick--; } return answer; }
[ "rlaalswl0320@naver.com" ]
rlaalswl0320@naver.com
56cf9ce31a329955e8339d06ad640b15845724f6
a551c17a46705a0dbfe2c2e284bc1ae2dcd1a8bb
/iwds/iwds/jni/src/include/smartsense/sensormanager.h
c856cfb5245a5eb16f91e720c2573db4d800d8db
[]
no_license
liaokesen168/slpt
60b18542653a67c4149520aad9e3649d8a5f2154
cdc874c15e762f8cdd2f8288b7166a30f6495109
refs/heads/master
2021-01-01T05:19:51.079608
2016-04-15T08:32:10
2016-04-15T08:32:10
56,303,858
2
0
null
null
null
null
UTF-8
C++
false
false
2,085
h
/* * Copyright (C) 2014 Ingenic Semiconductor * * SunWenZhong(Fighter) <wenzhong.sun@ingenic.com, wanmyqawdr@126.com> * * Elf/IDWS Project * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * 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., * 675 Mass Ave, Cambridge, MA 02139, USA. */ #ifndef SENSORMANAGER_H #define SENSORMANAGER_H #include <tr1/memory> #include <string> #include <iwds.h> #include <utils/protectedlist.h> #include <utils/mutex.h> #include <smartsense/hal/sensordevice.h> #include <smartsense/sensor.h> class SensorEventCallback; class SensorManager { public: static std::tr1::shared_ptr<SensorManager> getInstance(); bool initialize(); int getSensorCount() const; bool intallSensorEventCallback( enum Sensor::SensorType sensorType, std::tr1::shared_ptr<SensorEventCallback> callback); std::tr1::shared_ptr<Sensor> getSensorByIndex(int index); std::tr1::shared_ptr<Sensor> getSensorByType( enum Sensor::SensorType type); bool setSensorActive(enum Sensor::SensorType type, bool enable); bool isSensorActive(enum Sensor::SensorType type); std::string errorString() const; bool handleEvent(sensors_event_t *hal_event); private: SensorManager(); std::tr1::shared_ptr<Sensor> getSensorByTypeNolock( enum Sensor::SensorType type); void fillSensorByHal(Sensor *sensor, const sensor_t *hal) const; void setErrorString(const std::string &errorString); Iwds::ProtectedList<std::tr1::shared_ptr<Sensor> > m_sensors; mutable Iwds::Mutex m_errorStringLock; std::string m_errorString; std::tr1::shared_ptr<SensorDevice> m_sensorDevice; }; #endif
[ "kesen.liao@ingenic.com" ]
kesen.liao@ingenic.com
72e849f4907636d3172f70bd86ab8b997df6450d
36f533088d1c5a93e058bc72a6d643ee262e4401
/CodeAdapter/EllipseArtist.cpp
b7d981f062d434141723a0319790214fd559eede
[ "MIT" ]
permissive
NeuroWhAI/CodeAdapter
3fd16b3538d76f0c9d835ea370e94f6d8c1bd027
b07815b9a610f74bcd50ae198a02b5131389cab7
refs/heads/master
2021-04-15T09:40:52.092641
2017-04-07T13:26:50
2017-04-07T13:26:50
55,895,368
7
3
null
2016-09-04T04:42:01
2016-04-10T11:34:11
C++
UTF-8
C++
false
false
164
cpp
#include "EllipseArtist.h" BEGIN_NAMESPACE_CA_DRAWING EllipseArtist::EllipseArtist() { } EllipseArtist::~EllipseArtist () { } END_NAMESPACE_CA_DRAWING
[ "neurowhai@gmail.com" ]
neurowhai@gmail.com
fb418c976700f0c1c2b0a955b9099458220f228b
9fe8defd8579cc805da43db25b5098c123c81e34
/contest/dev2_a.cpp
704bdfa963d46bd369ee66ecaada7f3fd8643568
[]
no_license
Kanonahmed/ACM-Programming
a9ea92b3e6031a6a7c022d6359110ba0ff43ecb6
7ebb662e92cb334ecdf519278cdba39af9a1f67c
refs/heads/master
2021-07-05T23:57:16.330893
2017-09-30T19:45:47
2017-09-30T19:45:47
105,396,479
0
0
null
null
null
null
UTF-8
C++
false
false
2,042
cpp
#include<bits/stdc++.h> using namespace std; #define xx first #define yy second #define pb push_back; #define mp make_pair #define LL long long #define PI acos(-1.0) #define AND(a,b) ((a) & (b)) #define OR(a,b) ((a)|(b)) #define XOR(a,b) ((a) ^ (b)) #define f1(i,n) for(int i=1;i<=n;i++) #define f0(i,n) for(int i=0;i<n;i++) #define meminf(B) memset(B,126,sizeof B) #define all(a) a.begin(),a.end() #define DEG_to_REDI(X) (X*PI/180) #define REDI_to_DEG(X) (180*X/(PI)) #define UB(a,x) (upper_bound(all(a),x)-a.begin()) #define LB(a,x) (lower_bound(all(a),x)-a.begin()) #define countbit(x) __builtin_popcountll((ll)x) //File input/output #define input freopen("in.txt","r",stdin) #define output freopen("out.txt","w",stdout) template <class T> inline T bigmod(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 modinverse(T a,T M){return bigmod(a,M-2,M);} /* ---------------------------------------- | Scratch where itches | ---------------------------------------- */ int Set(int N,int pos){ return N=N | (1<<pos);} int Reset(int N,int pos){return N= N & ~(1<<pos);} bool Chkbit(int N,int pos){return (bool)(N & (1<<pos));} int month[]={-1,31,28,31,30,31,30,31,31,30,31,30,31}; //Not Leap Year int dx[]={1,0,-1,0};int dy[]={0,1,0,-1}; //4 Direction //int dx[]={1,1,0,-1,-1,-1,0,1};int dy[]={0,1,1,1,0,-1,-1,-1};//8 direction //int dx[]={2,1,-1,-2,-2,-1,1,2};int dy[]={1,2,2,1,-1,-2,-2,-1};//Knight Direction //int dx[]={-1,-1,+0,+1,+1,+0};int dy[]={-1,+1,+2,+1,-1,-2}; //Hexagonal Direction const double eps=1e-6; int main() { int tc,ks=1; cin>>tc; while(tc--) { LL a,b; cin>>a>>b; a*=2LL; printf("Case %d: %lld\n",ks++,(a*a-b*b)); } return 0; }
[ "kanoncse41@gmail.com" ]
kanoncse41@gmail.com
bd8750915d2e51006bb6509b27bc4a92c08e204d
0543967d1fcd1ce4d682dbed0866a25b4fef73fd
/Midterm/solutions/midterm2017_72/L/000757-midterm2017_72-L.cpp
2d685049cd5c95e3bb428a05a2a37f55354671e8
[]
no_license
Beisenbek/PP12017
5e21fab031db8a945eb3fa12aac0db45c7cbb915
85a314d47cd067f4ecbbc24df1aa7a1acd37970a
refs/heads/master
2021-01-19T18:42:22.866838
2017-11-25T12:13:24
2017-11-25T12:13:24
101,155,127
0
0
null
null
null
null
UTF-8
C++
false
false
544
cpp
#include<iostream> #include<cmath> #include<string> #include<algorithm> using namespace std; int b[1000],n,a[700][700],s1=0,s2=0,m,maxx,d=0,in; int main() { cin>>n>>m; for (int i=1;i<=n;++i) for (int j=1;j<=m;++j) { cin>>a[i][j]; if (a[i][j]>0) b[i]++; } maxx=b[1]; for (int i=1;i<=n;++i) maxx=max(maxx,b[i]); for (int i=1;i<=n;++i) if (maxx==b[i]) in=i; for (int i=1;i<=n;++i) { if (maxx!=b[i]) { cout<<in; return 0; } } cout<<"Numbers are equal"; }
[ "beysenbek@gmail.com" ]
beysenbek@gmail.com
9865fb4ad93619d6b79d50d2c68ec9332a49f99b
f960d194a3f837194b96f6fde779ecefdc164155
/SampleIME/FunctionProviderSink.cpp
d3e68a32dc23d6d3452586ec45e724aefceed0ec
[]
no_license
jackfnx/NaiveIME
c2cc0a5a67878cbc42cd292f25e9e4e25d0a9a52
d5688d142790c98c888bf7fc610f0b27a9b1afed
refs/heads/master
2020-11-29T01:41:31.230984
2019-12-24T17:38:44
2019-12-24T17:38:44
229,980,720
0
0
null
null
null
null
UTF-8
C++
false
false
1,902
cpp
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // // Copyright (c) Microsoft Corporation. All rights reserved #include "Private.h" #include "SampleIME.h" #include "SearchCandidateProvider.h" //+--------------------------------------------------------------------------- // // _InitFunctionProviderSink // //---------------------------------------------------------------------------- BOOL CSampleIME::_InitFunctionProviderSink() { ITfSourceSingle* pSourceSingle = nullptr; BOOL ret = FALSE; if (SUCCEEDED(_pThreadMgr->QueryInterface(IID_ITfSourceSingle, (void **)&pSourceSingle))) { IUnknown* punk = nullptr; if (SUCCEEDED(QueryInterface(IID_IUnknown, (void **)&punk))) { if (SUCCEEDED(pSourceSingle->AdviseSingleSink(_tfClientId, IID_ITfFunctionProvider, punk))) { if (SUCCEEDED(CSearchCandidateProvider::CreateInstance(&_pITfFnSearchCandidateProvider, (ITfTextInputProcessorEx*)this))) { ret = TRUE; } } punk->Release(); } pSourceSingle->Release(); } return ret; } //+--------------------------------------------------------------------------- // // _UninitFunctionProviderSink // //---------------------------------------------------------------------------- void CSampleIME::_UninitFunctionProviderSink() { ITfSourceSingle* pSourceSingle = nullptr; if (SUCCEEDED(_pThreadMgr->QueryInterface(IID_ITfSourceSingle, (void **)&pSourceSingle))) { pSourceSingle->UnadviseSingleSink(_tfClientId, IID_ITfFunctionProvider); pSourceSingle->Release(); } }
[ "sixue@bbs.ustc.edu.cn" ]
sixue@bbs.ustc.edu.cn
05b9f64ee7d23ac0f7ffbeaa4db0ecf936cf49c5
37525014a50e09ea0507331206e4d835a94e29ce
/wire_core/include/wire/core/IStateEstimator.h
496bd20850f5acced2f9681487c5b2fa2ecfe359
[ "BSD-2-Clause" ]
permissive
ropod-project/wire
11b40c1d821a125a5edf665f0cafc66564f92abe
4962c36d5749a4f4aaea6a8c4610f5a1373ac5e4
refs/heads/master
2020-05-19T21:11:00.711705
2019-06-24T10:45:43
2019-06-24T10:45:43
185,217,799
1
1
BSD-2-Clause
2019-05-06T14:54:37
2019-05-06T14:54:36
null
UTF-8
C++
false
false
5,750
h
/************************************************************************ * Copyright (C) 2012 Eindhoven University of Technology (TU/e). * * 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 TU/e "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 TU/e 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. * * * * The views and conclusions contained in the software and * * documentation are those of the authors and should not be * * interpreted as representing official policies, either expressed or * * implied, of TU/e. * ************************************************************************/ #ifndef WM_I_STATE_ESTIMATOR_H_ #define WM_I_STATE_ESTIMATOR_H_ #include "wire/core/datatypes.h" #include "problib/pdfs/PDF.h" namespace mhf { /** * @author Sjoerd van den Dries * @date December, 2012 * * @brief Base class for all state estimators used by the world model. * * A state estimator estimates the value of one specific attribute * of one specific object in the world. The attribute value is represented * by a probability density over the domain of the attribute. For example, * a position can be represented by a PDF over Cartesian space. A state * estimator should implement three methods: propagate(Time t), which * changes the internal state of the estimator to the estimated value at * Time t; update(PDF z, Time time) which updates the internal state * based on measurement z at Time t; and getValue() which returns the * current state. */ class IStateEstimator { public: virtual ~IStateEstimator() {} virtual IStateEstimator* clone() const = 0; /** * @brief Propagates the internal state to Time time * @param time The time to which the internal state is propagated */ virtual void propagate(const Time& time) = 0; /** * @brief Updates the internal state based on measurement z * @param z The measurement with which to update, represented as a probability density function * @param time The time to which the internal state is propagated before updating */ virtual void update(const pbl::PDF& z, const Time& time) = 0; /** * @brief Resets the internal state of the estimator to its initial value */ virtual void reset() = 0; /** * @brief Returns the current estimated state value * @return The current state, i.e., the current attribute value represented as probability density function */ virtual const pbl::PDF& getValue() const = 0; /** * @brief Resets the internal state of the estimator to the given PDF * @param pdf The value to which the internal state is set */ //virtual void setValue(const pbl::PDF& pdf) { //} /** * @brief Set a boolean parameter of this state estimator * @param param The parameter name * @param b The boolean value * @return Returns true if the parameter was known to the estimator; false otherwise */ virtual bool setParameter(const std::string& param, bool b) { return false; } /** * @brief Set a real-valued parameter of this state estimator * @param param The parameter name * @param v The float value * @return Returns true if the parameter was known to the estimator; false otherwise */ virtual bool setParameter(const std::string& param, double v) { return false; } /** * @brief Set a string parameter of this state estimator * @param param The parameter name * @param s The string value * @return Returns true if the parameter was known to the estimator; false otherwise */ virtual bool setParameter(const std::string& param, const std::string& s) { return false; } }; } #endif /* WM_I_STATE_ESTIMATOR_H_ */
[ "jos.elfring@tno.nl" ]
jos.elfring@tno.nl
b25eea0b2c07ed39c55e2cf18083d9bee5db1cff
f280a5fa1824059cbac8dc36298d5b11e53c79de
/SES KONTROL ROBOTU/Arduino kodları/VoiceLED/VoiceLED.ino
79a5a7fb587a9f383335a41b0fecc96de9af6e54
[]
no_license
mujganazcan/Sesle-Kontrol-Edilebilen-Robot
f104d44a5903559e610c8661c73ae66665482759
17995c1afe1bfafbd44e811cd001878c0b036ad9
refs/heads/master
2020-08-13T18:20:39.838901
2019-11-02T11:47:52
2019-11-02T11:47:52
215,015,310
1
0
null
null
null
null
UTF-8
C++
false
false
3,195
ino
#include <ld3320.h> VoiceRecognition Voice; //声明一个语音识别对象 #define Led 8 //定义LED控制引脚 //初始化VoiceRecognition模块 #define Motor_sag_ileri 3 #define Motor_sag_geri 5 #define Motor_sol_ileri 6 #define Motor_sol_geri 7 void setup() { pinMode(Led,OUTPUT); //初始化LED引脚为输出模式 digitalWrite(Led,LOW); //LED引脚低电平 Serial.begin(9600); //配置9600 Serial.print("Uart start!"); Voice.init(); //初始化VoiceRecognition模块 Voice.addCommand("kai deng",0); //添加指令,(指令内容,指令标签(可重复)) Voice.addCommand("guan deng",1); //添加指令,参数(指令内容,指令标签(可重复)) Voice.addCommand("hello",2); //添加垃圾词汇 Voice.addCommand("ni hao",3); // ileri ni hao 你好 Voice.addCommand("wei wei",4); //geri vıy vıy-vı参数ey vıey 伟伟 Voice.addCommand("Wǒmen",5); //sağ Nín - vın 我们 Voice.addCommand("Zuǒ",6); //sol suo-suvo-zuo 剩下 Voice.addCommand("deng",7); //dur deng-denk 停止 Voice.start();//开始识别 digitalWrite(Led,LOW); //点亮LED } void loop() { switch(Voice.read()) //判断识别 { case 0: digitalWrite(Led,HIGH);//熄灭LED Serial.println("LED ON"); break; case 1: //若是指令“guan deng” digitalWrite(Led,LOW);//熄灭LED Serial.println("LED OFF");//若是指令“ka break; case 2: //若是指令“guan deng” Serial.println("hello"); break; case 3: Serial.println("ileri"); digitalWrite(Motor_sag_ileri,HIGH); digitalWrite(Motor_sag_geri,LOW); digitalWrite(Motor_sol_ileri,HIGH); digitalWrite(Motor_sol_geri,LOW); break; case 4: Serial.println("geri"); digitalWrite(Motor_sag_ileri,LOW); digitalWrite(Motor_sag_geri,HIGH); digitalWrite(Motor_sol_ileri,LOW); digitalWrite(Motor_sol_geri,HIGH); break; case 5: Serial.println("sağ"); digitalWrite(Motor_sag_ileri,LOW); digitalWrite(Motor_sag_geri,LOW); digitalWrite(Motor_sol_ileri,HIGH); digitalWrite(Motor_sol_geri,LOW); break; case 6: Serial.println("sol"); digitalWrite(Motor_sag_ileri,HIGH); digitalWrite(Motor_sag_geri,LOW); digitalWrite(Motor_sol_ileri,LOW); digitalWrite(Motor_sol_geri,LOW); break; case 7: Serial.println("dur"); digitalWrite(Motor_sag_ileri,LOW); digitalWrite(Motor_sag_geri,LOW); digitalWrite(Motor_sol_ileri,LOW); digitalWrite(Motor_sol_geri,LOW); break; default: break; } }
[ "noreply@github.com" ]
mujganazcan.noreply@github.com
c2aa11701f92297e16b12dae3bc8e6286df777dc
36183993b144b873d4d53e7b0f0dfebedcb77730
/GameDevelopment/Game Programming Gems 6/Section1-General_Programming/1-5-BSPTechniques/code/compiler.h
0df929b4f0a432e51c187a5950263be1a61a43a3
[]
no_license
alecnunn/bookresources
b95bf62dda3eb9b0ba0fb4e56025c5c7b6d605c0
4562f6430af5afffde790c42d0f3a33176d8003b
refs/heads/master
2020-04-12T22:28:54.275703
2018-12-22T09:00:31
2018-12-22T09:00:31
162,790,540
20
14
null
null
null
null
UTF-8
C++
false
false
13,673
h
#ifndef __COMPILER_H__ #define __COMPILER_H__ #include "geometry.h" #include <list> //-------------------------------------------------------------------------------- #define NODE_EMPTY 0x0 #define NODE_SOLID 0x1 #define NODE_LEAF 0x80000000 #define N_FRONT 1 #define N_BACK 0 #define FLAG_PROCESSED 0x8000000 //-------------------------------------------------------------------------------- #define _THREAD_WAIT_BRANCH_ //-------------------------------------------------------------------------------- class BaseThrCB { public: BaseThrCB(){}; virtual ~BaseThrCB(){}; virtual int ThreadMain()=0; static int ThreadFunction(void* p){return reinterpret_cast<BaseThrCB*>(p)->ThreadMain();} void Start(){ DWORD uid; h_t = ::CreateThread(0,0,reinterpret_cast<LPTHREAD_START_ROUTINE>(ThreadFunction), this,0,&uid); } void Wait(){::WaitForSingleObject(h_t, INFINITE);} HANDLE h_t; }; //-------------------------------------------------------------------------------- class Bsp_Tree; class CBspNode { public: CBspNode(Bsp_Tree* pBsp, DWORD dw=0) { _idxNodeThis = -1; _nodeidx[0] = -1; _nodeidx[1] = -1; _planeIdx = -1; _nPolys = 0; _polyIdx = -1; _flags = dw; _pBsp = pBsp; _leafIdx = -1; _idxParent = -1; } virtual ~CBspNode(){} CBspNode* Back(); CBspNode* Front(); CBspNode* Parent(); int FontIdx(){return _nodeidx[1];} int BackIdx(){return _nodeidx[0];} BOOL IsEmptyLeaf() {return (_flags & NODE_LEAF) && !(_flags & NODE_SOLID);} BOOL IsLeaf() {return (_flags & NODE_LEAF);} BOOL IsSolid() {return (_flags & NODE_SOLID);} BOOL IsSpace() {return !(_flags & NODE_SOLID) && (_flags & NODE_LEAF);} BOOL IsNode() {return !(_flags & NODE_LEAF);} INLN Plane& GetPlane()const;// INLN Poly* GetPolys(int& count); public: int _idxNodeThis; int _idxParent; int _nodeidx[2]; int _planeIdx; int _leafIdx; DWORD _flags; int _nPolys; int _polyIdx; Bsp_Tree* _pBsp; Box _bbox; }; //-------------------------------------------------------------------------------- class CLeaf : public CBspNode { public: CLeaf(Bsp_Tree* pBsp, DWORD dw=0):CBspNode(pBsp, dw), _pvsIdx(-1), _portIdxes(4), _flags(0){ } virtual ~CLeaf(){_portIdxes.clear();} void AddPortalIdx(int idx){_portIdxes.push_back(idx);}; vvector<int>& GetPortalIdxes(){return _portIdxes;} int _pvsIdx; vvector<int> _portIdxes; DWORD _flags; }; //-------------------------------------------------------------------------------- class Bsp_Tree ; struct ThrData { int nodeIdx; #ifdef _THREAD_WAIT_BRANCH_ list<Poly>* polys; #else list<Poly> polys; #endif // Bsp_Tree* ptree; }; //-------------------------------------------------------------------------------- class Compiler; class Bsp_Tree { public: enum _BSP_TYPE{BSP_LEAFY=0, BSP_TERRAIN}; public: friend class CBspNode; friend class Compiler; Bsp_Tree(int expected=128){ _polys.reserve(expected); _nodes.reserve(expected*2); _balance = 6; _bsptype = BSP_LEAFY; ::InitializeCriticalSection(&c_s); }; virtual ~Bsp_Tree(){ ::DeleteCriticalSection(&c_s); Clear(); }; void SetType(_BSP_TYPE bt){ _bsptype = bt; } void Clear(); vvector<Poly>& GetPolys() {return _polys;}; void Process(vvector<Poly>& polys, BOOL busethreads); // virtual from base int ThreadMain(); CBspNode* Root(){return _nodes[0];}// _pRoot; vvector<CBspNode*>& GetNodes(){return _nodes; } CBspNode* GetNode(int idx){ASSERT(idx < (int)_nodes.size()); return _nodes[idx];} Plane& GetPlane(int iplane){ASSERT(iplane < (int)_planes.size()); return _planes[iplane];} Poly& GetPoly(int idx) {ASSERT(idx < (int)_polys.size()); return _polys[idx];} CLeaf* GetLeaf(int idx){ASSERT(idx < _leafs.size()); return _leafs[idx];} BOOL SegmentIntersect(V3& paa, V3& pab, int node , V3& col); int GetCurrentLeaf(V3& pov, int nodeIdx=0); void R_Compile(int nodeIdx, list<Poly>&); BOOL Lock(){if(b_usethreads)::EnterCriticalSection(&c_s); return 1;} void UnLock(){if(b_usethreads)::LeaveCriticalSection(&c_s); ;} static int T_Compile(void*); private: void Recurs_Or_Thread(int nodeIdx, list<Poly>& polys); void UpdateNodeBB(CBspNode* pNode, list<Poly>& polys); void UpdateNodeBB(CBspNode* pNode, vvector<Poly>& polys); BOOL BuildDummyBSP(vvector<Poly>& polys); void MakeRoot(){ASSERT(_nodes.size()==0); AddNode(new CBspNode(this));}; void BuildPlaneArray(list<Poly>& polys); void R_TerrainCompile(int nodeIdx, list<Poly>&); int GetBestSplitter(list<Poly>& polys, Poly* pWantPoly=0); int Partition(CBspNode* pNode, list<Poly>&, list<Poly>&,list<Poly>&); void PartitionTerrain(CBspNode* pNode, list<Poly>&, list<Poly>&,list<Poly>&); void FindSplitterPlane(list<Poly>& polys, CBspNode* pNode); Plane GetOptimSpliterPlane(list<Poly>& polys, int moe=16); BOOL FormConvex(list<Poly>& frontPolys); BOOL R_SegmentIntersect(int nodeIdx, V3& a, V3& b, V3& col); void AddNode(CBspNode* pNn){ pNn->_idxNodeThis = _nodes.size(); _nodes << pNn; if(pNn->IsEmptyLeaf()) { pNn->_leafIdx = _leafs.size(); _leafs << (CLeaf*)pNn; } } CBspNode* CreateNode(DWORD dw){ if(dw & NODE_SOLID) return new CBspNode(this, dw); return new CLeaf(this, dw); } public: vvector<CBspNode*> _nodes; vvector<CLeaf*> _leafs; vvector<Poly> _polys; vvector<Plane> _planes; vvector<Poly>* _pInPolys; _BSP_TYPE _bsptype; int _reachedDepth; int _balance; BOOL _hitTest; DWORD dw_deltatime; BOOL b_usethreads; int n_thrcount; long n_threadsup; HANDLE h_handles[64]; CRITICAL_SECTION c_s; }; //------------------------------------------------------------------------------------------ INLN Plane& CBspNode::GetPlane()const { ASSERT(_planeIdx>=0 && _planeIdx < (int)_pBsp->_planes.size()); if(_planeIdx>=0 && _planeIdx < (int)_pBsp->_planes.size()) return _pBsp->_planes[_planeIdx]; return _pBsp->_planes[0]; }; INLN Poly* CBspNode::GetPolys(int& count){ vvector<Poly>& polys = _pBsp->GetPolys(); count = _nPolys; return &polys[_polyIdx]; }; //-------------------------------------------------------------------------------- #define PORT_INITAL 0x1 #define PORT_DUP 0x2 #define PORT_REVERSED 0x4 #define PORT_DELETED 0x8 //-------------------------------------------------------------------------------- class Portal_Prc; class Portal : public Plane { public: Portal(){}; ~Portal() { _vxes.clear(); _sideLIdx.clear(); _sideLIdxFinal.clear(); } Portal(Portal_Prc* pp):_pPortPrc(pp),_flags(0),_planeIdx(-1){} Portal(const Portal& r){ _planeIdx = r._planeIdx; _flags = r._flags; _vxes = r._vxes; _sideLIdx = r._sideLIdx; _n = r._n; _c = r._c; _pPortPrc = r._pPortPrc; _idxThis = r._idxThis; } void Reverse(){ _flags |= PORT_REVERSED; _n.negate(); _c=-_c; _vxes.reverse(); } Portal& operator=(const Portal& r){ if(this !=&r){ _planeIdx = r._planeIdx; _flags = r._flags; _vxes = r._vxes; _sideLIdx = r._sideLIdx; _n = r._n; _c = r._c; _pPortPrc = r._pPortPrc; _idxThis = r._idxThis; } return *this; } V3 GetCenter() { V3 ret; for(UINT i=0; i < _vxes.size(); ++i) { ret+=_vxes[i]; } ret/= (REAL)_vxes.size(); return ret; } void AdjustVxOrder() { Plane tp; GCalcNormal(&tp,_vxes[0],_vxes[1],_vxes[2]); if(!IsZero( Vdp(tp._n, _n)-1.0f,.00625f)) { _vxes.reverse(); GCalcNormal(&tp,_vxes[0],_vxes[1],_vxes[2]); } } REL_POS Classify(Plane& plane) { int fronts = 0, backs = 0, coinciss = 0; int vxes = _vxes.size(); REAL rdp; FOREACH(vvector<V3>, _vxes, vx) { rdp = plane.DistTo(*vx); if(rdp > .5f) fronts++; else if(rdp < -.5f) backs++; else{ coinciss++; backs++; fronts++;} } if (coinciss == vxes) return ON_PLANE; if (fronts == vxes) return ON_FRONT; if (backs == vxes) return ON_BACK; return ON_SPLIT; } void CopyProps(Portal& pFrom){ _planeIdx = pFrom._planeIdx; _flags = pFrom._flags; _sideLIdx = pFrom._sideLIdx; _n = pFrom._n; _c = pFrom._c; _idxThis = pFrom._idxThis; } void AddSideLeafIdx(int idx){_sideLIdx<<idx;} void Split(Plane& plane, Portal& a, Portal& b); INLN CLeaf* BackLeaf(); INLN CLeaf* FrontLeaf(); INLN Plane& GetPlane(); void Clear(){_vxes.clear(); } public: int _idxThis; int _planeIdx; // index in planes index of the BSP wich ortal belons too DWORD _flags; vvector<V3> _vxes; vvector<int> _sideLIdx; vvector<int> _sideLIdxFinal; Portal_Prc* _pPortPrc; }; //-------------------------------------------------------------------------------- class Portal_Prc { public: friend class Portal; friend class Compiler; Portal_Prc(){ _pTree = 0; } ~Portal_Prc(){Clear();} void Process(Bsp_Tree& tree); void Clear(); CLeaf* GetLeaf(int idx){ CBspNode* pL = _pTree->GetLeaf(idx); ASSERT(pL->_flags & NODE_LEAF); return (CLeaf*)pL; } Portal& GetPortal(int idx){return _portals[idx];} vvector<Portal>& GetPortals(){return _portals;} BOOL HasPortals(){return _portals.size()>0;} private: void CutPortalWithNodeBox(Portal& portal, Box& box,BOOL b=0); BOOL CalculateInitialPortal(Portal&, CBspNode* ); BOOL ValidatePortal(Portal&); BOOL DuplicatePortals(vvector<Portal>& i, vvector<Portal>& o); Plane& GetPlane(int idx){return _pTree->GetPlane(idx);} void AddPortal(Portal& p){ p._idxThis = _portals.size(); _portals << p; } void ClipWithLeafSides(CLeaf* pLeaf, Portal& portal); public: vvector<Portal> _portals; Bsp_Tree* _pTree; DWORD dw_deltatime; }; //---------------------------------------------------------------------------------------- INLN CLeaf* Portal::BackLeaf(){ ASSERT(_sideLIdx.size()==2); return _pPortPrc->GetLeaf(_sideLIdx[0]); } INLN CLeaf* Portal::FrontLeaf(){ ASSERT(_sideLIdx.size()==2); return _pPortPrc->GetLeaf(_sideLIdx[1]); } Plane& Portal::GetPlane(){ return _pPortPrc->GetPlane(_planeIdx); } //-------------------------------------------------------------------------------- struct PortalData { PortalData(int sz):_portArrPvs(sz) { _possibleVisCount = 0; _size = _portArrPvs.Size(); } ~PortalData(){} int _size; int _possibleVisCount; CBitArray _portArrPvs; }; //-------------------------------------------------------------------------------- class PVS_Prc { public: PVS_Prc():_nleafs(0),_pvs(0),_cPvss(0){} virtual ~PVS_Prc(){ Clear(); }; void Clear(){ delete[] _pvs; _pvs=0; _cPvss = 0; _portVs.deleteelements(); dw_deltatime = GetTickCount(); }; void Process(Bsp_Tree& tree, Portal_Prc& portalprc); private: BOOL InitalPortalVis(vvector<Portal>& rPortals); void R_PortalFlood(Portal& portal, BYTE* pVis, int nLeaf); // flood in neghbour leaf void PerformPVS(Portal& pOrigin, vvector<Portal>& rPortals, BYTE* prevPvs); void GaterLeafsVis(); BOOL PortalSeesPortal(Portal& a, Portal& b); Bsp_Tree* _pBspTree; Portal_Prc* _pPortPrc; int _nleafs; public: BYTE* _pvs; int _cPvss; vvector<PortalData*> _portVs; DWORD dw_deltatime; }; //-------------------------------------------------------------------------------- class CBsp_TechniquesDlg; class Compiler : public BaseThrCB { public: Compiler(){}; virtual ~Compiler(){}; BOOL Compile(Brush& brush, CBsp_TechniquesDlg& theDlg, BOOL usehthreads); void Render(UINT mode, BOOL is3D); void Clear(); private: int ThreadMain(); void RenderBSP(BOOL is3D); void RenderPortals(BOOL is3D); public: Portal_Prc portal_procesor; PVS_Prc pvs_procesor; Bsp_Tree bsp_tree; CBsp_TechniquesDlg* p_dlg; Brush* p_brush; BOOL b_usethreads; }; #endif // !__COMPILER_H__
[ "alec.nunn@gmail.com" ]
alec.nunn@gmail.com
0a3edb5da0ac0aa14f423831d3cf6a897c9a9f0f
75d4ee482b9c42694069db8f99c43a7fca40b35e
/src/twist_unstamper_node.cpp
8381a75034266ee6989feafec4046a7315168bcf
[]
no_license
joshs333/twist_tools
1fc70d8b487384d4e7e8758eae30308b39f76776
b6606b5b7601aec1dc1631deea4f47bc21a46f11
refs/heads/master
2022-12-24T23:48:27.406809
2020-10-05T09:40:38
2020-10-05T09:40:38
301,355,271
1
0
null
null
null
null
UTF-8
C++
false
false
1,929
cpp
/** * @brief Node that inputs a stamped twist message and outputs a regular twist message * @author Joshua Spisak <joshs333@live.com> * @date October 5, 2020 * @license MIT **/ // ROS #include <ros/ros.h> #include <geometry_msgs/Twist.h> #include <geometry_msgs/TwistStamped.h> namespace twist_tools { /** * @brief node that subscribes to a twist stamped and outputs a twist message **/ class TwistUnstamperNode { public: /** * @brief parameters for creating node **/ struct Params { //! Input twist stamped topic std::string input_twist_stamped = "/twist_stamped_in"; //! Output twist topic std::string output_twist = "/twist_out"; }; /** * @brief creates node * @param nh nodehandle to use to create topics, etc.. * @param params general params to generate node with **/ TwistUnstamperNode(ros::NodeHandle& nh, Params& params) { input_sub_ = nh.subscribe<geometry_msgs::TwistStamped>(params.input_twist_stamped, 1, &TwistUnstamperNode::twistCB, this); output_pub_ = nh.advertise<geometry_msgs::Twist>(params.output_twist, 1, true); } /** * @brief callback for twist messages * @param input the input twist message **/ void twistCB(const geometry_msgs::TwistStamped::ConstPtr& input) { output_pub_.publish(input->twist); } private: //! Input Sub ros::Subscriber input_sub_; //! Output Publisher ros::Publisher output_pub_; }; // TwistUnstamperNode }; /* namespace twist_tools */ int main(int argc, char** argv) { ros::init(argc, argv, "twist_stamper_node"); ros::NodeHandle nh("~"); twist_tools::TwistUnstamperNode::Params params; nh.getParam("input_twist_stamped", params.input_twist_stamped); nh.getParam("output_twist", params.output_twist); twist_tools::TwistUnstamperNode node(nh, params); ros::spin(); return 0; }
[ "joshs333@live.com" ]
joshs333@live.com
00d6baa957a4be81127c7b2526c11c0b332d12e0
524345d1d8467b588cdd760b62d238a7c7ad34d1
/Basic_Implementation/OpenMP.cpp
39e47e2723ec6bb3472bf4a71596e2506a2b4926
[]
no_license
veersenjadhav/HPC-Seminar
483908a2956511710e7cfffaddbd5acaef3646c3
4283fa974ca64921a59c43f6c8790fd901373488
refs/heads/master
2020-05-26T08:15:08.045541
2019-05-23T04:50:00
2019-05-23T04:50:00
188,163,295
0
0
null
null
null
null
UTF-8
C++
false
false
2,282
cpp
#include <string> #include <sstream> #include <iostream> #include <fstream> #include <cmath> #include <stdlib.h> #include <omp.h> #include <chrono> #define ROWS 36634 #define FEATURES 14 #define DATASET "Dataset.csv" using namespace std; using namespace chrono; int main(int argc, char const *argv[]) { string line, field; double* dataset = new double[ROWS * FEATURES]; double* min = new double[FEATURES], *max = new double[FEATURES]; double* normalized = new double[ROWS * FEATURES]; ifstream in(DATASET); int value = 0; while ( getline(in,line) ) { stringstream ss(line); while (getline(ss,field,',')) { dataset[value] = (double)atof(field.c_str()); value++; } } auto start = steady_clock::now(); #pragma omp parallel { #pragma omp for for(int j=0; j<FEATURES; j++) { double temp_min = dataset[j]; for(int i=1; i<ROWS; i++) { if(dataset[i * FEATURES + j] < temp_min) { temp_min = dataset[i * FEATURES + j]; } } min[j] = temp_min; } #pragma omp for for(int j=0; j<FEATURES; j++) { double temp_max = dataset[j]; for(int i=0; i<ROWS; i++) { if(dataset[i * FEATURES + j] > temp_max) { temp_max = dataset[i * FEATURES + j]; } } max[j] = temp_max; } #pragma omp for for(int i=0; i<ROWS; i++) { for(int j=0; j<FEATURES; j++) { normalized[i * FEATURES + j] = (dataset[i * FEATURES + j] - min[j]) / (max[j] - min[j]); } } } auto end = steady_clock::now(); /*for(int i=0; i<ROWS; i++) { for(int j=0; j<FEATURES; j++) { printf("%.8f \t",normalized[i * FEATURES + j]); } printf("\n"); }*/ cout << "\n Elapsed time in seconds : " << chrono::duration_cast<chrono::microseconds>(end - start).count() << " microsec" << endl; delete[] dataset, min, max, normalized; return 0; }
[ "noreply@github.com" ]
veersenjadhav.noreply@github.com
ff891063324d65de746ed7925ad69c61fef1bf59
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/git/gumtree/git_old_hunk_3763.cpp
566166f84130cf8dfd99af4a54a3a025a9724570
[]
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
358
cpp
color = diff_get_color_opt(&opt->diffopt, status ? DIFF_WHITESPACE : DIFF_FRAGINFO); reset = diff_get_color_opt(&opt->diffopt, DIFF_RESET); while (*bol) { eol = strchrnul(bol, '\n'); printf("%s%.*s%s%s", color, (int)(eol - bol), bol, reset, *eol ? "\n" : ""); graph_show_oneline(opt->graph); bol = (*eol) ? (eol + 1) : eol; } }
[ "993273596@qq.com" ]
993273596@qq.com
deb3a255e37a5ca9db1cbfa623aa1de8d998b3cb
9401a919b491a6045955ae9511a2d8bca77e6884
/HLS_Test/QP_HLS/QP/sim/autowrap/testbench/fp_test_tb.cpp_pre.cpp
c8660e9e1415ffa4dd3e736a01c4ef2657581444
[]
no_license
wuyou33/MPC
0bb56c499bd8c04b477840ef4a1c4bf41258ad14
35a0d9a4fd5e0c922720cf39d75a7db9bf1ea3c5
refs/heads/master
2021-05-18T02:17:26.404408
2020-01-16T19:15:59
2020-01-16T19:15:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
166
cpp
# 1 "C:/Users/hkhaj/Desktop/MPC/HLS_Test/QP_HLS/fp_test_tb.cpp" # 1 "<built-in>" # 1 "<command-line>" # 1 "C:/Users/hkhaj/Desktop/MPC/HLS_Test/QP_HLS/fp_test_tb.cpp"
[ "hkhajanchi97@att.net" ]
hkhajanchi97@att.net
ea1ac8cf33734e88dd3d80c10656ba5a8b4c5c1b
a1fe3366863fd797feb19d83dccfd4c3a5cb690a
/SDRSpectrumAnalyzerOpenGL/SDRSpectrumAnalyzerOpenGL/GUI.cpp
1215e19e32dcdfb01bef296ad2c69a0d89c46766
[]
no_license
moderncoder/SDRReradiationSpectrumAnalyzer
da1733c8d1b6cd7817bf1e1d13ac17f6660189ef
c347e3ab9d62f48daf23dd76222abc44f596fd93
refs/heads/master
2023-03-14T22:22:16.068295
2021-03-10T12:15:43
2021-03-10T12:15:43
346,340,703
0
0
null
null
null
null
UTF-8
C++
false
false
248
cpp
#include "Graphs.h" class GUI { private: Graphs* graphs = new Graphs(); Graph *dataGraph, *fftGraphForDevicesRange, *correlationGraph, *fftGraphStrengthsForDeviceRange; SelectedGraph selectedGraphStart; SelectedGraph selectedGraphEnd; };
[ "clint@getfitnowapps.com" ]
clint@getfitnowapps.com
a748964d68da56901dbea8cd530b420b6c0fbeed
dc2a81c665f7a79a10760b4bbde6d98d48c0bcbe
/src/logging/log.cpp
a21f9a3569e42027aa5c576d8b6bcdca974c678f
[ "MIT" ]
permissive
clman94/Wolf-Gang-Engine
14b219b9518f6a14317ebcff4e7516de29504b9b
52fa71d6be1fb940a0998f29b4e0ce631e624b25
refs/heads/master
2021-07-23T20:57:44.552521
2021-02-11T20:15:50
2021-02-11T20:15:50
68,487,653
5
2
null
2017-05-21T00:33:37
2016-09-18T01:29:31
C++
UTF-8
C++
false
false
3,331
cpp
#include <wge/logging/log.hpp> #include <fmt/chrono.h> #include <fmt/format.h> #include <iostream> #include <fstream> #include <array> #include <filesystem> using namespace wge; static const char* get_ansi_color_reset() { return "\033[0m"; } static const char* get_ansi_color_for_level(log::level pSeverity_level) { switch (pSeverity_level) { case log::level::unknown: return "\033[95m"; break; case log::level::info: return get_ansi_color_reset(); break; case log::level::debug: return "\033[96m"; break; case log::level::warning: return "\033[93m"; break; case log::level::error: return "\033[91m"; break; default: return get_ansi_color_reset(); } } namespace wge::log { static std::vector<message> gLog; static std::ofstream gLog_output_file; void message::stamp_time() { time_stamp = std::time(nullptr); } std::string message::to_string(bool pAnsi_color) const { std::tm timeinfo; #ifdef __linux__ localtime_r(&time, &timeinfo); #else localtime_s(&timeinfo, &time_stamp); #endif constexpr std::array severity_level_name = { "Unknown", "Info", "Debug", "Warning", "Error" }; fmt::memory_buffer buffer; fmt::format_to(buffer, "[{:%m-%d-%y %T}] {}{}: ", timeinfo, pAnsi_color ? get_ansi_color_for_level(severity_level) : "", severity_level_name[static_cast<std::size_t>(severity_level)]); std::string line_info_str = line_info.to_string(); if (!line_info_str.empty()) fmt::format_to(buffer, "{}: ", line_info_str); fmt::format_to(buffer, "{}{}", string, pAnsi_color ? get_ansi_color_reset() : ""); return fmt::to_string(std::move(buffer)); } util::span<const message> get_log() { return gLog; } message& add_message(message&& pMessage) { gLog.emplace_back(std::forward<message>(pMessage)); std::cout << gLog.back().to_string(true) << std::endl; return gLog.back(); } message& add_message(const message& pMessage) { gLog.push_back(pMessage); std::cout << gLog.back().to_string(true) << std::endl; return gLog.back(); } void userdata(userdata_t pData) { if (!gLog.empty()) { gLog.back().userdata = std::move(pData); } } bool open_file(const char* pFile) { gLog_output_file.open(pFile); if (gLog_output_file) info("Log: Successfully opened log file \"{}\"", pFile); else error("Log: Failed to open log file \"{}\"", pFile); return gLog_output_file.good(); } bool soft_assert(bool pExpression, std::string_view pMessage, line_info pLine_info) { if (!pExpression) { pLine_info.shorten_path(); warning("{} Assertion Failure: {}", pLine_info.to_string(), pMessage); } return pExpression; } void line_info::shorten_path() { if (!file.empty() && system_filesystem && std::filesystem::exists(file)) { std::filesystem::path relate_path = std::filesystem::relative(file); std::string path_str = relate_path.string(); if (file.length() > path_str.length()) file = path_str; } } std::string line_info::to_string() const { fmt::memory_buffer buffer; if (!file.empty()) fmt::format_to(buffer, "{}", file); const bool has_line = line >= 0; const bool has_column = column >= 0; if (has_line && !has_column) fmt::format_to(buffer, "({})", line); else if (has_column) fmt::format_to(buffer, "({}, {})", has_line ? std::to_string(line).c_str() : "?", column); return fmt::to_string(buffer); } } // namespace wge::log
[ "capnsword@gmail.com" ]
capnsword@gmail.com
b26f8363e7b8b29a9fe8b959e1a0b0dd597a4547
0ff374c9840ecb4b91b5d96659ba852601d57f3f
/lcs.cpp
f8f6943dd9fe4330950ed3cfc410ffcf6bd79efc
[]
no_license
ankurdcruz/CPP-Programs
4675fffa4b9d5f4e63f98565add7977645460cbf
5326e3a1257e1f4423d753bdfba23745ddbd2d99
refs/heads/master
2021-07-01T13:09:24.920637
2021-01-04T18:26:24
2021-01-04T18:26:24
213,186,643
0
5
null
2020-10-31T17:41:24
2019-10-06T14:49:02
C++
UTF-8
C++
false
false
1,030
cpp
/* Dynamic Programming C/C++ implementation of LCS problem */ #include <bits/stdc++.h> int max(int a, int b); /* Returns length of LCS for X[0..m-1], Y[0..n-1] */ int lcs(char* X, char* Y, int m, int n) { int L[m + 1][n + 1]; int i, j; /* Following steps build L[m+1][n+1] in bottom up fashion. Note that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] */ for (i = 0; i <= m; i++) { for (j = 0; j <= n; j++) { if (i == 0 || j == 0) L[i][j] = 0; else if (X[i - 1] == Y[j - 1]) L[i][j] = L[i - 1][j - 1] + 1; else L[i][j] = max(L[i - 1][j], L[i][j - 1]); } } /* L[m][n] contains length of LCS for X[0..n-1] and Y[0..m-1] */ return L[m][n]; } /* Utility function to get max of 2 integers */ int max(int a, int b) { return (a > b) ? a : b; } /* Driver program to test above function */ int main() { char X[] = "AGGTAB"; char Y[] = "GXTXAYB"; int m = strlen(X); int n = strlen(Y); printf("Length of LCS is %d\n", lcs(X, Y, m, n)); return 0; }
[ "noreply@github.com" ]
ankurdcruz.noreply@github.com
0c16910a04dda4ec46f01ae098e97aa487928b65
2896d712be1d186526bb7611e539edc608b8b0a2
/Object/arxiv/Geo2DObjectUtilFunc.h
de9055f6422df7438d70de97ab098d145cf57ad0
[]
no_license
LArbys/Geo2D
bc694e92d801f8f5546a0d6d95fdf7fea57de7df
8522ba20c78d5b03098185e4d86fe5fde9fec208
refs/heads/master
2021-09-08T09:42:09.860852
2016-09-28T23:11:09
2016-09-28T23:11:09
69,510,990
1
0
null
null
null
null
UTF-8
C++
false
false
93
h
#ifndef GEO2DOBJECTUTILFUNC_H #define GEO2DOBJECTUTILFUNC_H namespace geo2d { } #endif
[ "kazuhiro@nevis.columbia.edu" ]
kazuhiro@nevis.columbia.edu
0640405bad65fcc86d9d983f0746f89dc03c9b66
779dbcf7605da4c321592ec73978d0ca00e70e18
/src/legacy/past/20150309/OkaoClientSub2.cpp
2298dcb461fc05fa3b20c30c134ac06cd2118b5d
[]
no_license
cvpapero/okao_client
0486ad81f92b6ee7841d294f30539f55fa74e4cb
7a7ed436c5ba46fe0773002be1caee494cdab413
refs/heads/master
2021-01-20T21:23:16.997153
2015-09-01T10:49:15
2015-09-01T10:49:15
27,530,207
1
0
null
null
null
null
UTF-8
C++
false
false
10,432
cpp
/* 2014.11.19------------------ 人物の頭の部分をくりぬいてOKAO Serverに送信 2014.10.21------------------ humans_msgsによってパブリッシュ 個人属性データが、一人一人についてパブリッシュされてないのか? 2014.8.22------------------- 信頼度によるUNKNOWNの設定 2014.7.16------------------- パブリッシュ機能を追加 2014.7.15------------------- 安達くんのOKAOサーバにコネクトする json */ #include <ros/ros.h> #include <iostream> #include <sstream> #include <string> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <vector> //ROS #include <image_transport/image_transport.h> #include <cv_bridge/cv_bridge.h> #include <sensor_msgs/image_encodings.h> //オリジナルのメッセージ #include <humans_msgs/Humans.h> #include "okao_client/OkaoStack.h" //OpenCV #include <opencv2/opencv.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> //通信用ライブラリ #include <msgpack.hpp> #include "zmq.hpp" #include "zmq.h" #include "picojson.h" #include "Message.h" #define OKAO 3 #define SRVTEMPO 10 static const std::string OPENCV_WINDOW = "OKAO Client sub2 Window"; using namespace cv; using namespace std; int callbackCount = 0; bool stackSrv = false; class ImageConverter { private: ros::NodeHandle nh_; //パブリッシャとサブスクライバの定義 ros::Publisher okaoData_pub_; image_transport::ImageTransport it_; image_transport::Subscriber image_sub_; image_transport::Subscriber depth_sub_; image_transport::Publisher image_pub_; zmq::context_t context; zmq::socket_t* responder; public: ImageConverter() : it_(nh_), context(3) { //画像データのサブスクライブとパブリッシュ image_sub_ = it_.subscribe("/camera/image/color",1, &ImageConverter::imageCb, this); image_pub_ = it_.advertise("/image_converter/output_video",1); //検出した顔データのパブリッシュ okaoData_pub_ = nh_.advertise<humans_msgs::Humans>("/humans/OkaoServer",10); //ソケットの作成 responder = new zmq::socket_t(context, ZMQ_REQ); assert( responder ); try { responder->connect("tcp://133.19.23.33:50001"); } catch(const zmq::error_t& e) { cout <<"Server Conect Error: " << e.what() << endl; return; } //ウィンドウ cv::namedWindow(OPENCV_WINDOW); } ~ImageConverter() { cv::destroyWindow(OPENCV_WINDOW); if( responder ) { delete responder; } //zmq_close( responder ); } //コールバック関数 void imageCb(const sensor_msgs::ImageConstPtr& imgmsg) { //Subscribe humans_msgs::HumansConstPtr kinect = ros::topic::waitForMessage<humans_msgs::Humans>("/humans/KinectV2", nh_); Mat rgbImage,grayImage;//画像イメージ格納用 cv_bridge::CvImagePtr cv_ptr; try { //画像メッセージ(ROS)をMat型(OpenCV)に代入し、グレイスケール変換する cv_ptr = cv_bridge::toCvCopy(imgmsg, sensor_msgs::image_encodings::BGR8); Mat tmpRgbImage = cv_ptr->image; Mat reRgbImage(tmpRgbImage, cv::Rect(960, 0, 960, 540)); rgbImage = reRgbImage; cv::cvtColor(rgbImage,grayImage,CV_BGR2GRAY); } catch(cv_bridge::Exception& e) { ROS_ERROR("cv_bridge exception: %s",e.what()); return; } try { //画像の読み込み cv::Mat img = grayImage;//cv_ptr->image; //cout <<"cols:" << img.cols << ",rows:"<<img.rows << endl; std::vector<unsigned char> buf(img.data, img.data + img.cols * img.rows * img.channels()); double width = rgbImage.cols; double height = rgbImage.rows; double resize_width = width / img.cols; double resize_height = height / img.rows; //cout<<"img.cols: "<< img.cols << endl; //cout<<"resize_width: "<< resize_width << endl; // 画像をエンコードする必要があれば std::vector<int> encodeParam(2); encodeParam[0] = CV_IMWRITE_PNG_COMPRESSION; encodeParam[1] = 3; cv::imencode(".png", img, buf, encodeParam); //std::cout << "encoded size: " << buf.size() << std::endl; // 画像のパラメータ // エンコードした際はformatをRAWからPNG等に変えること // また、width, heightも適切に設定すること picojson::object p; p.insert(std::make_pair("mode",picojson::value(std::string("FaceRecognition")))); p.insert(std::make_pair("format",picojson::value(std::string("PNG")))); p.insert(std::make_pair("width",picojson::value((double)img.cols))); p.insert(std::make_pair("height",picojson::value((double)img.rows))); p.insert(std::make_pair("depth",picojson::value((double)1))); picojson::value para = picojson::value(p); std::string param = para.serialize().c_str(); // リクエストメッセージの作成 OkaoServer::RequestMessage reqMsg; reqMsg.img = buf; reqMsg.param = param; // cout << "send to OKAOServer" << endl; // 送信 OkaoServer::sendRequestMessage(*responder, reqMsg); // 受信 //cout << "receive from OKAOServer" << endl; OkaoServer::ReplyMessage repMsg; OkaoServer::recvReplyMessage(*responder, &repMsg); std::cout << "repMsg.okao: " << repMsg.okao << std::endl; const char* json = repMsg.okao.c_str(); picojson::value v; std::string err; picojson::parse(v,json,json + strlen(json),&err); if(err.empty()) { int pos[4]; int people_num = 0; //一番外側のオブジェクトを取得 picojson::object& obj = v.get<picojson::object>(); //facesの中身があるならば if( obj.find("error") != obj.end() && obj["error"].get<std::string>().empty()) { if( obj.find("faces") != obj.end() ) { picojson::array array = obj["faces"].get<picojson::array>(); int people_num = array.size();//人数 humans_msgs::Humans okao_msg; okao_msg.human.resize(people_num); for( int n = 0; n<people_num; ++n) okao_msg.human[n].face.persons.resize(3); okao_msg.num = people_num;//OkaoサーバとKinectサーバで認識した人数の違いをどうするか? //cout << "people_num:" <<people_num << endl; //検出した人数分ループ int num = 0; for(picojson::array::iterator it = array.begin(); it != array.end(); ++it,++num) { picojson::object& person_obj = it->get<picojson::object>(); //顔の位置のとりだし picojson::array pos_array = person_obj["position"].get<picojson::array>(); for(int i = 0; i < 4; ++i) { pos[i] = (int)pos_array[i].get<double>(); } //人物ID,信頼度の取り出し picojson::array id_array = person_obj["id"].get<picojson::array>(); picojson::array db_info_array = person_obj["db_info"].get<picojson::array>(); //picojson::array id1 = id_array[0].get<picojson::array>(); //double conf = (int)id1[1].get<double>(); double tmp_id[3], tmp_conf[3]; std::string tmp_name[3], tmp_grade[3], tmp_laboratory[3]; ++callbackCount; if( !(callbackCount % SRVTEMPO) ) { stackSrv = true; callbackCount = 0; } for(int n = 0; n < OKAO; ++n) { picojson::array id_array_array = id_array[n].get<picojson::array>(); tmp_id[n] = (int)id_array_array[0].get<double>(); tmp_conf[n] = (int)id_array_array[1].get<double>(); picojson::object& db_info_obj = db_info_array[n].get<picojson::object>(); tmp_name[n] = db_info_obj["name"].get<std::string>(); tmp_grade[n] = db_info_obj["grade"].get<std::string>(); tmp_laboratory[n] = db_info_obj["laboratory"].get<std::string>(); //if(stackSrv){ //srv //stackSrv = false; ros::ServiceClient client = nh_.serviceClient<okao_client::OkaoStack>("okao_stack"); okao_client::OkaoStack stack; stack.request.rule = "add"; stack.request.okao_id = tmp_id[n]; stack.request.name = tmp_name[n]; stack.request.laboratory = tmp_laboratory[n]; stack.request.grade = tmp_grade[n]; if ( client.call(stack) ) cout << "service success!" << endl; else cout << "service missing!" << endl; //} } //一人目の信頼度を利用する if(tmp_conf[0] < 200) { for(int n = 0; n < OKAO; ++n) { tmp_id[n] = 0; tmp_conf[n] = 0; tmp_name[n] = "Unknown"; tmp_laboratory[n] = "Unknown"; tmp_grade[n] = "Unknown"; } } for(int n = 0; n < OKAO; ++n) { okao_msg.human[num].face.persons[n].okao_id = tmp_id[n]; okao_msg.human[num].face.persons[n].conf = tmp_conf[n]; okao_msg.human[num].face.persons[n].name = tmp_name[n]; okao_msg.human[num].face.persons[n].laboratory = tmp_laboratory[n]; okao_msg.human[num].face.persons[n].grade = tmp_grade[n]; } //顔の部分を四角で囲む cv::Point lt(pos[0],pos[1]); cv::Point rt(pos[2],pos[1]); cv::Point lb(pos[0],pos[3]); cv::Point rb(pos[2],pos[3]); cv::Scalar color(0, 0, 255); cv::line(rgbImage, lt , rt , color, 2); cv::line(rgbImage, rt , rb , color, 2); cv::line(rgbImage, rb , lb , color, 2); cv::line(rgbImage, lb , lt , color, 2); //名前の表示 cv::putText(rgbImage,tmp_name[0],rb,FONT_HERSHEY_SIMPLEX,2.5,color,2,CV_AA); okao_msg.human[num].face.position.lt.x = pos[0]*resize_width; okao_msg.human[num].face.position.lt.y = pos[1]*resize_height; okao_msg.human[num].face.position.rt.x = pos[2]*resize_width; okao_msg.human[num].face.position.rt.y = pos[1]*resize_height; okao_msg.human[num].face.position.lb.x = pos[0]*resize_width; okao_msg.human[num].face.position.lb.y = pos[3]*resize_height; okao_msg.human[num].face.position.rb.x = pos[2]*resize_width; okao_msg.human[num].face.position.rb.y = pos[3]*resize_height; } //Mat tmpRgbImage(rgbImage, cv::Rect(640, 360, 640, 360)); cv::imshow(OPENCV_WINDOW, rgbImage); cv::waitKey(1); //パブリッシュ okao_msg.header.stamp = ros::Time::now(); okao_msg.header.frame_id = "okao"; okaoData_pub_.publish(okao_msg); } } } } catch(const zmq::error_t& e) { std::cout << e.what() << std::endl; return ; } } }; int main(int argc, char** argv) { ros::init(argc, argv, "OkaoClientSub2"); ImageConverter ic; ros::spin(); return 0; }
[ "cvpapero14@gmail.com" ]
cvpapero14@gmail.com
11ce43bc04e9b2ae857ff37009196d95d732c543
4feaa7c33d6ad4885de30b90568a909332cbe334
/main.cpp
7fa2c6c41cc5f43798188597b8977ea2604a3b73
[]
no_license
WilliamAuCS/Edit-Distance
a71165f0cf2f17728d7467d119f87504a95cce61
a32dd497335d5e5c9574c957f02c10038c720796
refs/heads/master
2020-09-13T16:32:14.582349
2019-11-20T19:07:30
2019-11-20T19:07:30
222,842,074
0
0
null
null
null
null
UTF-8
C++
false
false
123
cpp
#include <iostream> #include "Edits.cpp" int main() { EditDistance edit; edit.findMatrix("broad", "board"); return 0; }
[ "WilliamAuCS@gmail.com" ]
WilliamAuCS@gmail.com
d36f1b79250b29026c085ff86a3b0184c0182d9c
cb38863a57da0fc7bbee3174f74f68dc59746cb9
/code/rocket/RocketMenuPlugin.cpp
5ccbf2e33fe17a0211bdbbfab937a276b11b9ad2
[]
no_license
dylski/duke3d-megaton
82397b8d0349496f680f7f2e84146dfd993eda11
4761ba83b46917aa4229365e40f32cf24ed71d0b
refs/heads/master
2021-01-15T12:10:19.217462
2013-09-27T14:45:54
2013-09-27T14:45:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
35,860
cpp
// // Created by Sergei Shubin <s.v.shubin@gmail.com> // #include "RocketMenuPlugin.h" #include <Rocket/Core.h> #include <Rocket/Core/Element.h> #include "PluginUtils.h" #include "helpers.h" #include "math.h" static void SetActiveKeySlot(Rocket::Core::Element *menu_item, int active_key); /*** Context Data ***/ struct ContextData { Rocket::Core::ElementDocument *current_document; ContextData():current_document(0) {} virtual ~ContextData(){}; }; static void SetContextData(Rocket::Core::Context *context, ContextData *user_data) { SetElementUserData(context->GetRootElement(), (void*)user_data, "__menu_context_data"); } static ContextData* GetContextData(Rocket::Core::Context *context) { return (ContextData*)GetElementUserData(context->GetRootElement(), "__menu_context_data"); } /*** Document Data ***/ struct DocumentData { Rocket::Core::Element *menu; Rocket::Core::Element *active_item; Rocket::Core::Element *cursor_left, *cursor_right; int active_key; DocumentData():active_item(0),menu(0),cursor_left(0),cursor_right(0),active_key(0) {} virtual ~DocumentData() {}; }; static void SetDocumentData(Rocket::Core::ElementDocument *document, DocumentData *doc_data) { SetElementUserData(document, (void*)doc_data, "__menu_doc_data"); } static DocumentData* GetDocumentData(Rocket::Core::ElementDocument *document) { return (DocumentData*)GetElementUserData(document, "__menu_doc_data"); } /*** Options Data ***/ struct OptionsData { Rocket::Core::Element *menu_item; Rocket::Core::Element *hdr, *ftr; Rocket::Core::ElementList options; Rocket::Core::ElementList::iterator current; OptionsData():menu_item(NULL),hdr(NULL),ftr(NULL){} virtual ~OptionsData() {}; }; static void SetOptionsData(Rocket::Core::Element *element, OptionsData *data) { SetElementUserData(element, (void*)data, "__menu_options_data"); } static OptionsData* GetOptionsData(Rocket::Core::Element *element) { return (OptionsData*)GetElementUserData(element, "__menu_options_data"); } /*** Range Data ***/ struct RangeData { Rocket::Core::Element *menu_item; Rocket::Core::Element *hdr, *ftr; Rocket::Core::Element *range; // Rocket::Core::Element *rail, *grip; // float rail_x, rail_y, rail_length; float min, max, value, step; RangeData():menu_item(NULL),hdr(NULL),ftr(NULL),range(NULL), // rail(NULL),grip(NULL), min(0.0f),max(1.0f),value(0.0f),step(0.1f) {} virtual ~RangeData() {}; }; static void SetRangeData(Rocket::Core::Element *element, RangeData *data) { SetElementUserData(element, (void*)data, "__menu_range_data"); } static RangeData* GetRangeData(Rocket::Core::Element *element) { return (RangeData*)GetElementUserData(element, "__menu_range_data"); } /*** Key Data ***/ struct KeyData { Rocket::Core::Element *menu_item; Rocket::Core::Element *hdr1, *ftr1; Rocket::Core::Element *hdr2, *ftr2; Rocket::Core::Element *opt1, *opt2; KeyData():menu_item(NULL),hdr1(NULL),ftr1(NULL),hdr2(NULL),ftr2(NULL),opt1(NULL),opt2(NULL){} virtual ~KeyData(){} }; static void SetKeyData(Rocket::Core::Element *element, KeyData *data) { SetElementUserData(element, (void*)data, "__menu_key_data"); } static KeyData* GetKeyData(Rocket::Core::Element *element) { return (KeyData*)GetElementUserData(element, "__menu_key_data"); } /************/ RocketMenuPlugin::RocketMenuPlugin():m_animation(0),m_delegate(0) { } RocketMenuPlugin::~RocketMenuPlugin() { } void RocketMenuPlugin::OnInitialise() { } void RocketMenuPlugin::OnShutdown() { } void RocketMenuPlugin::OnDocumentOpen(Rocket::Core::Context* context, const Rocket::Core::String& document_path) { } void RocketMenuPlugin::SetupOptions(Rocket::Core::Element *menu_item, Rocket::Core::Element *options_element) { OptionsData *data = new OptionsData(); SetOptionsData(menu_item, data); data->menu_item = menu_item; options_element->GetElementsByTagName(data->options, "option"); if (data->options.size() == 0) { if (m_delegate != NULL) { m_delegate->PopulateOptions(menu_item, options_element); options_element->GetElementsByTagName(data->options, "option"); } } data->hdr = Rocket::Core::Factory::InstanceElement(options_element, "hdr", "hdr", Rocket::Core::XMLAttributes()); data->hdr->AddEventListener("click", this); data->hdr->SetInnerRML("&lt;"); ShowElement(data->hdr, false); options_element->InsertBefore(data->hdr, options_element->GetFirstChild()); data->hdr->RemoveReference(); data->ftr = Rocket::Core::Factory::InstanceElement(options_element, "ftr", "ftr", Rocket::Core::XMLAttributes()); data->ftr->AddEventListener("click", this); data->ftr->SetInnerRML("&gt;"); ShowElement(data->ftr, false); options_element->AppendChild(data->ftr); data->ftr->RemoveReference(); for (Rocket::Core::ElementList::iterator i = data->options.begin(); i != data->options.end(); i++) { Rocket::Core::Element *element = *i; ShowElement(element, false); } data->current = data->options.begin(); ShowElement(*data->current, true); } void RocketMenuPlugin::SetupRange(Rocket::Core::Element *menu_item, Rocket::Core::Element *range_element) { RangeData *data = new RangeData(); SetRangeData(menu_item, data); data->menu_item = menu_item; if (range_element->HasAttribute("min")) { data->min = range_element->GetAttribute("min")->Get<float>(); } if (range_element->HasAttribute("max")) { data->max = range_element->GetAttribute("max")->Get<float>(); } if (range_element->HasAttribute("value")) { data->value = range_element->GetAttribute("value")->Get<float>(); } if (range_element->HasAttribute("step")) { data->step = range_element->GetAttribute("step")->Get<float>(); } data->hdr = Rocket::Core::Factory::InstanceElement(range_element, "hdr", "hdr", Rocket::Core::XMLAttributes()); data->hdr->AddEventListener("click", this); data->hdr->SetInnerRML("&lt;"); ShowElement(data->hdr, false); //options_element->InsertBefore(data->hdr, options_element->GetFirstChild()); range_element->AppendChild(data->hdr); data->hdr->RemoveReference(); Rocket::Core::XMLAttributes input_attrs; input_attrs.Set("type", "range"); input_attrs.Set("min", 0.0f); input_attrs.Set("max", 1.0f); input_attrs.Set("step", 0.001f); input_attrs.Set("value", (data->value - data->min)/(data->max - data->min)); data->range = Rocket::Core::Factory::InstanceElement(range_element, "input", "input", input_attrs); data->range->AddEventListener("change", this); data->range->SetProperty("margin-top", "15px"); range_element->AppendChild(data->range); data->range->RemoveReference(); data->ftr = Rocket::Core::Factory::InstanceElement(range_element, "ftr", "ftr", Rocket::Core::XMLAttributes()); data->ftr->AddEventListener("click", this); data->ftr->SetInnerRML("&gt;"); ShowElement(data->ftr, false); range_element->AppendChild(data->ftr); data->ftr->RemoveReference(); SetRangeValue(menu_item, data->value, false); } void RocketMenuPlugin::SetupKeyChooser(Rocket::Core::Element *element) { Rocket::Core::String caption; element->GetInnerRML(caption); element->SetInnerRML("<caption/><keys><key1><hdr>&lt;</hdr><keyval/><ftr>&gt;</ftr></key1><key2><hdr>&lt;</hdr><keyval/><ftr>&gt;</ftr></key2></keys>"); Rocket::Core::Element *caption_element = element->GetChild(0); caption_element->SetInnerRML(caption); Rocket::Core::Element *keys_element = element->GetChild(1); Rocket::Core::Element *key1_element = keys_element->GetChild(0); Rocket::Core::Element *key2_element = keys_element->GetChild(1); key1_element->AddEventListener("mousemove", this, false); key2_element->AddEventListener("mousemove", this, false); KeyData *data = new KeyData(); data->menu_item = element; data->hdr1 = key1_element->GetChild(0); data->opt1 = key1_element->GetChild(1); data->ftr1 = key1_element->GetChild(2); data->hdr2 = key2_element->GetChild(0); data->opt2 = key2_element->GetChild(1); data->ftr2 = key2_element->GetChild(2); data->opt1->SetInnerRML("None"); data->opt2->SetInnerRML("None"); ShowElement(data->hdr1, false); ShowElement(data->ftr1, false); ShowElement(data->hdr2, false); ShowElement(data->ftr2, false); SetKeyData(element, data); } void RocketMenuPlugin::SetupMenuItem(Rocket::Core::Element *element) { element->AddEventListener("click", this); element->AddEventListener("mousemove", this); element->AddEventListener("mouseout", this); if (element->HasAttribute("options") && element->GetNumChildren() > 0) { Rocket::Core::ElementList options_list; element->GetElementsByTagName(options_list, "options"); if (options_list.size() > 0) { SetupOptions(element, options_list[0]); } } if (element->HasAttribute("range") && element->GetNumChildren() > 0) { Rocket::Core::ElementList elist; element->GetElementsByTagName(elist, "range"); if (elist.size() > 0) { SetupRange(element, elist[0]); } } if (element->HasAttribute("key-chooser")) { SetupKeyChooser(element); } } void RocketMenuPlugin::OnDocumentLoad(Rocket::Core::ElementDocument* document) { DocumentData *doc_data = new DocumentData(); doc_data->cursor_left = document->GetElementById("cursor-left"); doc_data->cursor_right = document->GetElementById("cursor-right"); doc_data->menu = document->GetElementById("menu"); if (doc_data->menu == NULL) { for (int i = 0, n = document->GetNumChildren(); i!=n; i++) { Rocket::Core::Element *element = document->GetChild(i); if (element->IsClassSet("game-menu")) { doc_data->menu = element; break; } } } if (doc_data->menu != NULL) { for (int i = 0, n = doc_data->menu->GetNumChildren(); i < n; i++) { Rocket::Core::Element *e = doc_data->menu->GetChild(i); SetupMenuItem(e); } SetDocumentData(document, doc_data); } else { delete doc_data; } } // Called when a document is unloaded from its context. This is called after the document's 'unload' event. void RocketMenuPlugin::OnDocumentUnload(Rocket::Core::ElementDocument* document) { delete GetDocumentData(document); } // Called when a new context is created. void RocketMenuPlugin::OnContextCreate(Rocket::Core::Context* context) { SetContextData(context, new ContextData()); } // Called when a context is destroyed. void RocketMenuPlugin::OnContextDestroy(Rocket::Core::Context* context) { ContextData *data = GetContextData(context); if (data != NULL) { delete data; SetContextData(context, NULL); } } // Called when a new element is created void RocketMenuPlugin::OnElementCreate(Rocket::Core::Element* element) { } // Called when an element is destroyed. void RocketMenuPlugin::OnElementDestroy(Rocket::Core::Element* element) { OptionsData *options_data = GetOptionsData(element); if (options_data != NULL) { delete options_data; SetOptionsData(element, NULL); } RangeData *range_data = GetRangeData(element); if (range_data != NULL) { delete range_data; SetRangeData(element, NULL); } KeyData *key_data = GetKeyData(element); if (key_data != NULL) { delete key_data; SetKeyData(element, NULL); } } class ColorAnimation: public BasicAnimationActuator { private: rgb p, q; //Rocket::Core::String initial_color; //Rocket::Core::Colourb initial_color; void ApplyColorsForPosition(Rocket::Core::Element *e, float position) { rgb v = rgb_lerp(p, q, position); char color[50]; int r = (int)(v.r*255); int g = (int)(v.g*255); int b = (int)(v.b*255); sprintf(color, "rgb(%d,%d,%d)", r, g, b); e->SetProperty("color", color);; } public: ColorAnimation(rgb p, rgb q, float offset):p(p),q(q) { } virtual void Init(Rocket::Core::Element *element) { /* initial_color = element->GetProperty<Rocket::Core::Colourb>("color"); */ }; virtual void Apply(Rocket::Core::Element *e, float position) { ApplyColorsForPosition(e, position); } virtual void Stop(Rocket::Core::Element *e) {}; virtual void Reset(Rocket::Core::Element *e) { e->RemoveProperty("color"); }; }; void RocketMenuPlugin::ProcessEvent(Rocket::Core::Event& event) { Rocket::Core::Element *element = event.GetCurrentElement(); if (event.GetType() == "click") { if (element->GetTagName() == "ftr") { SetNextItemValue(element->GetParentNode()->GetParentNode()); event.StopPropagation(); } else if (element->GetTagName() == "hdr") { SetPreviousItemValue(element->GetParentNode()->GetParentNode()); event.StopPropagation(); } else { DoItemAction(ItemActionEnter, element); } } else if (event.GetType() == "mousemove") { if (element->GetTagName() == "div") { HighlightItem(element); } else if (element->GetTagName() == "key1") { Rocket::Core::Element *menu_item = element->GetParentNode()->GetParentNode(); SetActiveKeySlot(menu_item, 0); } else if (element->GetTagName() == "key2") { Rocket::Core::Element *menu_item = element->GetParentNode()->GetParentNode(); SetActiveKeySlot(menu_item, 1); } } else if (event.GetType() == "change") { if (m_delegate != NULL && element->GetOwnerDocument()->IsVisible()) { Rocket::Core::Element *menu_item = element->GetParentNode()->GetParentNode(); RangeData *data = GetRangeData(menu_item); const Rocket::Core::Dictionary *p = event.GetParameters(); float v = p->Get("value")->Get<float>(); float new_value = data->min + v*(data->max - data->min); if (fabs(new_value-data->value) > 0.001f) { data->value = new_value; m_delegate->DidChangeRangeValue(menu_item, data->value); } } } } void RocketMenuPlugin::ShowDocument(Rocket::Core::Context* context, const Rocket::Core::String& id, bool backlink) { ContextData *cd = GetContextData(context); Rocket::Core::ElementDocument *new_doc = context->GetDocument(id); if (new_doc != NULL) { if (new_doc != cd->current_document) { if (cd->current_document != NULL) { if (cd->current_document->IsVisible()) { cd->current_document->Hide(); if (m_delegate) { m_delegate->DidCloseMenuPage(cd->current_document); } } if (backlink) { new_doc->SetAttribute("parent", cd->current_document->GetId()); } } cd->current_document = new_doc; DocumentData *dd = GetDocumentData(cd->current_document); if (cd->current_document->HasAttribute("default-item")) { Rocket::Core::String def; cd->current_document->GetAttribute("default-item")->GetInto(def); if (dd->menu != NULL) { HighlightItem(cd->current_document->GetElementById(def)); } } else { if (dd->active_item == NULL) { if (dd->menu != NULL) { HighlightItem(dd->menu->GetChild(0)); } } } if (!cd->current_document->IsVisible()) { cd->current_document->Show(); if (m_delegate) { m_delegate->DidOpenMenuPage(cd->current_document); } } } } else { printf("[ROCK] unable to show document with id: %s\n", id.CString()); } } bool RocketMenuPlugin::GoBack(Rocket::Core::Context *context, bool notify_delegate) { ContextData *cd = GetContextData(context); if (cd->current_document != NULL) { Rocket::Core::Variant *attr = cd->current_document->GetAttribute("parent"); if (attr != NULL) { Rocket::Core::String menu_id = attr->Get<Rocket::Core::String>(); if (cd->current_document->HasAttribute("closecmd") && notify_delegate) { Rocket::Core::String closecmd; cd->current_document->GetAttribute("closecmd")->GetInto(closecmd); cd->current_document->RemoveAttribute("closecmd"); m_delegate->DoCommand(cd->current_document, closecmd); cd->current_document->SetAttribute("closecmd", closecmd); } ShowDocument(context, menu_id, false); return true; } } return false; } void RocketMenuPlugin::SetAnimationPlugin(RocketAnimationPlugin *p) { m_animation = p; } static void AttachCursor(Rocket::Core::Element *menu_item, Rocket::Core::Element *cursor_left, Rocket::Core::Element *cursor_right) { float item_width = menu_item->GetOffsetWidth(); float item_height = menu_item->GetOffsetHeight(); float item_x = menu_item->GetAbsoluteLeft(); float item_y = menu_item->GetAbsoluteTop(); if (cursor_left != NULL) { float cursor_height = cursor_left->GetOffsetHeight(); cursor_left->SetProperty("left", Rocket::Core::Property(item_x-cursor_left->GetOffsetWidth(), Rocket::Core::Property::PX)); cursor_left->SetProperty("top", Rocket::Core::Property(item_y + (item_height-cursor_height)/2, Rocket::Core::Property::PX)); } if (cursor_right != NULL) { float cursor_height = cursor_right->GetOffsetHeight(); cursor_right->SetProperty("left", Rocket::Core::Property(item_x+item_width, Rocket::Core::Property::PX)); cursor_right->SetProperty("top", Rocket::Core::Property(item_y + (item_height-cursor_height)/2, Rocket::Core::Property::PX)); } } static void DoScroll(Rocket::Core::Element *old, Rocket::Core::Element *neww, Rocket::Core::Element *scroll) { //float scroll_height = scroll->GetScrollHeight(); float new_top = neww->GetOffsetTop(); float new_height = neww->GetOffsetHeight(); float window_height = scroll->GetOffsetHeight(); float position = scroll->GetScrollTop(); if (new_top < position || (new_top + new_height > position + window_height)) { if (old == NULL) { position = new_top+new_height/2-window_height/2; } else { float old_top = old->GetOffsetTop(); if (old_top < new_top) { position = new_top+new_height-window_height; } else { position = new_top; } } scroll->SetScrollTop(position); } } static void UpdateKeyChooser(KeyData *data, int active_key, bool highlight) { ShowElement(data->hdr1, highlight && !active_key); ShowElement(data->ftr1, highlight && !active_key); ShowElement(data->hdr2, highlight && active_key); ShowElement(data->ftr2, highlight && active_key); } void RocketMenuPlugin::HighlightItem(Rocket::Core::Element *e) { static ColorAnimation colorAnimation(rgb(255,255,255), rgb(235, 156, 9), 1); DocumentData *doc_data = GetDocumentData(e->GetOwnerDocument()); if (doc_data != NULL) { if (doc_data->active_item != e && !e->IsClassSet("disabled")) { if (doc_data->active_item != NULL) { m_animation->CancelAnimation(doc_data->active_item); OptionsData *options_data = GetOptionsData(doc_data->active_item); if (options_data != NULL) { ShowElement(options_data->hdr, false); ShowElement(options_data->ftr, false); } RangeData *range_data = GetRangeData(doc_data->active_item); if (range_data != NULL) { ShowElement(range_data->hdr, false); ShowElement(range_data->ftr, false); } KeyData *key_data = GetKeyData(doc_data->active_item); if (key_data != NULL) { UpdateKeyChooser(key_data, doc_data->active_key, false); } } if (e != NULL) { if (e->GetParentNode()->HasAttribute("scroll")) { DoScroll(doc_data->active_item, e, e->GetParentNode()->GetParentNode()); } if (!e->HasAttribute("noanim")) { m_animation->AnimateElement(e, AnimationTypeBounce, 0.3f, &colorAnimation); } AttachCursor(e, doc_data->cursor_left, doc_data->cursor_right); OptionsData *options_data = GetOptionsData(e); if (options_data != NULL) { ShowElement(options_data->hdr, true); ShowElement(options_data->ftr, true); } RangeData *range_data = GetRangeData(e); if (range_data != NULL) { ShowElement(range_data->hdr, true); ShowElement(range_data->ftr, true); } KeyData *key_data = GetKeyData(e); if (key_data != NULL) { UpdateKeyChooser(key_data, doc_data->active_key, true); } m_delegate->DidActivateItem(e); } doc_data->active_item = e; } } } void RocketMenuPlugin::HighlightItem(Rocket::Core::ElementDocument *document, const Rocket::Core::String& id) { Rocket::Core::Element *element = document->GetElementById(id); if (element != 0) { HighlightItem(element); } else { printf("[ROCK] RocketMenuPlugin::HighlightItem: unable to find element with id='%s'\n", id.CString()); } } void RocketMenuPlugin::HighlightItem(Rocket::Core::Context *context, const Rocket::Core::String& docId, const Rocket::Core::String& elementId) { Rocket::Core::ElementDocument *doc = context->GetDocument(docId); if (doc != NULL) { HighlightItem(doc, elementId); } else { printf("[ROCK] RocketMenuPlugin::HighlightItem: unable to find document with id='%s'\n", docId.CString()); } } void RocketMenuPlugin::HighlightItem(Rocket::Core::Context *context, const Rocket::Core::String& elementId) { ContextData *cd = GetContextData(context); if (cd->current_document != NULL) { HighlightItem(cd->current_document, elementId); } } Rocket::Core::Element* RocketMenuPlugin::FindNextItem(Rocket::Core::Element *menu_item) { Rocket::Core::Element *next = menu_item; do { next = next->GetNextSibling(); if (next == NULL) { next = menu_item->GetParentNode()->GetChild(0); } } while (next->IsClassSet("disabled") && next != menu_item); return next; } Rocket::Core::Element* RocketMenuPlugin::FindPreviousItem(Rocket::Core::Element *menu_item) { Rocket::Core::Element *next = menu_item; do { next = next->GetPreviousSibling(); if (next == NULL) { next = menu_item->GetParentNode()->GetChild(menu_item->GetParentNode()->GetNumChildren()-1); } } while (next->IsClassSet("disabled") && next != menu_item); return next; } void RocketMenuPlugin::HighlightNextItem(Rocket::Core::ElementDocument *document = NULL) { DocumentData *doc_data = GetDocumentData(document); if (doc_data != NULL) { if (doc_data->active_item != NULL) { Rocket::Core::Element *e = FindNextItem(doc_data->active_item); if (e != NULL) { HighlightItem(e); } } } else { printf("[ROCK] RocketMenuPlugin::HighlightNextItem: attempt to activate next item on the document with no menu\n"); } } void RocketMenuPlugin::HighlightNextItem(Rocket::Core::Context *context, const Rocket::Core::String& docId) { Rocket::Core::ElementDocument *doc = NULL; if (docId == "") { ContextData *cd = GetContextData(context); doc = cd->current_document; } else { doc = context->GetDocument(docId); } if (doc != NULL) { HighlightNextItem(doc); } else { printf("[ROCK] RocketMenuPlugin::HighlightNextItem: document not found: %s\n", docId.CString()); } } void RocketMenuPlugin::HighlightPreviousItem(Rocket::Core::ElementDocument *document) { DocumentData *doc_data = GetDocumentData(document); if (doc_data != NULL) { if (doc_data->active_item != NULL) { Rocket::Core::Element *e = FindPreviousItem(doc_data->active_item); if (e != NULL) { HighlightItem(e); } } } else { printf("[ROCK] RocketMenuPlugin::HighlightPreviousItem: attempt to activate next item on the document with no menu\n"); } } void RocketMenuPlugin::HighlightPreviousItem(Rocket::Core::Context *context, const Rocket::Core::String& docId) { Rocket::Core::ElementDocument *doc = NULL; if (docId == "") { ContextData *cd = GetContextData(context); doc = cd->current_document; } else { doc = context->GetDocument(docId); } if (doc != NULL) { HighlightPreviousItem(doc); } else { printf("[ROCK] RocketMenuPlugin::HighlightPreviousItem: document not found: %s\n", docId.CString()); } } void RocketMenuPlugin::DoItemAction(ItemAction action, Rocket::Core::Element *e) { if (!e->IsClassSet("disabled")) { switch (action) { case ItemActionEnter: { if (e->HasAttribute("submenu")) { bool backlink = !e->HasAttribute("noref"); Rocket::Core::String submenu; e->GetAttribute("submenu")->GetInto(submenu); ShowDocument(e->GetContext(), submenu, backlink); } if (e->HasAttribute("command") && m_delegate != NULL) { Rocket::Core::String command; e->GetAttribute("command")->GetInto(command); m_delegate->DoCommand(e, command); } if (e->HasAttribute("options")) { ActivateNextOption(e); } RequestKeyForKeyChooser(e); break; } case ItemActionLeft: if (e->HasAttribute("options")) { ActivatePreviousOption(e); } break; case ItemActionRight: if (e->HasAttribute("options")) { ActivateNextOption(e); } break; case ItemActionClear: { ClearMenuItem(e); break; } } } } void RocketMenuPlugin::DoItemAction(ItemAction action, Rocket::Core::ElementDocument *document, const Rocket::Core::String& id) { Rocket::Core::Element *element = document->GetElementById(id); if (element != NULL) { DoItemAction(action, element); } else { printf("[ROCK] RocketMenuPlugin::DoItemAction: element not found: %s\n", id.CString()); } } void RocketMenuPlugin::DoItemAction(ItemAction action, Rocket::Core::Context *context, const Rocket::Core::String& docId, const Rocket::Core::String& elementId) { Rocket::Core::ElementDocument *doc = context->GetDocument(docId); if (doc != NULL) { DoItemAction(action, doc, elementId); } else { printf("[ROCK] RocketMenuPlugin::DoItemAction: document not found: %s\n", docId.CString()); } } void RocketMenuPlugin::DoItemAction(ItemAction action, Rocket::Core::Context *context, const Rocket::Core::String& id) { ContextData *cd = GetContextData(context); if (cd->current_document != NULL) { DocumentData *dd = GetDocumentData(cd->current_document); Rocket::Core::Element *e = NULL; if (id != "") { e = cd->current_document->GetElementById(id); } else if (dd != NULL) { e = dd->active_item; } if (e != NULL) { DoItemAction(action, e); } } } Rocket::Core::Element* RocketMenuPlugin::GetHighlightedItem(Rocket::Core::ElementDocument *doc) { DocumentData *dd = GetDocumentData(doc); return dd ? dd->active_item : NULL; } Rocket::Core::Element* RocketMenuPlugin::GetHighlightedItem(Rocket::Core::Context *context, const Rocket::Core::String& docId) { Rocket::Core::ElementDocument *doc = context->GetDocument(docId); return doc ? GetHighlightedItem(doc) : NULL; } void RocketMenuPlugin::SetDelegate(RocketMenuDelegate *delegate) { m_delegate = delegate; } RocketMenuDelegate* RocketMenuPlugin::GetDelegate() { return m_delegate; } void RocketMenuPlugin::ActivateNextOption(Rocket::Core::Element *menu_item) { OptionsData *data = GetOptionsData(menu_item); if (data != NULL) { Rocket::Core::ElementList::iterator next = data->current+1; if (next == data->options.end()) { next = data->options.begin(); } ActivateOption(data, next); } } void RocketMenuPlugin::ActivatePreviousOption(Rocket::Core::Element *menu_item) { OptionsData *data = GetOptionsData(menu_item); if (data != NULL) { Rocket::Core::ElementList::iterator next = data->current; if (next == data->options.begin()) { next = data->options.end()-1; } else { next--; } ActivateOption(data, next); } } void RocketMenuPlugin::ActivateOption(Rocket::Core::Element *menu_item, Rocket::Core::Element *option, bool notify_delegate) { OptionsData *data = GetOptionsData(menu_item); if (data != NULL) { Rocket::Core::ElementList::iterator next = data->options.end(); for (Rocket::Core::ElementList::iterator i = data->options.begin(); i != data->options.end(); i++) { if (*i == option) { next = i; break; } } if (next != data->options.end()) { ActivateOption(data, next, notify_delegate); } } } void RocketMenuPlugin::ActivateOption(Rocket::Core::Element *menu_item, const Rocket::Core::String& option_id, bool notify_delegate) { OptionsData *data = GetOptionsData(menu_item); if (data != NULL) { Rocket::Core::ElementList::iterator next = data->options.end(); for (Rocket::Core::ElementList::iterator i = data->options.begin(); i != data->options.end(); i++) { if ((*i)->GetId() == option_id) { next = i; break; } } if (next != data->options.end()) { ActivateOption(data, next, notify_delegate); } } } void RocketMenuPlugin::ActivateOption(OptionsData *data, Rocket::Core::ElementList::iterator next, bool notify_delegate) { if (next != data->current) { ShowElement(*data->current, false); ShowElement(*next, true); data->current = next; if (m_delegate != NULL && notify_delegate) { m_delegate->DidChangeOptionValue(data->menu_item, *(data->current)); } } } void RocketMenuPlugin::SetNextItemValue(Rocket::Core::Context *context) { ContextData *cd = GetContextData(context); if (cd != NULL) { Rocket::Core::ElementDocument *doc = cd->current_document; if (doc != NULL) { DocumentData *dd = GetDocumentData(doc); if (dd != NULL) { SetNextItemValue(dd->active_item); } } } } void RocketMenuPlugin::SetPreviousItemValue(Rocket::Core::Context *context) { ContextData *cd = GetContextData(context); if (cd != NULL) { Rocket::Core::ElementDocument *doc = cd->current_document; if (doc != NULL) { DocumentData *dd = GetDocumentData(doc); if (dd != NULL) { SetPreviousItemValue(dd->active_item); } } } } Rocket::Core::ElementDocument* RocketMenuPlugin::GetCurrentPage(Rocket::Core::Context *context) { ContextData *cd = GetContextData(context); if (cd != NULL) { return cd->current_document; } return NULL; } Rocket::Core::Element* RocketMenuPlugin::GetMenuItem(Rocket::Core::ElementDocument *doc, const Rocket::Core::String& id) { DocumentData *dd = GetDocumentData(doc); if (dd != NULL) { return dd->menu->GetElementById(id); } return NULL; } Rocket::Core::Element* RocketMenuPlugin::GetMenuItem(Rocket::Core::ElementDocument *doc, int index) { DocumentData *dd = GetDocumentData(doc); if (dd != NULL) { return dd->menu->GetChild(index); } return NULL; } int RocketMenuPlugin::GetNumMenuItems(Rocket::Core::ElementDocument *doc) { DocumentData *dd = GetDocumentData(doc); if (dd != NULL) { return dd->menu->GetNumChildren(); } return NULL; } Rocket::Core::Element* RocketMenuPlugin::GetActiveOption(Rocket::Core::Element *menu_item) { OptionsData *data = GetOptionsData(menu_item); if (data != NULL) { return *(data->current); } return NULL; } Rocket::Core::Element* RocketMenuPlugin::GetOptionById(Rocket::Core::Element *menu_item, const Rocket::Core::String& option_id) { OptionsData *data = GetOptionsData(menu_item); if (data != NULL) { for (Rocket::Core::ElementList::iterator i = data->options.begin(); i != data->options.end(); i++) { if ((*i)->GetId() == option_id) { return *i; } } } return NULL; } void RocketMenuPlugin::SetRangeValue(Rocket::Core::Element *menu_item, float value, bool notify_delegate) { RangeData *data = GetRangeData(menu_item); if (data != NULL) { Rocket::Core::String tmp; // printf("=======\n"); // data->range->GetAttribute("min")->GetInto(tmp); // printf("min: %s\n", tmp.CString()); // data->range->GetAttribute("max")->GetInto(tmp); // printf("max: %s\n", tmp.CString()); // data->range->GetAttribute("value")->GetInto(tmp); // printf("value: %s\n", tmp.CString()); // data->range->GetAttribute("step")->GetInto(tmp); // printf("step: %s\n", tmp.CString()); data->value = clamp(value, data->min, data->max); data->range->SetAttribute("value", (data->value - data->min)/(data->max - data->min)); #if 0 float position = data->rail_x + data->value/(data->max-data->min)*data->rail_length; data->grip->SetProperty("left", Rocket::Core::Property(position, Rocket::Core::Property::PX)); #endif // if (m_delegate != NULL && notify_delegate) { // m_delegate->DidChangeRangeValue(menu_item, value); // } } } float RocketMenuPlugin::GetRangeValue(Rocket::Core::Element *menu_item) { RangeData *data = GetRangeData(menu_item); if (data != NULL) { return data->value; } return 0.0f; } void RocketMenuPlugin::IncreaseRangeValue(Rocket::Core::Element *menu_item) { RangeData *data = GetRangeData(menu_item); if (data != NULL) { SetRangeValue(menu_item, data->value + data->step); } } void RocketMenuPlugin::DecreaseRangeValue(Rocket::Core::Element *menu_item) { RangeData *data = GetRangeData(menu_item); if (data != NULL) { SetRangeValue(menu_item, data->value - data->step); } } static void ChangeActiveKeySlot(Rocket::Core::Element *menu_item) { Rocket::Core::Context *context = menu_item->GetContext(); DocumentData *document_data = GetDocumentData(menu_item->GetOwnerDocument()); KeyData *key_data = GetKeyData(menu_item); if (document_data != NULL && key_data != NULL) { document_data->active_key = 1-document_data->active_key; UpdateKeyChooser(key_data, document_data->active_key, true); } } static void SetActiveKeySlot(Rocket::Core::Element *menu_item, int active_key) { Rocket::Core::Context *context = menu_item->GetContext(); DocumentData *document_data = GetDocumentData(menu_item->GetOwnerDocument()); KeyData *key_data = GetKeyData(menu_item); if (document_data != NULL && key_data != NULL) { document_data->active_key = active_key; UpdateKeyChooser(key_data, document_data->active_key, true); } } void RocketMenuPlugin::SetNextItemValue(Rocket::Core::Element *menu_item) { ActivateNextOption(menu_item); IncreaseRangeValue(menu_item); ChangeActiveKeySlot(menu_item); } void RocketMenuPlugin::SetPreviousItemValue(Rocket::Core::Element *menu_item) { ActivatePreviousOption(menu_item); DecreaseRangeValue(menu_item); ChangeActiveKeySlot(menu_item); } void RocketMenuPlugin::RequestKeyForKeyChooser(Rocket::Core::Element *menu_item) { Rocket::Core::Context *context = menu_item->GetContext(); DocumentData *document_data = GetDocumentData(menu_item->GetOwnerDocument()); KeyData *key_data = GetKeyData(menu_item); if (document_data != NULL && key_data != NULL && m_delegate != NULL) { m_delegate->DidRequestKey(menu_item, document_data->active_key); } } void RocketMenuPlugin::SetKeyChooserValue(Rocket::Core::Element *menu_item, int slot, const Rocket::Core::String& text, const Rocket::Core::String& id) { DocumentData *document_data = GetDocumentData(menu_item->GetOwnerDocument()); KeyData *key_data = GetKeyData(menu_item); if (document_data != NULL && key_data != NULL && m_delegate != NULL) { Rocket::Core::Element *slot_element = slot ? key_data->opt2 : key_data->opt1; slot_element->SetId(id); slot_element->SetInnerRML(text); slot_element->SetClass("no-key-chosen", id == "None"); } } const Rocket::Core::String RocketMenuPlugin::GetKeyChooserValue(Rocket::Core::Element *menu_item, int slot) { DocumentData *document_data = GetDocumentData(menu_item->GetOwnerDocument()); KeyData *key_data = GetKeyData(menu_item); if (document_data != NULL && key_data != NULL && m_delegate != NULL) { Rocket::Core::Element *slot_element = slot ? key_data->opt2 : key_data->opt1; return slot_element->GetId(); } return ""; } void RocketMenuPlugin::ClearMenuItem(Rocket::Core::Element *menu_item) { KeyData *key_data = GetKeyData(menu_item); if (key_data != NULL) { DocumentData *document_data = GetDocumentData(menu_item->GetOwnerDocument()); if (document_data != NULL) { SetKeyChooserValue(menu_item, document_data->active_key, "None", "None"); if (m_delegate != NULL) { m_delegate->DidClearKeyChooserValue(menu_item, document_data->active_key); } } } }
[ "drtermit@gmail.com" ]
drtermit@gmail.com
a69fd8492c881d1ab489f0a97010836b57233465
bb72b975267b12fb678248ce565f3fd9bd6153ee
/testgles/NdkOpenGL/jni/platform/CCFileUtilsAndroid.cpp
f9b957bab3e90920de27ae626c6442e7898d1cc0
[]
no_license
fiskercui/testlanguage
cfbcc84ffaa31a535a7f898d6c7b42dcbf2dc71b
b15746d9fa387172b749e54a90e8c6251750f192
refs/heads/master
2021-05-30T13:26:11.792822
2016-01-13T02:03:26
2016-01-13T02:03:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,255
cpp
#include "base/ccMacros.h" #include "base/CCPlatformConfig.h" #include "CCFileUtilsAndroid.h" //#include "platform/CCCommon.h" #include "help/Java_com_example_ndkopengl_Cocos2dxHelper.h" #include "android/asset_manager.h" #include "android/asset_manager_jni.h" #include <stdlib.h> #include <string> #ifndef LOG_TAG #define LOG_TAG "CCFileUtilsAndroid.cpp" #endif #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__) using namespace std; NS_CC_BEGIN AAssetManager* FileUtilsAndroid::assetmanager = nullptr; void FileUtilsAndroid::setassetmanager(AAssetManager* a) { if (nullptr == a) { LOGD("setassetmanager : received unexpected nullptr parameter"); return; } cocos2d::FileUtilsAndroid::assetmanager = a; } FileUtils* FileUtils::getInstance() { if (s_sharedFileUtils == nullptr) { s_sharedFileUtils = new FileUtilsAndroid(); if(!s_sharedFileUtils->init()) { delete s_sharedFileUtils; s_sharedFileUtils = nullptr; CCLOG("ERROR: Could not init CCFileUtilsAndroid"); } } return s_sharedFileUtils; } FileUtilsAndroid::FileUtilsAndroid() { } FileUtilsAndroid::~FileUtilsAndroid() { } bool FileUtilsAndroid::init() { _defaultResRootPath = "assets/"; return FileUtils::init(); } bool FileUtilsAndroid::isFileExistInternal(const std::string& strFilePath) const { if (strFilePath.empty()) { return false; } bool bFound = false; // Check whether file exists in apk. if (strFilePath[0] != '/') { const char* s = strFilePath.c_str(); // Found "assets/" at the beginning of the path and we don't want it if (strFilePath.find(_defaultResRootPath) == 0) s += strlen("assets/"); if (FileUtilsAndroid::assetmanager) { AAsset* aa = AAssetManager_open(FileUtilsAndroid::assetmanager, s, AASSET_MODE_UNKNOWN); if (aa) { bFound = true; AAsset_close(aa); } else { // CCLOG("[AssetManager] ... in APK %s, found = false!", strFilePath.c_str()); } } } else { FILE *fp = fopen(strFilePath.c_str(), "r"); if(fp) { bFound = true; fclose(fp); } } return bFound; } bool FileUtilsAndroid::isAbsolutePath(const std::string& strPath) const { // On Android, there are two situations for full path. // 1) Files in APK, e.g. assets/path/path/file.png // 2) Files not in APK, e.g. /data/data/org.cocos2dx.hellocpp/cache/path/path/file.png, or /sdcard/path/path/file.png. // So these two situations need to be checked on Android. if (strPath[0] == '/' || strPath.find(_defaultResRootPath) == 0) { return true; } return false; } std::string FileUtilsAndroid::getStringFromFile(const std::string& filename) { return getData(filename, true); } std::string FileUtilsAndroid::getData(const std::string& filename, bool forString) { if (filename.empty()) { return ""; } unsigned char* data = nullptr; ssize_t size = 0; string fullPath = fullPathForFilename(filename); if (fullPath[0] != '/') { string relativePath = string(); size_t position = fullPath.find("assets/"); if (0 == position) { // "assets/" is at the beginning of the path and we don't want it relativePath += fullPath.substr(strlen("assets/")); } else { relativePath += fullPath; } LOGD("relative path = %s", relativePath.c_str()); if (nullptr == FileUtilsAndroid::assetmanager) { LOGD("... FileUtilsAndroid::assetmanager is nullptr"); return ""; } // read asset data AAsset* asset = AAssetManager_open(FileUtilsAndroid::assetmanager, relativePath.c_str(), AASSET_MODE_UNKNOWN); if (nullptr == asset) { LOGD("asset is nullptr"); return ""; } off_t fileSize = AAsset_getLength(asset); if (forString) { data = (unsigned char*) malloc(fileSize + 1); data[fileSize] = '\0'; } else { data = (unsigned char*) malloc(fileSize); } int bytesread = AAsset_read(asset, (void*)data, fileSize); size = bytesread; AAsset_close(asset); } else { do { // read rrom other path than user set it //CCLOG("GETTING FILE ABSOLUTE DATA: %s", filename); const char* mode = nullptr; if (forString) mode = "rt"; else mode = "rb"; FILE *fp = fopen(fullPath.c_str(), mode); CC_BREAK_IF(!fp); long fileSize; fseek(fp,0,SEEK_END); fileSize = ftell(fp); fseek(fp,0,SEEK_SET); if (forString) { data = (unsigned char*) malloc(fileSize + 1); data[fileSize] = '\0'; } else { data = (unsigned char*) malloc(fileSize); } fileSize = fread(data,sizeof(unsigned char), fileSize,fp); fclose(fp); size = fileSize; } while (0); } std::string ret; if (data == nullptr || size == 0) { std::string msg = "Get data from file("; msg.append(filename).append(") failed!"); CCLOG("%s", msg.c_str()); return ""; } else { // ret.fastSet(data, size); std::string ret((char*)data, (int)size); CCLOG("file data:%s", data); return ret; } // return ret; } string FileUtilsAndroid::getWritablePath() const { // Fix for Nexus 10 (Android 4.2 multi-user environment) // the path is retrieved through Java Context.getCacheDir() method string dir(""); string tmp = getFileDirectoryJNI(); if (tmp.length() > 0) { dir.append(tmp).append("/"); return dir; } else { return ""; } } NS_CC_END
[ "weihua@weihuacuideMac-mini.local" ]
weihua@weihuacuideMac-mini.local
f1409e22bea3c7f76058e8d2ad666776a6c55e36
3cd1fa9c7282a351975bf4bc57e2feb2017cd795
/data_structures/lab-5/lab_5.cpp
a151963fc96017afd47148529bf94cedfc16a16e
[]
no_license
ReznikovRoman/mirea-hw
f1ce52a4a6dca977c072cc7d2e19bc2376fda1ce
c4cdc8bc5f9ed8fb71e336da58e68e056da07e2b
refs/heads/master
2023-05-08T09:45:27.979411
2021-06-02T17:40:10
2021-06-02T17:40:10
292,531,575
0
0
null
null
null
null
UTF-8
C++
false
false
3,623
cpp
#include <string> #include <iostream> #include <stack> using namespace std; // Задание 1 // Получаем приоритет операторов int getOperatorsPrecedence(char c) { if (c == '^') return 3; else if (c == '*' || c == '/') return 2; else if (c == '+' || c == '-') return 1; else return -1; } // Конвертируем инфиксную форму в постфиксную string infixToPostfix(string s) { stack<char> operationsStack; string result; for (int i = 0; i < s.length(); i++) { char c = s[i]; // Добавляем операнды к результату if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')) { result += c; } // "Обработка скобок" else if (c == '(') operationsStack.push('('); else if (c == ')') { while (!operationsStack.empty() && operationsStack.top() != '(') { char temp = operationsStack.top(); operationsStack.pop(); result += temp; } operationsStack.pop(); } else { while (!operationsStack.empty() && getOperatorsPrecedence(s[i]) < getOperatorsPrecedence(operationsStack.top())) { char temp = operationsStack.top(); operationsStack.pop(); result += temp; } operationsStack.push(c); } } // Убираем оставшиеся элементы из стэка while (!operationsStack.empty()) { char temp = operationsStack.top(); operationsStack.pop(); result += temp; } return result; } // Задание - 2 (стек реализован с помощью списка) struct StackNode { int data; StackNode *next; }; StackNode *newNode(int data) { StackNode *stackNode = new StackNode(); stackNode->data = data; stackNode->next = NULL; return stackNode; } // 2 - "Пуст ли стек" int isEmpty(StackNode *root) { return !root; } // 2 - "Воткнуть элемент в стек" void push(StackNode **root, int data) { StackNode *stackNode = newNode(data); stackNode->next = *root; *root = stackNode; cout << data << " pushed to stack\n"; } // 2 - "Вытолкнуть элемент из стек" int pop(StackNode **root) { if (isEmpty(*root)) return INT_MIN; StackNode *temp = *root; *root = (*root)->next; int popped = temp->data; free(temp); return popped; } // 2 - "Вернуть значение вершины стека" int peek(StackNode *root) { if (isEmpty(root)) return INT_MIN; return root->data; } void task1() { string exp = "((a+b)*c)"; cout << infixToPostfix(exp) << endl; // ab + c* } void task2() { StackNode *root = NULL; push(&root, 1); push(&root, 2); push(&root, 3); cout << pop(&root) << " has been popped from stack\n"; cout << "Top element is " << peek(root) << endl; cout << "Elements in stack : "; while (!isEmpty(root)) { // Выводим значение "верхнего" элемента cout << peek(root) << " "; // Удаляем значение "верхнего" элемента pop(&root); } } int main() { task1(); cout << endl; task2(); cout << endl; return 0; }
[ "romanreznikov2002@yandex.ru" ]
romanreznikov2002@yandex.ru
5fe190846fcc2b626f587cabaf931a1942c226d6
b37c75b4e587211cd463176ee46e5b4268e96683
/BinaryTree/InvertBinaryTree.cpp
4627e08e7f9065376af3b0e6ad29b696e41efffe
[]
no_license
tangziyi001/LeetCode
0171044b472658f1bb4ff36cf939522d43ae24ae
a51640a282f60696d2627283684b563af6d584bc
refs/heads/master
2021-06-12T19:53:18.100244
2017-04-05T00:09:42
2017-04-05T00:09:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
477
cpp
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: void invert(TreeNode* now){ if(now == NULL) return; invert(now->left); invert(now->right); swap(now->left, now->right); } TreeNode* invertTree(TreeNode* root) { invert(root); return root; } };
[ "tangziyi001@gmail.com" ]
tangziyi001@gmail.com
faf69ce454a6653405b4cd3c8ea089a65f38871f
a6b5b78fe6f83a92231337e1cdd9ac20bc10d478
/asio/j.cc
5a84bd66c2609f46b23d83dca17c8f1415a477a4
[ "CC0-1.0" ]
permissive
guoxiaoyong/simple-useful
faf33b03f3772f78bbfd5e8050244ac365d90713
63f483250cc5e96ef112aac7499ab9e3a35572a8
refs/heads/master
2023-03-09T11:51:56.168743
2020-06-13T23:14:07
2020-06-13T23:14:07
43,603,113
0
0
CC0-1.0
2023-03-01T12:30:26
2015-10-03T15:12:43
Jupyter Notebook
UTF-8
C++
false
false
1,459
cc
// // server.cpp // ~~~~~~~~~~ // // Copyright (c) 2003-2013 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) // #include <ctime> #include <iostream> #include <string> #include <boost/array.hpp> #include <boost/asio.hpp> using boost::asio::ip::udp; std::string make_daytime_string() { using namespace std; // For time_t, time and ctime; time_t now = time(0); return ctime(&now); } int main() { try { boost::asio::io_service io_service; udp::socket socket(io_service, udp::endpoint(udp::v4(), 13)); for (;;) { boost::array<char, 1> recv_buf; udp::endpoint remote_endpoint; boost::system::error_code error; socket.receive_from(boost::asio::buffer(recv_buf), remote_endpoint, 0, error); if (error && error != boost::asio::error::message_size) throw boost::system::system_error(error); std::string message = make_daytime_string(); boost::system::error_code ignored_error; socket.send_to(boost::asio::buffer(message), remote_endpoint, 0, ignored_error); } } catch (std::exception& e) { std::cerr << e.what() << std::endl; } return 0; }
[ "guo.xiaoyong@gmail.com" ]
guo.xiaoyong@gmail.com
701e70c051151b6e5638ad0de7d1929b37d44801
5f9cff6db34ebfa86a3794eb491b0e0f0f8d53c3
/src/qt/guiutil.cpp
00128e2e2bd3b0015de793745554624287be2035
[ "MIT" ]
permissive
selfdirectedcoin/selfdirectedcoin
7d788a20c5207630f2bb9ed8a3ff78602e113274
75524be2848e1d508908c393c9f306fb0d9979e5
refs/heads/master
2021-05-12T19:18:49.694630
2018-01-11T13:43:03
2018-01-11T13:43:03
117,089,400
0
0
null
null
null
null
UTF-8
C++
false
false
16,554
cpp
// Copyright (c) 2011-2014 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <QApplication> #include "guiutil.h" #include "bitcoinaddressvalidator.h" #include "walletmodel.h" #include "bitcoinunits.h" #include "util.h" #include "init.h" #include <QDateTime> #include <QDoubleValidator> #include <QFont> #include <QLineEdit> #if QT_VERSION >= 0x050000 #include <QUrlQuery> #else #include <QUrl> #endif #include <QTextDocument> // for Qt::mightBeRichText #include <QAbstractItemView> #include <QClipboard> #include <QFileDialog> #include <QDesktopServices> #include <QThread> #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> #ifdef WIN32 #ifdef _WIN32_WINNT #undef _WIN32_WINNT #endif #define _WIN32_WINNT 0x0501 #ifdef _WIN32_IE #undef _WIN32_IE #endif #define _WIN32_IE 0x0501 #define WIN32_LEAN_AND_MEAN 1 #ifndef NOMINMAX #define NOMINMAX #endif #include "shlwapi.h" #include "shlobj.h" #include "shellapi.h" #endif namespace GUIUtil { QString dateTimeStr(const QDateTime &date) { return date.date().toString(Qt::SystemLocaleShortDate) + QString(" ") + date.toString("hh:mm"); } QString dateTimeStr(qint64 nTime) { return dateTimeStr(QDateTime::fromTime_t((qint32)nTime)); } QFont bitcoinAddressFont() { QFont font("Monospace"); font.setStyleHint(QFont::TypeWriter); return font; } void setupAddressWidget(QLineEdit *widget, QWidget *parent) { widget->setMaxLength(BitcoinAddressValidator::MaxAddressLength); widget->setValidator(new BitcoinAddressValidator(parent)); widget->setFont(bitcoinAddressFont()); } void setupAmountWidget(QLineEdit *widget, QWidget *parent) { QDoubleValidator *amountValidator = new QDoubleValidator(parent); amountValidator->setDecimals(8); amountValidator->setBottom(0.0); widget->setValidator(amountValidator); widget->setAlignment(Qt::AlignRight|Qt::AlignVCenter); } bool parseBitcoinURI(const QUrl &uri, SendCoinsRecipient *out) { // return if URI is not valid or is no bitcoin URI if(!uri.isValid() || uri.scheme() != QString("SelfDirectedCoin")) return false; SendCoinsRecipient rv; rv.address = uri.path(); rv.amount = 0; #if QT_VERSION < 0x050000 QList<QPair<QString, QString> > items = uri.queryItems(); #else QUrlQuery uriQuery(uri); QList<QPair<QString, QString> > items = uriQuery.queryItems(); #endif for (QList<QPair<QString, QString> >::iterator i = items.begin(); i != items.end(); i++) { bool fShouldReturnFalse = false; if (i->first.startsWith("req-")) { i->first.remove(0, 4); fShouldReturnFalse = true; } if (i->first == "label") { rv.label = i->second; fShouldReturnFalse = false; } else if (i->first == "amount") { if(!i->second.isEmpty()) { if(!BitcoinUnits::parse(BitcoinUnits::BTC, i->second, &rv.amount)) { return false; } } fShouldReturnFalse = false; } if (fShouldReturnFalse) return false; } if(out) { *out = rv; } return true; } bool parseBitcoinURI(QString uri, SendCoinsRecipient *out) { // Convert bitcoin:// to bitcoin: // // Cannot handle this later, because bitcoin:// will cause Qt to see the part after // as host, // which will lower-case it (and thus invalidate the address). if(uri.startsWith("SelfDirectedCoin://")) { uri.replace(0, 11, "SelfDirectedCoin:"); } QUrl uriInstance(uri); return parseBitcoinURI(uriInstance, out); } QString HtmlEscape(const QString& str, bool fMultiLine) { #if QT_VERSION < 0x050000 QString escaped = Qt::escape(str); #else QString escaped = str.toHtmlEscaped(); #endif if(fMultiLine) { escaped = escaped.replace("\n", "<br>\n"); } return escaped; } QString HtmlEscape(const std::string& str, bool fMultiLine) { return HtmlEscape(QString::fromStdString(str), fMultiLine); } void copyEntryData(QAbstractItemView *view, int column, int role) { if(!view || !view->selectionModel()) return; QModelIndexList selection = view->selectionModel()->selectedRows(column); if(!selection.isEmpty()) { // Copy first item (global clipboard) QApplication::clipboard()->setText(selection.at(0).data(role).toString(), QClipboard::Clipboard); // Copy first item (global mouse selection for e.g. X11 - NOP on Windows) QApplication::clipboard()->setText(selection.at(0).data(role).toString(), QClipboard::Selection); } } void setClipboard(const QString& str) { QApplication::clipboard()->setText(str, QClipboard::Clipboard); QApplication::clipboard()->setText(str, QClipboard::Selection); } QString getSaveFileName(QWidget *parent, const QString &caption, const QString &dir, const QString &filter, QString *selectedSuffixOut) { QString selectedFilter; QString myDir; if(dir.isEmpty()) // Default to user documents location { #if QT_VERSION < 0x050000 myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation); #else myDir = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation); #endif } else { myDir = dir; } QString result = QFileDialog::getSaveFileName(parent, caption, myDir, filter, &selectedFilter); /* Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...) */ QRegExp filter_re(".* \\(\\*\\.(.*)[ \\)]"); QString selectedSuffix; if(filter_re.exactMatch(selectedFilter)) { selectedSuffix = filter_re.cap(1); } /* Add suffix if needed */ QFileInfo info(result); if(!result.isEmpty()) { if(info.suffix().isEmpty() && !selectedSuffix.isEmpty()) { /* No suffix specified, add selected suffix */ if(!result.endsWith(".")) result.append("."); result.append(selectedSuffix); } } /* Return selected suffix if asked to */ if(selectedSuffixOut) { *selectedSuffixOut = selectedSuffix; } return result; } Qt::ConnectionType blockingGUIThreadConnection() { if(QThread::currentThread() != qApp->thread()) { return Qt::BlockingQueuedConnection; } else { return Qt::DirectConnection; } } bool checkPoint(const QPoint &p, const QWidget *w) { QWidget *atW = QApplication::widgetAt(w->mapToGlobal(p)); if (!atW) return false; return atW->topLevelWidget() == w; } bool isObscured(QWidget *w) { return !(checkPoint(QPoint(0, 0), w) && checkPoint(QPoint(w->width() - 1, 0), w) && checkPoint(QPoint(0, w->height() - 1), w) && checkPoint(QPoint(w->width() - 1, w->height() - 1), w) && checkPoint(QPoint(w->width() / 2, w->height() / 2), w)); } void openDebugLogfile() { boost::filesystem::path pathDebug = GetDataDir() / "debug.log"; /* Open debug.log with the associated application */ if (boost::filesystem::exists(pathDebug)) QDesktopServices::openUrl(QUrl::fromLocalFile(QString::fromStdString(pathDebug.string()))); } ToolTipToRichTextFilter::ToolTipToRichTextFilter(int size_threshold, QObject *parent) : QObject(parent), size_threshold(size_threshold) { } bool ToolTipToRichTextFilter::eventFilter(QObject *obj, QEvent *evt) { if(evt->type() == QEvent::ToolTipChange) { QWidget *widget = static_cast<QWidget*>(obj); QString tooltip = widget->toolTip(); if(tooltip.size() > size_threshold && !tooltip.startsWith("<qt") && !Qt::mightBeRichText(tooltip)) { // Envelop with <qt></qt> to make sure Qt detects this as rich text // Escape the current message as HTML and replace \n by <br> tooltip = "<qt>" + HtmlEscape(tooltip, true) + "</qt>"; widget->setToolTip(tooltip); return true; } } return QObject::eventFilter(obj, evt); } #ifdef WIN32 boost::filesystem::path static StartupShortcutPath() { return GetSpecialFolderPath(CSIDL_STARTUP) / "SelfDirectedCoin.lnk"; } bool GetStartOnSystemStartup() { // check for Bitcoin.lnk return boost::filesystem::exists(StartupShortcutPath()); } bool SetStartOnSystemStartup(bool fAutoStart) { // If the shortcut exists already, remove it for updating boost::filesystem::remove(StartupShortcutPath()); if (fAutoStart) { CoInitialize(NULL); // Get a pointer to the IShellLink interface. IShellLink* psl = NULL; HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, reinterpret_cast<void**>(&psl)); if (SUCCEEDED(hres)) { // Get the current executable path TCHAR pszExePath[MAX_PATH]; GetModuleFileName(NULL, pszExePath, sizeof(pszExePath)); TCHAR pszArgs[5] = TEXT("-min"); // Set the path to the shortcut target psl->SetPath(pszExePath); PathRemoveFileSpec(pszExePath); psl->SetWorkingDirectory(pszExePath); psl->SetShowCmd(SW_SHOWMINNOACTIVE); psl->SetArguments(pszArgs); // Query IShellLink for the IPersistFile interface for // saving the shortcut in persistent storage. IPersistFile* ppf = NULL; hres = psl->QueryInterface(IID_IPersistFile, reinterpret_cast<void**>(&ppf)); if (SUCCEEDED(hres)) { WCHAR pwsz[MAX_PATH]; // Ensure that the string is ANSI. MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().string().c_str(), -1, pwsz, MAX_PATH); // Save the link by calling IPersistFile::Save. hres = ppf->Save(pwsz, TRUE); ppf->Release(); psl->Release(); CoUninitialize(); return true; } psl->Release(); } CoUninitialize(); return false; } return true; } #elif defined(LINUX) // Follow the Desktop Application Autostart Spec: // http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html boost::filesystem::path static GetAutostartDir() { namespace fs = boost::filesystem; char* pszConfigHome = getenv("XDG_CONFIG_HOME"); if (pszConfigHome) return fs::path(pszConfigHome) / "autostart"; char* pszHome = getenv("HOME"); if (pszHome) return fs::path(pszHome) / ".config" / "autostart"; return fs::path(); } boost::filesystem::path static GetAutostartFilePath() { return GetAutostartDir() / "SelfDirectedCoin.desktop"; } bool GetStartOnSystemStartup() { boost::filesystem::ifstream optionFile(GetAutostartFilePath()); if (!optionFile.good()) return false; // Scan through file for "Hidden=true": std::string line; while (!optionFile.eof()) { getline(optionFile, line); if (line.find("Hidden") != std::string::npos && line.find("true") != std::string::npos) return false; } optionFile.close(); return true; } bool SetStartOnSystemStartup(bool fAutoStart) { if (!fAutoStart) boost::filesystem::remove(GetAutostartFilePath()); else { char pszExePath[MAX_PATH+1]; memset(pszExePath, 0, sizeof(pszExePath)); if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath)-1) == -1) return false; boost::filesystem::create_directories(GetAutostartDir()); boost::filesystem::ofstream optionFile(GetAutostartFilePath(), std::ios_base::out|std::ios_base::trunc); if (!optionFile.good()) return false; // Write a bitcoin.desktop file to the autostart directory: optionFile << "[Desktop Entry]\n"; optionFile << "Type=Application\n"; optionFile << "Name=SelfDirectedCoin\n"; optionFile << "Exec=" << pszExePath << " -min\n"; optionFile << "Terminal=false\n"; optionFile << "Hidden=false\n"; optionFile.close(); } return true; } #elif defined(Q_OS_MAC) // based on: https://github.com/Mozketo/LaunchAtLoginController/blob/master/LaunchAtLoginController.m #include <CoreFoundation/CoreFoundation.h> #include <CoreServices/CoreServices.h> LSSharedFileListItemRef findStartupItemInList(LSSharedFileListRef list, CFURLRef findUrl); LSSharedFileListItemRef findStartupItemInList(LSSharedFileListRef list, CFURLRef findUrl) { // loop through the list of startup items and try to find the bitcoin app CFArrayRef listSnapshot = LSSharedFileListCopySnapshot(list, NULL); for(int i = 0; i < CFArrayGetCount(listSnapshot); i++) { LSSharedFileListItemRef item = (LSSharedFileListItemRef)CFArrayGetValueAtIndex(listSnapshot, i); UInt32 resolutionFlags = kLSSharedFileListNoUserInteraction | kLSSharedFileListDoNotMountVolumes; CFURLRef currentItemURL = NULL; LSSharedFileListItemResolve(item, resolutionFlags, &currentItemURL, NULL); if(currentItemURL && CFEqual(currentItemURL, findUrl)) { // found CFRelease(currentItemURL); return item; } if(currentItemURL) { CFRelease(currentItemURL); } } return NULL; } bool GetStartOnSystemStartup() { CFURLRef bitcoinAppUrl = CFBundleCopyBundleURL(CFBundleGetMainBundle()); LSSharedFileListRef loginItems = LSSharedFileListCreate(NULL, kLSSharedFileListSessionLoginItems, NULL); LSSharedFileListItemRef foundItem = findStartupItemInList(loginItems, bitcoinAppUrl); return !!foundItem; // return boolified object } bool SetStartOnSystemStartup(bool fAutoStart) { CFURLRef bitcoinAppUrl = CFBundleCopyBundleURL(CFBundleGetMainBundle()); LSSharedFileListRef loginItems = LSSharedFileListCreate(NULL, kLSSharedFileListSessionLoginItems, NULL); LSSharedFileListItemRef foundItem = findStartupItemInList(loginItems, bitcoinAppUrl); if(fAutoStart && !foundItem) { // add bitcoin app to startup item list LSSharedFileListInsertItemURL(loginItems, kLSSharedFileListItemBeforeFirst, NULL, NULL, bitcoinAppUrl, NULL, NULL); } else if(!fAutoStart && foundItem) { // remove item LSSharedFileListItemRemove(loginItems, foundItem); } return true; } #else bool GetStartOnSystemStartup() { return false; } bool SetStartOnSystemStartup(bool fAutoStart) { return false; } #endif HelpMessageBox::HelpMessageBox(QWidget *parent) : QMessageBox(parent) { header = tr("SelfDirectedCoin-Qt") + " " + tr("version") + " " + QString::fromStdString(FormatFullVersion()) + "\n\n" + tr("Usage:") + "\n" + " SelfDirectedCoin-qt [" + tr("command-line options") + "] " + "\n"; coreOptions = QString::fromStdString(HelpMessage()); uiOptions = tr("UI options") + ":\n" + " -lang=<lang> " + tr("Set language, for example \"de_DE\" (default: system locale)") + "\n" + " -min " + tr("Start minimized") + "\n" + " -splash " + tr("Show splash screen on startup (default: 1)") + "\n"; setWindowTitle(tr("SelfDirectedCoin-Qt")); setTextFormat(Qt::PlainText); // setMinimumWidth is ignored for QMessageBox so put in non-breaking spaces to make it wider. setText(header + QString(QChar(0x2003)).repeated(50)); setDetailedText(coreOptions + "\n" + uiOptions); } void HelpMessageBox::printToConsole() { // On other operating systems, the expected action is to print the message to the console. QString strUsage = header + "\n" + coreOptions + "\n" + uiOptions; fprintf(stdout, "%s", strUsage.toStdString().c_str()); } void HelpMessageBox::showOrPrint() { #if defined(WIN32) // On Windows, show a message box, as there is no stderr/stdout in windowed applications exec(); #else // On other operating systems, print help text to console printToConsole(); #endif } } // namespace GUIUtil
[ "peterburns89@gmail.com" ]
peterburns89@gmail.com
be8273c47a9cfb86b9055e871f6fdcfb33a526df
9fbff544471056f0816fa52d1bbf0c4db47c1f24
/template/tree/二叉树的遍历2.cpp
cd4f217c451f0e2c5497f99369b5fdd597ea9442
[]
no_license
theDreamBear/algorithmn
88d1159fb70e60b5a16bb64673d7383e20dc5fe5
c672d871848a7453ac3ddb8335b1e38d112626ee
refs/heads/master
2023-06-08T15:47:08.368054
2023-06-02T13:00:30
2023-06-02T13:00:30
172,293,806
0
0
null
null
null
null
UTF-8
C++
false
false
12,545
cpp
#include <iostream> #include <iterator> #include <queue> #include <stack> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution1 { public: bool isSymmetricHeler(TreeNode *left, TreeNode *right) { if (nullptr == left && nullptr == right) { return true; } if (nullptr == left || nullptr == right || left->val != right->val) { return false; } return isSymmetricHeler(left->left, right->right) && isSymmetricHeler(left->right, right->left); } bool isSymmetric(TreeNode *root) { // 这是一种很直白的前序 return isSymmetricHeler(root, root); } }; class Solution2 { public: bool isSymmetric(TreeNode *root) { if (nullptr == root) { return true; } stack<pair<TreeNode *, TreeNode *>> st; st.push(make_pair(root, root)); while (!st.empty()) { auto[lhs, rhs] = st.top(); st.pop(); if (nullptr == lhs && nullptr == rhs) { continue; } if (nullptr == lhs || nullptr == rhs || lhs->val != rhs->val) { return false; } st.push(make_pair(lhs->right, rhs->left)); st.push(make_pair(lhs->left, rhs->right)); } return true; } }; void postTraversal1(TreeNode *root) { if (nullptr == root) { return; } // 存储待访问节点 // 约定1、不能有空节点 stack<TreeNode *> st; TreeNode *cur = root; // 上一个访问的节点 TreeNode *pre = nullptr; while (cur || !st.empty()) { while (cur) { st.push(cur); cur = cur->left; } cur = st.top(); if (nullptr == cur->right || cur->right == pre) { cout << cur->val << "\t" << endl; st.pop(); pre = cur; cur = nullptr; } else { cur = cur->right; } } } void postTraversal3(TreeNode *root) { if (nullptr == root) { return; } // 存储待访问节点 // 约定1、不能有空节点 stack<TreeNode *> st; TreeNode* cur = root; TreeNode* preHandled = nullptr; while (cur || !st.empty()) { // cur 是未添加节点 while (cur) { st.push(cur); if (cur->left) { cur = cur->left; } else { break; } } if (nullptr == cur) { cur = st.top(); } if (!cur->right || cur->right == preHandled) { cout << cur->val << "\t"; preHandled = cur; st.pop(); cur = nullptr; } else { cur = cur->right; } } } void postTraversal4(TreeNode *root) { if (nullptr == root) { return; } // 存储待访问节点 // 约定1、不能有空节点 stack<TreeNode *> st; TreeNode* cur = root; TreeNode* preHandled = nullptr; while (cur) { st.push(cur); cur = cur->left; } while (!st.empty()) { // 至少第二次遇到 cur = st.top(); if (nullptr == cur->right || cur->right == preHandled) { cout << cur->val << "\t"; preHandled = cur; st.pop(); } else { cur = cur->right; while (cur) { st.push(cur); cur = cur->left; } } } } void postTraversal2(TreeNode *root) { if (nullptr == root) { return; } // 存储待访问节点 // 约定1、不能有空节点 stack<TreeNode *> st; TreeNode *pre = nullptr; TreeNode *cur = root; while (cur) { // 所有节点第一次访问 st.push(cur); cur = cur->left; } while (!st.empty()) { // 保证遇到的都是第二次,第三次访问的 cur = st.top(); // 第二次 或者第三次 if (nullptr == cur->right || cur->right == pre) { cout << cur->val << "\t"; pre = cur; st.pop(); continue; } cur = cur->right; while (cur) { // 所有节点第一次访问 st.push(cur); cur = cur->left; } } } bool postTraversal(TreeNode *root) { if (nullptr == root) { return true; } // 存储待访问节点 // 约定1、约定可以有空节点 TreeNode dummy{-1}; auto gen = [&dummy](TreeNode *node, TreeNode *TreeNode::*lhs, TreeNode *TreeNode::*rhs) { stack<TreeNode *> st; TreeNode *pre = nullptr; TreeNode *cur = node; while (cur) { st.push(cur); cur = cur->*lhs; } queue<TreeNode *> q; return [=, &dummy]() mutable -> TreeNode * { while (!st.empty()) { if (!q.empty()) { auto res = q.front(); q.pop(); return res; } // yield if (nullptr == cur) { cur = st.top(); q.push(nullptr); } if (nullptr == cur->*rhs) { q.push(nullptr); pre = cur; st.pop(); if (!st.empty()) { cur = st.top(); } // push q.push(pre); } else if (cur->*rhs && cur->*rhs == pre) { pre = cur; st.pop(); if (!st.empty()) { cur = st.top(); } // push q.push(pre); } cur = cur->*rhs; while (cur) { st.push(cur); cur = cur->*lhs; } } if (!q.empty()) { auto res = q.front(); q.pop(); return res; } return &dummy; }; }; auto gen1 = gen(root, &TreeNode::left, &TreeNode::right); auto gen2 = gen(root, &TreeNode::right, &TreeNode::left); for (;;) { auto l = gen1(); auto r = gen2(); if (nullptr == l && nullptr == r) { continue; } if (nullptr == l || nullptr == r) { return false; } if (&dummy == l && &dummy == r) { break; } if (&dummy == l || &dummy == r) { return false; } if (l->val != r->val) { return false; } } return true; } class Solution { public: bool isSymmetric(TreeNode *root) { if (nullptr == root) { return true; } // 存储待访问节点 // 约定1、约定可以有空节点 TreeNode dummy{-1}; auto gen = [&dummy](TreeNode *node, TreeNode *TreeNode::*lhs, TreeNode *TreeNode::*rhs) { stack<TreeNode *> st; queue<TreeNode *> q; TreeNode *pre = nullptr; TreeNode *cur = node; return [=, &dummy]() mutable -> TreeNode * { while (cur || !st.empty()) { while (cur) { st.push(cur); cur = cur->*lhs; if (nullptr == cur) { q.push(nullptr); } } cur = st.top(); if (nullptr == cur->*rhs || (cur->*rhs && cur->*rhs == pre)) { if (nullptr == cur->*rhs) { q.push(nullptr); } q.push(cur); st.pop(); pre = cur; cur = nullptr; continue; } else { cur = cur->*rhs; } if (!q.empty()) { auto res = q.front(); q.pop(); return res; } } if (!q.empty()) { auto res = q.front(); q.pop(); return res; } return &dummy; }; }; auto gen1 = gen(root->left, &TreeNode::left, &TreeNode::right); auto gen2 = gen(root->right, &TreeNode::right, &TreeNode::left); for (;;) { auto l = gen1(); auto r = gen2(); if (nullptr == l && nullptr == r) { continue; } if (nullptr == l || nullptr == r) { return false; } if (&dummy == l && &dummy == r) { break; } if (&dummy == l || &dummy == r) { return false; } if (l->val != r->val) { return false; } } return true; } }; // 1,2,2,3,4,4,3 // 关键需要发现边界 void bfs(TreeNode* root) { if (nullptr == root) { return; } queue<TreeNode*> q; q.push(root); q.push(nullptr); while (q.size() > 1) { auto node = q.front(); q.pop(); if (node) { cout << node->val << "\t"; if (node->left) { q.push(node->left); } if (node->right) { q.push(node->right); } } else { cout << endl; q.push(nullptr); } } } int main(int argc, char *argv[]) { TreeNode *root = new TreeNode(1); root->left = new TreeNode(2); root->right = new TreeNode(2); root->left->left = new TreeNode(3); root->left->right = new TreeNode(4); root->right->left = new TreeNode(4); root->right->right = new TreeNode(3); //cout << Solution{}.isSymmetric(root); postTraversal4(root); } #include <iostream> #include <iterator> #include <queue> #include <stack> #include <unordered_map> using namespace std; struct TreeNode { struct TreeNode *left, *right; int val; explicit TreeNode(int val) : val(val), left(left), right(right) { auto x = &TreeNode::left; } }; enum Order { PRE, IN, POST, }; vector<TreeNode *TreeNode::*> children = {&TreeNode::left, &TreeNode::right, nullptr}; void traversal(TreeNode *root, Order order) { if (nullptr == root) { return; } for (auto next: children) { if (next == children[order]) { cout << root->val << "\t"; } if (next == nullptr) { return; } traversal(root->*next, order); } } bool isNULL(const string &s) { return s == "null"; } TreeNode *makeNode(string value) { if (isNULL(value)) { return nullptr; } return new TreeNode(atoi(value.c_str())); } TreeNode *makeTree(const vector<std::string> &data) { if (data.empty()) { return NULL; } int cur_available_pos = 0; TreeNode *root = makeNode(data[cur_available_pos++]); assert(root != nullptr); queue<pair<TreeNode *, int>> q; q.push(make_pair(root, cur_available_pos)); cur_available_pos += 2; auto addChild = [&](TreeNode *node, int idx, TreeNode *TreeNode::* child) { if (idx >= data.size()) { return; } auto newNode = makeNode(data[idx]); node->*child = newNode; // for child's children if (nullptr != newNode) { q.push(make_pair(newNode, cur_available_pos)); cur_available_pos += 2; } }; while (!q.empty()) { int sz = q.size(); for (int i = 0; i < sz; i++) { auto[node, start] = q.front(); q.pop(); // start 必定是合法的 addChild(node, start, &TreeNode::left); addChild(node, start + 1, &TreeNode::right); } } return root; } int main(int argc, char *argv[]) { auto root = makeTree({"1", "2", "3", "null", "4", "null", "null", "5"}); traversal(root, PRE); cout << endl; traversal(root, IN); cout << endl; traversal(root, POST); cout << endl; }
[ "nichao@zuoyebang.com" ]
nichao@zuoyebang.com
aa4581b8d9dfbb67b507c4d7e76615c61b2123a4
48a73a0ba850ac2925118dd304baa8f7b2874582
/C++/source/HttpInterface/HttpInterfaceMethodWorker.cpp
692f5cb4e0708da0f4671701e36b4e267ca250d0
[ "Apache-2.0" ]
permissive
cxvisa/Wave
5e66dfbe32c85405bc2761c509ba8507ff66f8fe
1aca714933ff1df53d660f038c76ca3f2202bf4a
refs/heads/master
2021-05-03T15:00:49.991391
2018-03-31T23:06:40
2018-03-31T23:06:40
56,774,204
2
1
null
null
null
null
UTF-8
C++
false
false
1,123
cpp
/*************************************************************************** * Copyright (C) 2005-2011 Vidyasagara Guntaka * * All rights reserved. * * Author : Vidyasagara Reddy Guntaka * ***************************************************************************/ #include "HttpInterface/HttpInterfaceMethodWorker.h" #include "HttpInterface/HttpInterfaceReceiverObjectManager.h" namespace WaveNs { HttpInterfaceMethodWorker::HttpInterfaceMethodWorker (HttpInterfaceReceiverObjectManager* pHttpInterfaceReceiverObjectManager, const WaveHttpInterfaceMethod& waveHttpInterfaceMethod) : WaveWorker (pHttpInterfaceReceiverObjectManager), m_waveHttpInterfaceMethod (waveHttpInterfaceMethod) { pHttpInterfaceReceiverObjectManager->addHttpInterfaceMethodWorker (waveHttpInterfaceMethod, this); } HttpInterfaceMethodWorker::~HttpInterfaceMethodWorker() { } WaveHttpInterfaceMethod HttpInterfaceMethodWorker::getWaveHttpInterfaceMethod () const { return (m_waveHttpInterfaceMethod); } }
[ "sagar@wave.sagar.cisco.com" ]
sagar@wave.sagar.cisco.com
5277bb9e1686556c1da0c5c00fe0a54979a1d648
6d9133176e013e4145d8ea785f6927b72ae678b7
/Cyborg/src/cNeck.cpp
c6b5dc4e6a56437e3315aef4f98f96ba9d772bd3
[]
no_license
Memaguer/OpenGL_Cyborg
cc2a18285718ea27e0c0035935329464df66551c
02ae38db99b02a641f42ac27dde8c099bbfef454
refs/heads/master
2021-05-03T11:14:49.619732
2018-02-07T01:44:05
2018-02-07T01:44:05
120,547,765
0
0
null
null
null
null
UTF-8
C++
false
false
536
cpp
// // cNeck.cpp // Cyborg // // Created by MBG on 2/5/18. // Copyright © 2018 MBG. All rights reserved. // #include "cNeck.hpp" Neck::Neck() { neck = new Part(1, 1, 1); head = new Head(); } Neck::~Neck() { delete neck; delete head; } void Neck::draw() { // ############## NECK ############# glTranslatef(0, 0.6, 0); glScalef(0.25, 0.3, 0.3); neck -> draw(); // ####### HEAD ####### glPushMatrix(); { head -> draw(); } glPopMatrix(); } void Neck:: update() { }
[ "gbarrientos@alabool.mx" ]
gbarrientos@alabool.mx
0582b1edaf1466093b64f9fbc5b5f33d68cf7469
ec0a5d5ddf5436ddeebc095341c95ffb4cc0c471
/core/utils/LinearInterpolator.h
64269c51417af31f8e05a7f9fcfbf684a161c690
[ "MIT" ]
permissive
egbaquela/CODeM-Toolkit
ca08e8c26fd8fab58da217e958aa71d708f20f57
c08f578bd54a5de9abd459d6f3f320db2991764a
refs/heads/master
2020-03-20T19:45:04.086811
2018-07-05T01:09:31
2018-07-05T01:09:31
137,651,950
0
0
null
2018-06-17T12:02:48
2018-06-17T12:02:47
null
UTF-8
C++
false
false
2,196
h
/**************************************************************************** ** ** The MIT License (MIT) ** ** Copyright (c) 2016 The University of Sheffield (www.sheffield.ac.uk) ** ** Permission is hereby granted, free of charge, to any person obtaining a copy ** of this software and associated documentation files (the "Software"), to deal ** in the Software without restriction, including without limitation the rights ** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ** copies of the Software, and to permit persons to whom the Software is ** furnished to do so, subject to the following conditions: ** ** The above copyright notice and this permission notice shall be included in all ** copies or substantial portions of the Software. ** ** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE ** SOFTWARE ** ****************************************************************************/ #ifndef LINEARINTERPOLATOR_H #define LINEARINTERPOLATOR_H #include <core/CODeMGlobal.h> #include <vector> namespace CODeM { namespace Utils { class LinearInterpolator { public: LinearInterpolator(std::vector<double> xv, std::vector<double> yv); ~LinearInterpolator(); double interpolate(double xq); std::vector<double> interpolateV(std::vector<double> xq); virtual void defineXY(std::vector<double> x, std::vector<double> y); bool isConfigured(); protected: double baseInterpolate(int j, double x); int locate(const double x); int hunt(const double x); virtual bool checkConfiguration(); int n; int mm; int jsav; int cor; int dj; bool m_isConfigured; std::vector<double> xx; std::vector<double> yy; }; } // namespace Utils } // namespace CODeM #endif // LINEARINTERPOLATOR_H
[ "s.salomon@sheffield.ac.uk" ]
s.salomon@sheffield.ac.uk
684d4be1089ea5604d37a640306928b25e10b2bd
03380a2cf46385b0d971e150078d992cd7840980
/Source/Diagnostics/OpenPMDHelpFunction.H
9db4b9fb19454554475ad39aa319c56b4cc1518f
[ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause-LBNL" ]
permissive
ECP-WarpX/WarpX
0cfc85ce306cc5d5caa3108e8e9aefe4fda44cd3
e052c6d1994e4edb66fc27763d72fcf08c3a112a
refs/heads/development
2023-08-19T07:50:12.539926
2023-08-17T20:01:41
2023-08-17T20:01:41
150,626,842
210
147
NOASSERTION
2023-09-13T23:38:13
2018-09-27T17:53:35
C++
UTF-8
C++
false
false
386
h
/* Copyright 2023 The WarpX Community * * This file is part of WarpX. * * Authors: Juliette Pech, Axel Huebl * License: BSD-3-Clause-LBNL */ #ifndef WARPX_OPENPMDHELPFUNCTION_H_ #define WARPX_OPENPMDHELPFUNCTION_H_ #ifdef WARPX_USE_OPENPMD # include <openPMD/openPMD.hpp> #endif #include <string> std::string WarpXOpenPMDFileType (); #endif // WARPX_OPENPMDHELPFUNCTION_H_
[ "noreply@github.com" ]
ECP-WarpX.noreply@github.com
164f6620e6df1402cb1b6512ed3e8d7a04cfbef3
2ea1df8ee5b919b3d076fa192bce2081340e0cce
/OOP_Lab_08/Strategy/Newspaper.cpp
2d0acbe555f76591e72398559c2f38b0c295428c
[]
no_license
nadiyafomenko/OOP
a8c6efdb635951bd65f7a3f6dcd4ca916bb5f42b
14ccc533c7d87d79175cb505329fec669ed4ad03
refs/heads/master
2021-04-10T20:39:34.812484
2020-06-15T16:28:44
2020-06-15T16:28:44
248,963,871
0
1
null
2020-03-21T13:39:06
2020-03-21T11:40:06
C++
UTF-8
C++
false
false
1,343
cpp
#include "Newspaper.h" #include "PrintedProducts.h" void Newspaper::Print(std::ostream& out) { out << "Newspaper table: " << std::endl << "Title:" << "\t\t\t\t" << GetTitle() << std::endl << "Author:" << "\t\t\t\t" << GetAuthorName() << std::endl << "Pages:" << "\t\t\t\t" << GetPages() << std::endl << "Page size:" << "\t\t\t" << GetPageWidth() << " x " << GetPageHeight() << std::endl << "Amount:" << "\t\t\t\t" << GetAmount() << std::endl << "Period:" << "\t\t\t\t" << GetPeriod() << std::endl; } Newspaper::Newspaper() : PrintedProducts() { this->Amount = 0; this->pageHeight = 0; this->pageWidth = 0; this->Period = 0; } Newspaper::Newspaper( const std::string AuthorName, const std::string title, const double pages, const int pageHeight, const int pageWidth, const int Amount, const int Period) : PrintedProducts(AuthorName, title, pages) { if (Amount < 0) { throw "wrong amount"; } this->pageHeight = pageHeight; this->pageWidth = pageWidth; this->Amount = Amount; this->Period = Period; } Newspaper::~Newspaper() { } const int Newspaper::GetAmount() const { return this->Amount; } const int Newspaper::GetPeriod() const { return this->Period; } const int Newspaper::GetPageHeight() const { return this->pageHeight; } const int Newspaper::GetPageWidth() const { return this->pageWidth; }
[ "47325620+nadiyafomenko@users.noreply.github.com" ]
47325620+nadiyafomenko@users.noreply.github.com
3bbbd5f278722dac8eff2e8d192736daa5643246
72392c0ff4ecd2cb024d7b59e3c9bcc036133e4e
/example3.cpp
8964e5483b10ea02a47c2b56761e5aa9836a61e2
[]
no_license
thomasphillips3/gists
931658b394ce400b8a825d77af6d08620a3e3494
48e3861bb1fb5a25d2f29efef83d634b57e64ae2
refs/heads/master
2020-04-05T13:05:24.047257
2017-07-25T13:01:24
2017-07-25T13:01:24
95,075,015
0
0
null
null
null
null
UTF-8
C++
false
false
418
cpp
// https://developers.google.com/edu/c++/getting-started // Example 3: What does this program output? // Time tables // Thomas Phillips #include <iostream> using namespace std; int main(void) { cout << " 1\t2\t3\t4\t5\t6\t7\t8\t9" << endl << "" << endl; for (int c = 1; c < 10; c++) { cout << c << "| "; for (int i = 1; i < 10; i++) { cout << i*c << '\t'; } cout << endl; } return 0; }
[ "thomasphillips3@gmail.com" ]
thomasphillips3@gmail.com
aee44828d6f764216813590d329151b71ced1cfa
006f035d65012b7c5af15d54716407a276a096a8
/dependencies/include/cgal/CGAL/Segment_Delaunay_graph_2/Segment_Delaunay_graph_2_impl.h
f16d7b5ab7435b930411414b7a6faf40b60979a8
[]
no_license
rosecodym/space-boundary-tool
4ce5b67fd96ec9b66f45aca60e0e69f4f8936e93
300db4084cd19b092bdf2e8432da065daeaa7c55
refs/heads/master
2020-12-24T06:51:32.828579
2016-08-12T16:13:51
2016-08-12T16:13:51
65,566,229
7
0
null
null
null
null
UTF-8
C++
false
false
97,667
h
// Copyright (c) 2003,2004,2005,2006 INRIA Sophia-Antipolis (France). // All rights reserved. // // This file is part of CGAL (www.cgal.org). // You can redistribute it and/or modify it under the terms of the GNU // General Public License as published by the Free Software Foundation, // either version 3 of the License, or (at your option) any later version. // // Licensees holding a valid commercial license may use this file in // accordance with the commercial license agreement provided with the software. // // This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE // WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. // // $URL: svn+ssh://scm.gforge.inria.fr/svn/cgal/branches/releases/CGAL-4.1-branch/Segment_Delaunay_graph_2/include/CGAL/Segment_Delaunay_graph_2/Segment_Delaunay_graph_2_impl.h $ // $Id: Segment_Delaunay_graph_2_impl.h 70787 2012-07-27 10:38:58Z sloriot $ // // // Author(s) : Menelaos Karavelas <mkaravel@iacm.forth.gr> // class implementation continued //================================= namespace CGAL { //==================================================================== //==================================================================== // CONSTRUCTORS //==================================================================== //==================================================================== // copy constructor template<class Gt, class ST, class D_S, class LTag> Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>:: Segment_Delaunay_graph_2(const Segment_Delaunay_graph_2& other) : DG(other.geom_traits()) { Segment_Delaunay_graph_2& non_const_other = const_cast<Segment_Delaunay_graph_2&>(other); copy(non_const_other); CGAL_postcondition( is_valid() ); } // assignment operator template<class Gt, class ST, class D_S, class LTag> typename Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>::Self& Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>:: operator=(const Self& other) { if ( this != &other ) { Segment_Delaunay_graph_2& non_const_other = const_cast<Segment_Delaunay_graph_2&>(other); copy(non_const_other); } return (*this); } //==================================================================== //==================================================================== // METHODS FOR INSERTION //==================================================================== //==================================================================== //-------------------------------------------------------------------- // insertion of first three sites //-------------------------------------------------------------------- template<class Gt, class ST, class D_S, class LTag> typename Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>::Vertex_handle Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>:: insert_first(const Storage_site_2& ss, const Point_2& ) { CGAL_precondition( number_of_vertices() == 0 ); Vertex_handle v = this->_tds.insert_second(); v->set_site(ss); return v; } template<class Gt, class ST, class D_S, class LTag> typename Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>::Vertex_handle Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>:: insert_second(const Storage_site_2& ss, const Point_2& p) { CGAL_precondition( number_of_vertices() == 1 ); // p0 is actually a point Site_2 p0 = finite_vertices_begin()->site(); // MK: change the equality test between points by the functor in // geometric traits Site_2 tp = Site_2::construct_site_2(p); if ( same_points(tp,p0) ) { // merge info of identical sites merge_info(finite_vertices_begin(), ss); return finite_vertices_begin(); } return create_vertex_dim_up(ss); } template<class Gt, class ST, class D_S, class LTag> typename Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>::Vertex_handle Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>:: insert_third(const Storage_site_2& ss, const Point_2& p) { Site_2 t = Site_2::construct_site_2(p); return insert_third(t, ss); } template<class Gt, class ST, class D_S, class LTag> typename Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>::Vertex_handle Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>:: insert_third(const Site_2& t, const Storage_site_2& ss) { CGAL_precondition( number_of_vertices() == 2 ); // p0 and p1 are actually points Vertex_handle v0 = finite_vertices_begin(); Vertex_handle v1 = ++finite_vertices_begin(); Site_2 t0 = v0->site(); Site_2 t1 = v1->site(); if ( same_points(t, t0) ) { // merge info of identical sites merge_info(v0, ss); return v0; } if ( same_points(t, t1) ) { // merge info of identical sites merge_info(v1, ss); return v1; } Vertex_handle v = create_vertex_dim_up(ss); Face_handle f(finite_faces_begin()); Site_2 s1 = f->vertex(0)->site(); Site_2 s2 = f->vertex(1)->site(); Site_2 s3 = f->vertex(2)->site(); Orientation o = geom_traits().orientation_2_object()(s1, s2, s3); if ( o != COLLINEAR ) { if ( o == RIGHT_TURN ) { f->reorient(); for (int i = 0; i < 3; i++) { f->neighbor(i)->reorient(); } } } else { typename Geom_traits::Compare_x_2 compare_x = geom_traits().compare_x_2_object(); Comparison_result xcmp12 = compare_x(s1, s2); if ( xcmp12 == SMALLER ) { // x1 < x2 Comparison_result xcmp23 = compare_x(s2, s3); if ( xcmp23 == SMALLER ) { // x2 < x3 flip(f, f->index(v1)); } else { Comparison_result xcmp31 = compare_x(s3, s1); if ( xcmp31 == SMALLER ) { // x3 < x1 flip(f, f->index(v0)); } else { // x1 < x3 < x2 flip(f, f->index(v)); } } } else if ( xcmp12 == LARGER ) { // x1 > x2 Comparison_result xcmp32 = compare_x(s3, s2); if ( xcmp32 == SMALLER ) { // x3 < x2 flip(f, f->index(v1)); } else { Comparison_result xcmp13 = compare_x(s1, s3); if ( xcmp13 == SMALLER ) { // x1 < x3 flip(f, f->index(v0)); } else { // x2 < x3 < x1 flip(f, f->index(v)); } } } else { // x1 == x2 typename Geom_traits::Compare_y_2 compare_y = geom_traits().compare_y_2_object(); Comparison_result ycmp12 = compare_y(s1, s2); if ( ycmp12 == SMALLER ) { // y1 < y2 Comparison_result ycmp23 = compare_y(s2, s3); if ( ycmp23 == SMALLER ) { // y2 < y3 flip(f, f->index(v1)); } else { Comparison_result ycmp31 = compare_y(s3, s1); if ( ycmp31 == SMALLER ) { // y3 < y1 flip(f, f->index(v0)); } else { // y1 < y3 < y2 flip(f, f->index(v)); } } } else if ( ycmp12 == LARGER ) { // y1 > y2 Comparison_result ycmp32 = compare_y(s3, s2); if ( ycmp32 == SMALLER ) { // y3 < y2 flip(f, f->index(v1)); } else { Comparison_result ycmp13 = compare_y(s1, s3); if ( ycmp13 == SMALLER ) { // y1 < y3 flip(f, f->index(v0)); } else { // y2 < y3 < y1 flip(f, f->index(v)); } } } else { // this line should never have been reached CGAL_error(); } } } return v; } template<class Gt, class ST, class D_S, class LTag> typename Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>::Vertex_handle Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>:: insert_third(const Storage_site_2& ss, Vertex_handle , Vertex_handle ) { CGAL_precondition( number_of_vertices() == 2 ); // this can only be the case if the first site is a segment CGAL_precondition( dimension() == 1 ); Vertex_handle v = create_vertex_dim_up(ss); Face_circulator fc = incident_faces(v); while ( true ) { Face_handle f(fc); if ( !is_infinite(f) ) { flip(f, f->index(v)); break; } ++fc; } return v; } //-------------------------------------------------------------------- // insertion of a point //-------------------------------------------------------------------- template<class Gt, class ST, class D_S, class LTag> typename Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>::Vertex_handle Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>:: insert_point(const Storage_site_2& ss, const Point_2& p, Vertex_handle vnear) { size_type n = number_of_vertices(); if ( n == 0 ) { return insert_first(ss, p); } else if ( n == 1 ) { return insert_second(ss, p); } else if ( n == 2 ) { return insert_third(ss, p); } Site_2 t = Site_2::construct_site_2(p); return insert_point(ss, t, vnear); } template<class Gt, class ST, class D_S, class LTag> typename Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>::Vertex_handle Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>:: insert_point(const Storage_site_2& ss, const Site_2& t, Vertex_handle vnear) { CGAL_precondition( t.is_point() ); CGAL_assertion( number_of_vertices() > 2 ); //********************************************************************* //********************************************************************* //********************************************************************* //********************************************************************* //********************************************************************* //********************************************************************* //********************************************************************* //********************************************************************* //********************************************************************* //********************************************************************* //********************************************************************* // MK::ERROR: I need to write a insert_point_no_search method that // does not search for the nearest neighbor; this should be used by // insert_point. Below the first version of the code is correct. The // second is what the insert_point method should do before calling // insert_point_no_search. // first find the nearest neighbor #if 1 Vertex_handle vnearest = nearest_neighbor( t, vnear ); #else Vertex_handle vnearest; if ( vnear == Vertex_handle() ) { vnearest = nearest_neighbor( t, vnear ); } else { vnearest = vnear; } #endif //********************************************************************* //********************************************************************* //********************************************************************* //********************************************************************* //********************************************************************* //********************************************************************* //********************************************************************* //********************************************************************* //********************************************************************* //********************************************************************* //********************************************************************* // check is the point has already been inserted or lies on // a segment already inserted Arrangement_type at_res = arrangement_type(t, vnearest); if ( vnearest->is_point() ) { if ( at_res == AT2::IDENTICAL ) { // merge info of identical sites merge_info(vnearest, ss); return vnearest; } } else { CGAL_assertion( vnearest->is_segment() ); CGAL_assertion( at_res != AT2::TOUCH_1 ); CGAL_assertion( at_res != AT2::TOUCH_2 ); CGAL_assertion( at_res == AT2::DISJOINT || at_res == AT2::INTERIOR ); if ( at_res == AT2::INTERIOR ) { CGAL_assertion( t.is_input() ); Vertex_triple vt = insert_exact_point_on_segment(ss, t, vnearest); return vt.first; } else { // the point to be inserted does not belong to the interior of a // segment CGAL_assertion( at_res == AT2::DISJOINT ); } } return insert_point2(ss, t, vnearest); } template<class Gt, class ST, class D_S, class LTag> typename Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>::Vertex_handle Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>:: insert_point2(const Storage_site_2& ss, const Site_2& t, Vertex_handle vnearest) { CGAL_precondition( t.is_point() ); CGAL_assertion( number_of_vertices() > 2 ); CGAL_expensive_precondition ( nearest_neighbor(t, vnearest) == vnearest ); // find the first conflict #if !defined(CGAL_NO_ASSERTIONS) && !defined(NDEBUG) // verify that there are no intersections... Vertex_circulator vc = incident_vertices(vnearest); Vertex_circulator vc_start = vc; do { Vertex_handle vv(vc); Arrangement_type at_res = arrangement_type(t, vv); CGAL_assertion( at_res == AT2::DISJOINT ); ++vc; } while ( vc != vc_start ); #endif // first look for conflict with vertex Face_circulator fc_start = incident_faces(vnearest); Face_circulator fc = fc_start; Face_handle start_f; Sign s; #ifndef CGAL_SDG_NO_FACE_MAP std::map<Face_handle,Sign> sign_map; #endif do { Face_handle f(fc); s = incircle(f, t); #ifdef CGAL_SDG_NO_FACE_MAP f->tds_data().set_incircle_sign(s); #else sign_map[f] = s; #endif if ( s == NEGATIVE ) { start_f = f; break; } ++fc; } while ( fc != fc_start ); // we are not in conflict with a Voronoi vertex, so we have to // be in conflict with the interior of a Voronoi edge if ( s != NEGATIVE ) { Edge_circulator ec_start = incident_edges(vnearest); Edge_circulator ec = ec_start; bool interior_in_conflict(false); Edge e; do { e = *ec; #ifdef CGAL_SDG_NO_FACE_MAP Sign s1 = e.first->tds_data().incircle_sign(); Sign s2 = e.first->neighbor(e.second)->tds_data().incircle_sign(); #else Sign s1 = sign_map[e.first]; Sign s2 = sign_map[e.first->neighbor(e.second)]; #endif if ( s1 == s2 ) { interior_in_conflict = edge_interior(e, t, s1); } else { // It seems that there was a problem here when one of the // signs was positive and the other zero. In this case we // still check pretending that both signs where positive interior_in_conflict = edge_interior(e, t, POSITIVE); } if ( interior_in_conflict ) { break; } ++ec; } while ( ec != ec_start ); #ifndef CGAL_SDG_NO_FACE_MAP sign_map.clear(); #endif CGAL_assertion( interior_in_conflict ); return insert_degree_2(e, ss); } // we are in conflict with a Voronoi vertex; start from that and // find the entire conflict region and then repair the diagram List l; #ifndef CGAL_SDG_NO_FACE_MAP Face_map fm; #endif Triple<bool, Vertex_handle, Arrangement_type> vcross(false, Vertex_handle(), AT2::DISJOINT); // MK:: NEED TO WRITE A FUNCTION CALLED find_conflict_region WHICH // IS GIVEN A STARTING FACE, A LIST, A FACE MAP, A VERTEX MAP AND A // LIST OF FLIPPED EDGES AND WHAT IS DOES IS INITIALIZE THE CONFLICT // REGION AND EXPANDS THE CONFLICT REGION. initialize_conflict_region(start_f, l); #ifdef CGAL_SDG_NO_FACE_MAP expand_conflict_region(start_f, t, ss, l, vcross); #else expand_conflict_region(start_f, t, ss, l, fm, sign_map, vcross); #endif CGAL_assertion( !vcross.first ); Vertex_handle v = create_vertex(ss); #ifdef CGAL_SDG_NO_FACE_MAP retriangulate_conflict_region(v, l); #else retriangulate_conflict_region(v, l, fm); #endif return v; } //-------------------------------------------------------------------- // insertion of a point that lies on a segment //-------------------------------------------------------------------- template<class Gt, class ST, class D_S, class LTag> typename Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>::Face_pair Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>:: find_faces_to_split(const Vertex_handle& v, const Site_2& t) const { CGAL_precondition( v->is_segment() ); #ifndef CGAL_NO_ASSERTIONS { // count number of adjacent infinite faces Face_circulator fc = incident_faces(v); Face_circulator fc_start = fc; int n_inf = 0; do { if ( is_infinite(fc) ) { n_inf++; } fc++; } while ( fc != fc_start ); CGAL_assertion( n_inf == 0 || n_inf == 2 || n_inf == 4 ); } #endif Face_circulator fc1 = incident_faces(v); Face_circulator fc2 = fc1; ++fc2; Face_circulator fc_start = fc1; Face_handle f1, f2; bool found_f1 = false, found_f2 = false; Site_2 sitev_supp = v->site().supporting_site(); do { Face_handle ff1(fc1), ff2(fc2); Oriented_side os1, os2; if ( is_infinite(ff1) ) { int id_v = ff1->index(v); int cw_v = this->cw( id_v ); int ccw_v = this->ccw( id_v ); Site_2 sv_ep; if ( is_infinite( ff1->vertex(cw_v) ) ) { CGAL_assertion( !is_infinite( ff1->vertex(ccw_v) ) ); CGAL_assertion( ff1->vertex(ccw_v)->site().is_point() ); sv_ep = ff1->vertex(ccw_v)->site(); } else { CGAL_assertion( !is_infinite( ff1->vertex( cw_v) ) ); CGAL_assertion( ff1->vertex( cw_v)->site().is_point() ); sv_ep = ff1->vertex( cw_v)->site(); } os1 = oriented_side(sv_ep, sitev_supp, t); } else { os1 = oriented_side(fc1->vertex(0)->site(), fc1->vertex(1)->site(), fc1->vertex(2)->site(), sitev_supp, t); } if ( is_infinite(ff2) ) { int id_v = ff2->index(v); int cw_v = this->cw( id_v ); int ccw_v = this->ccw( id_v ); Site_2 sv_ep; if ( is_infinite( ff2->vertex(cw_v) ) ) { CGAL_assertion( !is_infinite( ff2->vertex(ccw_v) ) ); CGAL_assertion( ff2->vertex(ccw_v)->site().is_point() ); sv_ep = ff2->vertex(ccw_v)->site(); } else { CGAL_assertion( !is_infinite( ff2->vertex( cw_v) ) ); CGAL_assertion( ff2->vertex( cw_v)->site().is_point() ); sv_ep = ff2->vertex( cw_v)->site(); } os2 = oriented_side(sv_ep, sitev_supp, t); } else { os2 = oriented_side(fc2->vertex(0)->site(), fc2->vertex(1)->site(), fc2->vertex(2)->site(), sitev_supp, t); } if ( !found_f1 && os1 != ON_POSITIVE_SIDE && os2 == ON_POSITIVE_SIDE ) { f1 = ff2; found_f1 = true; } if ( !found_f2 && os1 == ON_POSITIVE_SIDE && os2 != ON_POSITIVE_SIDE ) { f2 = ff2; found_f2 = true; } if ( found_f1 && found_f2 ) { break; } ++fc1, ++fc2; } while ( fc_start != fc1 ); CGAL_assertion( found_f1 && found_f2 ); CGAL_assertion( f1 != f2 ); return Face_pair(f1, f2); } template<class Gt, class ST, class D_S, class LTag> typename Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>::Vertex_triple Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>:: insert_exact_point_on_segment(const Storage_site_2& ss, const Site_2& t, Vertex_handle v) { // splits the segment site v->site() in two and inserts represented by t // on return the three vertices are, respectively, the vertex // corresponding to t and the two subsegments of v->site() CGAL_assertion( t.is_point() ); CGAL_assertion( t.is_input() ); Storage_site_2 ssitev = v->storage_site(); CGAL_assertion( ssitev.is_segment() ); Face_pair fpair = find_faces_to_split(v, t); boost::tuples::tuple<Vertex_handle,Vertex_handle,Face_handle,Face_handle> qq = this->_tds.split_vertex(v, fpair.first, fpair.second); // now I need to update the sites for vertices v1 and v2 Vertex_handle v1 = boost::tuples::get<0>(qq); //qq.first; Storage_site_2 ssv1 = split_storage_site(ssitev, ss, true); v1->set_site( ssv1 ); Vertex_handle v2 = boost::tuples::get<1>(qq); //qq.second; Storage_site_2 ssv2 = split_storage_site(ssitev, ss, false); v2->set_site( ssv2 ); Face_handle qqf = boost::tuples::get<2>(qq); //qq.third; Vertex_handle vsx = this->_tds.insert_in_edge(qqf, cw(qqf->index(v1))); vsx->set_site(ss); // merge info of point and segment; the point lies on the segment merge_info(vsx, ssitev); return Vertex_triple(vsx, v1, v2); } template<class Gt, class ST, class D_S, class LTag> typename Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>::Vertex_triple Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>:: insert_point_on_segment(const Storage_site_2& ss, const Site_2& , Vertex_handle v, const Tag_true&) { // splits the segment site v->site() in two and inserts the point of // intersection of t and v->site() // on return the three vertices are, respectively, the point of // intersection and the two subsegments of v->site() Storage_site_2 ssitev = v->storage_site(); Storage_site_2 ssx = st_.construct_storage_site_2_object()(ss, ssitev); Site_2 sitev = ssitev.site(); Face_pair fpair = find_faces_to_split(v, ssx.site()); boost::tuples::tuple<Vertex_handle,Vertex_handle,Face_handle,Face_handle> qq = this->_tds.split_vertex(v, fpair.first, fpair.second); // now I need to update the sites for vertices v1 and v2 Vertex_handle v1 = boost::tuples::get<0>(qq); //qq.first; Vertex_handle v2 = boost::tuples::get<1>(qq); //qq.second; Storage_site_2 ssv1 = st_.construct_storage_site_2_object()(ssitev, ss, true); Storage_site_2 ssv2 = st_.construct_storage_site_2_object()(ssitev, ss, false); Site_2 sv1 = ssv1.site(); Site_2 sv2 = ssv2.site(); v1->set_site( ssv1 ); v2->set_site( ssv2 ); Face_handle qqf = boost::tuples::get<2>(qq); //qq.third; Vertex_handle vsx = this->_tds.insert_in_edge(qqf, cw(qqf->index(v1))); vsx->set_site(ssx); return Vertex_triple(vsx, v1, v2); } //-------------------------------------------------------------------- // insertion of a segment //-------------------------------------------------------------------- template<class Gt, class ST, class D_S, class LTag> typename Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>::Vertex_handle Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>:: insert_segment(const Storage_site_2& ss, const Site_2& t, Vertex_handle vnear) { CGAL_precondition( t.is_segment() ); CGAL_precondition( t.is_input() ); if ( is_degenerate_segment(t) ) { Storage_site_2 ss_src = ss.source_site(); convert_info(ss_src, ss, true); return insert_point(ss_src, t.source(), vnear); } Storage_site_2 ss_src = ss.source_site(); convert_info(ss_src, ss, true); Storage_site_2 ss_trg = ss.target_site(); convert_info(ss_trg, ss, false); Vertex_handle v0 = insert_point( ss_src, t.source(), vnear ); CGAL_assertion( is_valid() ); Vertex_handle v1 = insert_point( ss_trg, t.target(), v0 ); CGAL_assertion( is_valid() ); if ( number_of_vertices() == 2 ) { return insert_third(ss, v0, v1); } return insert_segment_interior(t, ss, v0); } template<class Gt, class ST, class D_S, class LTag> typename Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>::Vertex_handle Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>:: insert_segment_interior(const Site_2& t, const Storage_site_2& ss, Vertex_handle vnearest) { CGAL_precondition( t.is_segment() ); CGAL_precondition( number_of_vertices() > 2 ); CGAL_assertion( vnearest != Vertex_handle() ); // find the first conflict // first look if there are intersections... Vertex_circulator vc = incident_vertices(vnearest); Vertex_circulator vc_start = vc; do { Vertex_handle vv(vc); if ( is_infinite(vv) ) { vc++; continue; } Arrangement_type at_res = arrangement_type(t, vv); if ( vv->is_segment() ) { if ( at_res == AT2::DISJOINT || at_res == AT2::TOUCH_1 || at_res == AT2::TOUCH_2 || at_res == AT2::TOUCH_11 || at_res == AT2::TOUCH_12 || at_res == AT2::TOUCH_21 || at_res == AT2::TOUCH_22 ) { // do nothing } else if ( at_res == AT2::IDENTICAL ) { // merge info of identical items merge_info(vv, ss); return vv; } else if ( at_res == AT2::CROSSING ) { Intersections_tag itag; return insert_intersecting_segment(ss, t, vv, itag); } else if ( at_res == AT2::TOUCH_11_INTERIOR_1 ) { Vertex_handle vp = second_endpoint_of_segment(vv); Storage_site_2 ssvp = vp->storage_site(); Storage_site_2 sss = split_storage_site(ss, ssvp, false); Storage_site_2 sss1 = split_storage_site(ss, ssvp, true); // merge the info of the first (common) subsegment merge_info(vv, sss1); // merge the info of the (common) splitting endpoint merge_info(vp, ss); return insert_segment_interior(sss.site(), sss, vp); } else if ( at_res == AT2::TOUCH_12_INTERIOR_1 ) { Vertex_handle vp = first_endpoint_of_segment(vv); Storage_site_2 ssvp = vp->storage_site(); Storage_site_2 sss = split_storage_site(ss, ssvp, true); /*Storage_site_2 sss1 =*/ split_storage_site(ss, ssvp, false); // merge the info of the second (common) subsegment // merge_info(vv, sss); // merge the info of the (common) splitting endpoint merge_info(vp, ss); return insert_segment_interior(sss.site(), sss, vp); } else { // this should never be reached; the only possible values for // at_res are DISJOINT, CROSSING, TOUCH_11_INTERIOR_1 // and TOUCH_12_INTERIOR_1 CGAL_error(); } } else { CGAL_assertion( vv->is_point() ); if ( at_res == AT2::INTERIOR ) { Storage_site_2 ssvv = vv->storage_site(); if ( ssvv.is_input() ) { Storage_site_2 ss1 = split_storage_site(ss, ssvv, true); Storage_site_2 ss2 = split_storage_site(ss, ssvv, false); // merge the info of the splitting point and the segment merge_info(vv, ss); insert_segment_interior(ss1.site(), ss1, vv); return insert_segment_interior(ss2.site(), ss2, vv); } else { // this should never be reached; the only possible values for // at_res are DISJOINT and INTERIOR CGAL_error(); } } } ++vc; } while ( vc != vc_start ); // first look for conflict with vertex Face_circulator fc_start = incident_faces(vnearest); Face_circulator fc = fc_start; Face_handle start_f; Sign s; #ifndef CGAL_SDG_NO_FACE_MAP std::map<Face_handle,Sign> sign_map; #endif do { Face_handle f(fc); s = incircle(f, t); #ifdef CGAL_SDG_NO_FACE_MAP f->tds_data().set_incircle_sign(s); #else sign_map[f] = s; #endif if ( s == NEGATIVE ) { start_f = f; break; } ++fc; } while ( fc != fc_start ); // segments must have a conflict with at least one vertex CGAL_assertion( s == NEGATIVE ); // we are in conflict with a Voronoi vertex; start from that and // find the entire conflict region and then repair the diagram List l; #ifndef CGAL_SDG_NO_FACE_MAP Face_map fm; #endif Triple<bool, Vertex_handle, Arrangement_type> vcross(false, Vertex_handle(), AT2::DISJOINT); // MK:: NEED TO WRITE A FUNCTION CALLED find_conflict_region WHICH // IS GIVEN A STARTING FACE, A LIST, A FACE MAP, A VERTEX MAP AND A // LIST OF FLIPPED EDGES AND WHAT IS DOES IS INITIALIZE THE CONFLICT // REGION AND EXPANDS THE CONFLICT REGION. initialize_conflict_region(start_f, l); #ifdef CGAL_SDG_NO_FACE_MAP expand_conflict_region(start_f, t, ss, l, vcross); #else expand_conflict_region(start_f, t, ss, l, fm, sign_map, vcross); #endif CGAL_assertion( vcross.third == AT2::DISJOINT || vcross.third == AT2::CROSSING || vcross.third == AT2::INTERIOR ); // the following condition becomes true only if intersecting // segments are found if ( vcross.first ) { if ( t.is_segment() ) { if ( vcross.third == AT2::CROSSING ) { Intersections_tag itag; return insert_intersecting_segment(ss, t, vcross.second, itag); } else if ( vcross.third == AT2::INTERIOR ) { Storage_site_2 ssvv = vcross.second->storage_site(); Storage_site_2 ss1 = split_storage_site(ss, ssvv, true); Storage_site_2 ss2 = split_storage_site(ss, ssvv, false); // merge the info of the splitting point and the segment merge_info(vcross.second, ss); insert_segment_interior(ss1.site(), ss1, vcross.second); return insert_segment_interior(ss2.site(), ss2, vcross.second); } else { // this should never be reached; the only possible values for // vcross.third are CROSSING, INTERIOR and DISJOINT CGAL_error(); } } } // no intersecting segment has been found; we insert the segment as // usual... Vertex_handle v = create_vertex(ss); #ifdef CGAL_SDG_NO_FACE_MAP retriangulate_conflict_region(v, l); #else retriangulate_conflict_region(v, l, fm); #endif return v; } //-------------------------------------------------------------------- // insertion of an intersecting segment //-------------------------------------------------------------------- template<class Gt, class ST, class D_S, class LTag> typename Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>::Vertex_handle Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>:: insert_intersecting_segment_with_tag(const Storage_site_2& /* ss */, const Site_2& /* t */, Vertex_handle /* v */, Tag_false) { #if defined(__POWERPC__) && \ defined(__GNUC__) && (__GNUC__ == 3) && (__GNUC_MINOR__ == 4) // hack to avoid nasty warning for G++ 3.4 on Darwin static int i; #else static int i = 0; #endif if ( i == 0 ) { i = 1; print_error_message(); } return Vertex_handle(); } template<class Gt, class ST, class D_S, class LTag> typename Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>::Vertex_handle Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>:: insert_intersecting_segment_with_tag(const Storage_site_2& ss, const Site_2& t, Vertex_handle v, Tag_true tag) { CGAL_precondition( t.is_segment() && v->is_segment() ); const Storage_site_2& ssitev = v->storage_site(); Site_2 sitev = ssitev.site(); if ( same_segments(t, sitev) ) { merge_info(v, ss); return v; } Vertex_triple vt = insert_point_on_segment(ss, t, v, tag); Vertex_handle vsx = vt.first; Storage_site_2 ss3 = st_.construct_storage_site_2_object()(ss, ssitev, true); Storage_site_2 ss4 = st_.construct_storage_site_2_object()(ss, ssitev, false); Site_2 s3 = ss3.site(); Site_2 s4 = ss4.site(); insert_segment_interior(s3, ss3, vsx); insert_segment_interior(s4, ss4, vsx); return vsx; } //-------------------------------------------------------------------- //-------------------------------------------------------------------- // helper methods for insertion (find conflict region) //-------------------------------------------------------------------- //-------------------------------------------------------------------- template<class Gt, class ST, class D_S, class LTag> void Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>:: initialize_conflict_region(const Face_handle& f, List& l) { l.clear(); for (int i = 0; i < 3; i++) { l.push_back(sym_edge(f, i)); } } template<class Gt, class ST, class D_S, class LTag> void Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>:: expand_conflict_region(const Face_handle& f, const Site_2& t, const Storage_site_2& ss, #ifdef CGAL_SDG_NO_FACE_MAP List& l, #else List& l, Face_map& fm, std::map<Face_handle,Sign>& sign_map, #endif Triple<bool,Vertex_handle,Arrangement_type>& vcross) { #ifdef CGAL_SDG_NO_FACE_MAP if ( f->tds_data().is_in_conflict() ) { return; } #else if ( fm.find(f) != fm.end() ) { return; } #endif // this is done to stop the recursion when intersecting segments // are found if ( vcross.first ) { return; } // setting fm[f] to true means that the face has been reached and // that the face is available for recycling. If we do not want the // face to be available for recycling we must set this flag to // false. #ifdef CGAL_SDG_NO_FACE_MAP f->tds_data().mark_in_conflict(); fhc_.push_back(f); #else fm[f] = true; #endif // CGAL_assertion( fm.find(f) != fm.end() ); for (int i = 0; i < 3; i++) { Face_handle n = f->neighbor(i); #ifdef CGAL_SDG_NO_FACE_MAP bool face_registered = n->tds_data().is_in_conflict(); #else bool face_registered = (fm.find(n) != fm.end()); #endif if ( !face_registered ) { for (int j = 0; j < 3; j++) { Vertex_handle vf = n->vertex(j); if ( is_infinite(vf) ) { continue; } Arrangement_type at_res = arrangement_type(t, vf); CGAL_assertion( vcross.third == AT2::DISJOINT || vcross.third == AT2::CROSSING || vcross.third == AT2::INTERIOR ); if ( vf->is_segment() ) { CGAL_assertion( at_res != AT2::IDENTICAL ); CGAL_assertion( at_res != AT2::TOUCH_11_INTERIOR_1 ); CGAL_assertion( at_res != AT2::TOUCH_12_INTERIOR_1 ); if ( at_res == AT2::CROSSING ) { vcross.first = true; vcross.second = vf; vcross.third = AT2::CROSSING; l.clear(); #ifdef CGAL_SDG_NO_FACE_MAP fhc_.clear(); #else fm.clear(); #endif return; } else { CGAL_assertion ( at_res == AT2::DISJOINT || at_res == AT2::TOUCH_1 || at_res == AT2::TOUCH_2 || at_res == AT2::TOUCH_11 || at_res == AT2::TOUCH_12 || at_res == AT2::TOUCH_21 || at_res == AT2::TOUCH_22 ); // we do nothing in these cases } } else { CGAL_assertion( vf->is_point() ); if ( at_res == AT2::INTERIOR ) { vcross.first = true; vcross.second = vf; vcross.third = AT2::INTERIOR; l.clear(); #ifdef CGAL_SDG_NO_FACE_MAP fhc_.clear(); #else fm.clear(); #endif return; } } } } Sign s = incircle(n, t); #ifdef CGAL_SDG_NO_FACE_MAP n->tds_data().set_incircle_sign(s); Sign s_f = f->tds_data().incircle_sign(); #else sign_map[n] = s; Sign s_f = sign_map[f]; #endif if ( s == POSITIVE ) { continue; } if ( s != s_f ) { continue; } bool interior_in_conflict = edge_interior(f, i, t, s); if ( !interior_in_conflict ) { continue; } if ( face_registered ) { continue; } Edge e = sym_edge(f, i); CGAL_assertion( l.is_in_list(e) ); int j = this->_tds.mirror_index(f, i); Edge e_before = sym_edge(n, ccw(j)); Edge e_after = sym_edge(n, cw(j)); if ( !l.is_in_list(e_before) ) { l.insert_before(e, e_before); } if ( !l.is_in_list(e_after) ) { l.insert_after(e, e_after); } l.remove(e); #ifdef CGAL_SDG_NO_FACE_MAP expand_conflict_region(n, t, ss, l, vcross); #else expand_conflict_region(n, t, ss, l, fm, sign_map, vcross); #endif // this is done to stop the recursion when intersecting segments // are found // if ( fm.size() == 0 && l.size() == 0 ) { return; } if ( vcross.first ) { return; } } // for-loop } //-------------------------------------------------------------------- // retriangulate conflict region //-------------------------------------------------------------------- template<class Gt, class ST, class D_S, class LTag> typename Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>::Vertex_handle Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>:: add_bogus_vertex(Edge e, List& l) { Edge esym = sym_edge(e); Face_handle g1 = e.first; Face_handle g2 = esym.first; Vertex_handle v = insert_degree_2(e); Face_circulator fc(v); Face_handle f1(fc); Face_handle f2(++fc); int i1 = f1->index(v); int i2 = f2->index(v); CGAL_assertion( ((f1->neighbor(i1) == g1) && (f2->neighbor(i2) == g2)) || ((f1->neighbor(i1) == g2) && (f2->neighbor(i2) == g1)) ); Edge ee, eesym; if ( f1->neighbor(i1) == g1 ) { ee = Edge(f2, i2); eesym = Edge(f1, i1); } else { ee = Edge(f1, i1); eesym = Edge(f2, i2); } l.replace(e, ee); l.replace(esym, eesym); return v; } template<class Gt, class ST, class D_S, class LTag> typename Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>::Vertex_list Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>:: add_bogus_vertices(List& l) { #if defined(USE_INPLACE_LIST) && defined(CGAL_SDG_NO_FACE_MAP) Vertex_list vertex_list; Edge e_start = l.front(); Edge e = e_start; std::list<Edge> edge_list; do { Edge esym = sym_edge(e); if ( l.is_in_list(esym) ) { if ( !esym.first->tds_data().is_selected(esym.second) ) { e.first->tds_data().mark_selected(e.second); edge_list.push_back(e); } } e = l.next(e); } while ( e != e_start ); e_start = l.front(); e = e_start; do { if ( e.first->tds_data().is_selected(e.second) ) { e.first->tds_data().mark_unselected(e.second); } } while ( e != e_start ); typename std::list<Edge>::iterator it; for (it = edge_list.begin(); it != edge_list.end(); ++it) { Vertex_handle v = add_bogus_vertex(*it, l); vertex_list.push_back(v); } return vertex_list; #else Vertex_list vertex_list; std::set<Edge> edge_list; edge_list.clear(); Edge e_start = l.front(); Edge e = e_start; do { Edge esym = sym_edge(e); if ( l.is_in_list(esym) && edge_list.find(esym) == edge_list.end() ) { edge_list.insert(e); } e = l.next(e); } while ( e != e_start ); typename std::set<Edge>::iterator it; for (it = edge_list.begin(); it != edge_list.end(); ++it) { Vertex_handle v = add_bogus_vertex(*it, l); vertex_list.push_back(v); } return vertex_list; #endif } template<class Gt, class ST, class D_S, class LTag> void Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>:: remove_bogus_vertices(Vertex_list& vl) { while ( vl.size() > 0 ) { Vertex_handle v = vl.front(); vl.pop_front(); remove_degree_2(v); } } template<class Gt, class ST, class D_S, class LTag> void Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>:: #ifdef CGAL_SDG_NO_FACE_MAP retriangulate_conflict_region(Vertex_handle v, List& l) #else retriangulate_conflict_region(Vertex_handle v, List& l, Face_map& fm) #endif { // 1. add the bogus vetrices Vertex_list dummy_vertices = add_bogus_vertices(l); // 2. repair the face pointers... Edge e_start = l.front(); Edge eit = e_start; do { Edge esym = sym_edge(eit); Face_handle f = eit.first; int k = eit.second; CGAL_assertion( !l.is_in_list(esym) ); #ifdef CGAL_SDG_NO_FACE_MAP CGAL_assertion( !f->tds_data().is_in_conflict() ); #else CGAL_assertion( fm.find(f) == fm.end() ); #endif f->vertex(ccw(k))->set_face(f); f->vertex( cw(k))->set_face(f); eit = l.next(eit); } while ( eit != e_start ); // 3. copy the edge list to a vector of edges and clear the edge list // MK:: here I actually need to copy the edges to an std::list<Edge>, or // even better add iterators to the list of type List std::vector<Edge> ve(l.size()); Edge efront = l.front(); Edge e = efront; unsigned int k = 0; do { ve[k] = e; ++k; e = l.next(e); } while ( e != efront ); l.clear(); // 4. retriangulate the hole this->_tds.star_hole(v, ve.begin(), ve.end()); // 5. remove the bogus vertices remove_bogus_vertices(dummy_vertices); // 6. remove the unused faces #ifdef CGAL_SDG_NO_FACE_MAP typename std::vector<Face_handle>::iterator it; for (it = fhc_.begin(); it != fhc_.end(); ++it) { (*it)->tds_data().clear(); this->_tds.delete_face( *it ); } fhc_.clear(); #else typename Face_map::iterator it; for (it = fm.begin(); it != fm.end(); ++it) { Face_handle fh = (*it).first; this->_tds.delete_face(fh); } fm.clear(); #endif // 7. DONE!!!! } //==================================================================== //==================================================================== // METHODS FOR REMOVAL //==================================================================== //==================================================================== template<class Gt, class ST, class D_S, class LTag> bool Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>:: is_star(const Vertex_handle& v) const { CGAL_precondition( v->storage_site().is_point() ); Vertex_circulator vc_start = incident_vertices(v); Vertex_circulator vc = vc_start; Storage_site_2 p = v->storage_site(); size_type count = 0; do { Storage_site_2 ss = vc->storage_site(); if ( ss.is_segment() && is_endpoint_of_segment(p, ss) ) { ++count; // if ( count == 3 ) { break; } if ( count == 3 ) { return true; } } ++vc; } while ( vc != vc_start ); return false; } template<class Gt, class ST, class D_S, class LTag> bool Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>:: is_linear_chain(const Vertex_handle& v0, const Vertex_handle& v1, const Vertex_handle& v2) const { Site_2 tt[3] = { v0->site(), v1->site(), v2->site() }; if ( tt[1].is_point() && tt[0].is_segment() && tt[2].is_segment() && is_endpoint_of_segment(tt[1], tt[0]) && is_endpoint_of_segment(tt[1], tt[2]) ) { typename Geom_traits::Equal_2 are_equal = geom_traits().equal_2_object(); Site_2 s_end[2]; if ( are_equal( tt[1], tt[0].source_site() ) ) { s_end[0] = tt[0].target_site(); } else { s_end[0] = tt[0].source_site(); } if ( are_equal( tt[1], tt[2].source_site() ) ) { s_end[1] = tt[2].target_site(); } else { s_end[1] = tt[2].source_site(); } typename Geom_traits::Orientation_2 orientation = geom_traits().orientation_2_object(); return orientation(s_end[0], s_end[1], tt[1]) == COLLINEAR; } return false; } template<class Gt, class ST, class D_S, class LTag> bool Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>:: is_flippable(const Face_handle& f, int i) const { CGAL_assertion( !is_infinite(f->vertex( cw(i) )) ); Vertex_handle v_other = f->vertex( ccw(i) ); Vertex_handle v0 = f->vertex( i ); Vertex_handle v1 = this->_tds.mirror_vertex( f, i ); if ( is_infinite(v_other) || is_infinite(v0) || is_infinite(v1) ) { return false; } Vertex_handle v = f->vertex( cw(i) ); Storage_site_2 ss = v->storage_site(); Storage_site_2 ss_other = v_other->storage_site(); if ( ss_other.is_point() && ss.is_segment() && is_endpoint_of_segment(ss_other, ss) && is_star(v_other) ) { return false; } if ( is_linear_chain(v0, v_other, v1) ) { return false; } return (v0 != v1) && is_degenerate_edge(f, i); } template<class Gt, class ST, class D_S, class LTag> void Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>:: minimize_degree(const Vertex_handle& v) { CGAL_precondition ( degree(v) > 3 ); Face_circulator fc_start = incident_faces(v); Face_circulator fc = incident_faces(v); bool found(false); do { Face_handle f = Face_handle(fc); int i = ccw( f->index(v) ); CGAL_assertion( f->vertex( cw(i) ) == v ); if ( is_flippable(f,i) ) { Edge e = flip(f, i); f = e.first; if ( !f->has_vertex(v) ) { f = e.first->neighbor(e.second); CGAL_assertion( f->has_vertex(v) ); } fc = --( incident_faces(v,f) ); fc_start = fc; found = true; } else { ++fc; found = false; } } while ( found || fc != fc_start ); } template<class Gt, class ST, class D_S, class LTag> void Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>:: equalize_degrees(const Vertex_handle& v, Self& small_d, std::map<Vertex_handle,Vertex_handle>& vmap, List& l) const { size_type deg = degree(v); CGAL_assertion( l.size() <= deg ); if ( l.size() == deg ) { return; } #if 0 std::cerr << "size of l : " << l.size() << std::endl; std::cerr << "degree of v: " << deg << std::endl; #endif // typedef std::map<Edge,Edge> Edge_map; // maps edges on the boundary of the conflict region from the small // diagram to edges of the star of v in the small diagram // Edge_map emap; Edge e_small_start = l.front(); Edge e_small = e_small_start; bool found; Edge e_small_begin; Edge e_large_begin; do { found = false; Vertex_handle v_sml_src = e_small.first->vertex(cw(e_small.second)); Vertex_handle v_sml_trg = e_small.first->vertex(ccw(e_small.second)); // first we find a first edge in common Face_circulator fc_start = incident_faces(v); Face_circulator fc = fc_start; do { int id = fc->index(v); Vertex_handle v_lrg_src = fc->vertex(ccw(id)); Vertex_handle v_lrg_trg = fc->vertex(cw(id)); if ( vmap[v_sml_src] == v_lrg_src && vmap[v_sml_trg] == v_lrg_trg ) { found = true; e_large_begin = Edge(fc, id); e_small_begin = e_small; break; } } while ( ++fc != fc_start ); if ( found ) { break; } e_small = l.next(e_small); } while ( e_small != e_small_start ); CGAL_assertion( found ); Face_circulator fc_start = incident_faces(v, e_large_begin.first); Face_circulator fc = fc_start; e_small = e_small_begin; do { int id = fc->index(v); Vertex_handle vsml_src = e_small.first->vertex(cw(e_small.second)); Vertex_handle vsml_trg = e_small.first->vertex(ccw(e_small.second)); Vertex_handle vlrg_src = fc->vertex(ccw(id)); Vertex_handle vlrg_trg = fc->vertex(cw(id)); if ( vmap[vsml_src] != vlrg_src || vmap[vsml_trg] != vlrg_trg ) { Edge e_small_prev = l.previous(e_small); std::cerr << "size of l: " << l.size() << std::endl; l.remove(e_small); std::cerr << "size of l: " << l.size() << std::endl; Edge e_small_new = small_d.flip(e_small); Edge e_small_new_sym = small_d.sym_edge(e_small_new); Face_handle f1 = e_small_new.first; Face_handle f2 = e_small_new_sym.first; if ( f2->vertex(e_small_new_sym.second) == vsml_src ) { std::swap(f1, f2); std::swap(e_small_new, e_small_new_sym); CGAL_assertion( f1->vertex(e_small_new.second) == vsml_src ); CGAL_assertion( f2->vertex(e_small_new_sym.second) == vsml_trg ); } Edge to_list1(f1, cw(e_small_new.second)); Edge to_list2(f2, ccw(e_small_new_sym.second)); e_small = small_d.sym_edge(to_list1); l.insert_after(e_small_prev, e_small); std::cerr << "size of l: " << l.size() << std::endl; l.insert_after(e_small, small_d.sym_edge(to_list2)); std::cerr << "size of l: " << l.size() << std::endl; } else { e_small = l.next(e_small); ++fc; } CGAL_assertion( l.size() <= deg ); } while ( fc != fc_start ); #if 0 std::cerr << "size of l : " << l.size() << std::endl; std::cerr << "degree of v: " << deg << std::endl; #endif #if !defined(CGAL_NO_ASSERTIONS) && !defined(NDEBUG) // we go around the boundary of the conflict region verify that all // edges are there CGAL_assertion( l.size() == degree(v) ); e_small = e_small_begin; fc_start = incident_faces(v, e_large_begin.first); fc = fc_start; do { int id = fc->index(v); Vertex_handle vsml_src = e_small.first->vertex(cw(e_small.second)); Vertex_handle vsml_trg = e_small.first->vertex(ccw(e_small.second)); Vertex_handle vlrg_src = fc->vertex(ccw(id)); Vertex_handle vlrg_trg = fc->vertex(cw(id)); CGAL_assertion(vmap[vsml_src] == vlrg_src && vmap[vsml_trg] == vlrg_trg ); // go to next edge e_small = l.next(e_small); } while ( ++fc != fc_start ); #endif } template<class Gt, class ST, class D_S, class LTag> void Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>:: expand_conflict_region_remove(const Face_handle& f, const Site_2& t, const Storage_site_2& ss, List& l, Face_map& fm, Sign_map& sign_map) { if ( fm.find(f) != fm.end() ) { return; } // setting fm[f] to true means that the face has been reached and // that the face is available for recycling. If we do not want the // face to be available for recycling we must set this flag to // false. fm[f] = true; // CGAL_assertion( fm.find(f) != fm.end() ); for (int i = 0; i < 3; i++) { Face_handle n = f->neighbor(i); bool face_registered = (fm.find(n) != fm.end()); Sign s = incircle(n, t); sign_map[n] = s; Sign s_f = sign_map[f]; if ( s == POSITIVE ) { continue; } if ( s != s_f ) { continue; } bool interior_in_conflict = edge_interior(f, i, t, s); if ( !interior_in_conflict ) { continue; } if ( face_registered ) { continue; } Edge e = sym_edge(f, i); CGAL_assertion( l.is_in_list(e) ); int j = this->_tds.mirror_index(f, i); Edge e_before = sym_edge(n, ccw(j)); Edge e_after = sym_edge(n, cw(j)); if ( !l.is_in_list(e_before) ) { l.insert_before(e, e_before); } if ( !l.is_in_list(e_after) ) { l.insert_after(e, e_after); } l.remove(e); expand_conflict_region_remove(n, t, ss, l, fm, sign_map); } // for-loop } template<class Gt, class ST, class D_S, class LTag> void Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>:: find_conflict_region_remove(const Vertex_handle& v, const Vertex_handle& vnearest, List& l, Face_map& fm, Sign_map&) { CGAL_precondition( vnearest != Vertex_handle() ); Storage_site_2 ss = v->storage_site(); Site_2 t = ss.site(); // find the first conflict // first look for conflict with vertex Face_circulator fc_start = incident_faces(vnearest); Face_circulator fc = fc_start; Face_handle start_f; Sign s; Sign_map sign_map; do { Face_handle f(fc); s = incircle(f, t); sign_map[f] = s; if ( s == NEGATIVE ) { start_f = f; break; } ++fc; } while ( fc != fc_start ); CGAL_assertion( s == NEGATIVE ); // we are not in conflict with a Voronoi vertex, so we have to // be in conflict with the interior of a Voronoi edge if ( s != NEGATIVE ) { Edge_circulator ec_start = incident_edges(vnearest); Edge_circulator ec = ec_start; bool interior_in_conflict(false); Edge e; do { e = *ec; Sign s1 = sign_map[e.first]; Sign s2 = sign_map[e.first->neighbor(e.second)]; if ( s1 == s2 ) { interior_in_conflict = edge_interior(e, t, s1); } else { // It seems that there was a problem here when one of the // signs was positive and the other zero. In this case we // still check pretending that both signs where positive interior_in_conflict = edge_interior(e, t, POSITIVE); } if ( interior_in_conflict ) { break; } ++ec; } while ( ec != ec_start ); sign_map.clear(); CGAL_assertion( interior_in_conflict ); l.push_back(e); l.push_back(sym_edge(e)); return; } initialize_conflict_region(start_f, l); expand_conflict_region_remove(start_f, t, ss, l, fm, sign_map); } //-------------------------------------------------------------------- //-------------------------------------------------------------------- template<class Gt, class ST, class D_S, class LTag> typename Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>::size_type Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>:: count_faces(const List& l) const { std::vector<Face_handle> flist; get_faces(l, std::back_inserter(flist)); return flist.size(); } //-------------------------------------------------------------------- //-------------------------------------------------------------------- template<class Gt, class ST, class D_S, class LTag> void Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>:: fill_hole(const Self& small_d, const Vertex_handle& v, const List& l, std::map<Vertex_handle,Vertex_handle>& vmap) { #if 0 std::cerr << "size of l : " << l.size() << std::endl; std::cerr << "degree of v: " << degree(v) << std::endl; #endif typedef std::map<Edge,Edge> Edge_map; // maps edges on the boundary of the conflict region from the small // diagram to edges of the star of v in the small diagram Edge_map emap; Edge e_sml_sym = sym_edge(l.front()); Vertex_handle v_sml_src = e_sml_sym.first->vertex(ccw(e_sml_sym.second)); Vertex_handle v_sml_trg = e_sml_sym.first->vertex(cw(e_sml_sym.second)); // first we find a first edge in common Face_circulator fc_start = incident_faces(v); Face_circulator fc = fc_start; Face_circulator fc_begin; bool found = false; do { int id = fc->index(v); Vertex_handle v_lrg_src = fc->vertex(ccw(id)); Vertex_handle v_lrg_trg = fc->vertex(cw(id)); if ( vmap[v_sml_src] == v_lrg_src && vmap[v_sml_trg] == v_lrg_trg ) { found = true; fc_begin = fc; break; } } while ( ++fc != fc_start ); CGAL_assertion( found ); // container of faces to delete std::list<Face_handle> to_delete; // next we go around the boundary of the conflict region and map all edges Edge e_small = l.front(); fc_start = incident_faces(v, fc_begin); fc = fc_start; do { int id = fc->index(v); #if !defined(CGAL_NO_ASSERTIONS) && !defined(NDEBUG) Vertex_handle vsml_src = e_small.first->vertex(cw(e_small.second)); Vertex_handle vsml_trg = e_small.first->vertex(ccw(e_small.second)); Vertex_handle vlrg_src = fc->vertex(ccw(id)); Vertex_handle vlrg_trg = fc->vertex(cw(id)); CGAL_assertion(vmap[vsml_src] == vlrg_src && vmap[vsml_trg] == vlrg_trg ); #endif // set mapping emap[e_small] = sym_edge(fc, id); // keep face for deletion to_delete.push_back(fc); // go to next edge e_small = l.next(e_small); } while ( ++fc != fc_start ); // map the faces of the small diagram with the new faces of the // large diagram std::map<Face_handle,Face_handle> fmap; std::vector<Face_handle> f_small, f_large; small_d.get_faces(l, std::back_inserter(f_small)); for (unsigned int i = 0; i < f_small.size(); i++) { Face_handle f = this->_tds.create_face(); fmap[ f_small[i] ] = f; f_large.push_back(f); } CGAL_assertion( l.size() == degree(v) ); CGAL_assertion( f_small.size() == f_large.size() ); CGAL_assertion( f_small.size() == l.size() - 2 ); CGAL_assertion( f_small.size() == count_faces(l) ); // set the vertices for the new faces; also set the face for each // vertex for (typename std::vector<Face_handle>::iterator fit = f_small.begin(); fit != f_small.end(); ++fit) { Face_handle ff_small = *fit; Face_handle f = fmap[ff_small]; for (int i = 0; i < 3; ++i) { CGAL_assertion( vmap.find(ff_small->vertex(i)) != vmap.end() ); f->set_vertex(i, vmap[ff_small->vertex(i)]); // we are setting the face for each vertex a lot of times; we // could possibly do it faster if we use the edges on the // boundary of the conflict region // in fact we may not even need it since the make_hole method // updates the faces of the vertices of the boundary of the // hole, and we do not introduce any new vertices f->vertex(i)->set_face(f); } } // set the neighbors for each face for (typename std::vector<Face_handle>::iterator fit = f_small.begin(); fit != f_small.end(); ++fit) { Face_handle ff_small = *fit; for (int i = 0; i < 3; i++) { Face_handle f = fmap[ff_small]; Face_handle n_small = ff_small->neighbor(i); if ( fmap.find(n_small) != fmap.end() ) { // this is one of the new faces f->set_neighbor(i, fmap[n_small]); } else { // otherwise it is one of the old faces outside the conflict // region; we have to use the edge map in this case Edge e_small_sym = small_d.sym_edge(ff_small, i); CGAL_assertion(emap.find(e_small_sym) != emap.end()); Edge e_large = emap[e_small_sym]; f->set_neighbor(i, e_large.first); e_large.first->set_neighbor(e_large.second, f); } } } // delete the unused faces and the vertex while ( !to_delete.empty() ) { delete_face(to_delete.front()); to_delete.pop_front(); } delete_vertex(v); } //-------------------------------------------------------------------- //-------------------------------------------------------------------- template<class Gt, class ST, class D_S, class LTag> bool Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>:: remove_first(const Vertex_handle& v) { Delaunay_graph::remove_first(v); return true; } template<class Gt, class ST, class D_S, class LTag> bool Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>:: remove_second(const Vertex_handle& v) { Delaunay_graph::remove_second(v); return true; } template<class Gt, class ST, class D_S, class LTag> bool Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>:: remove_third(const Vertex_handle& v) { if ( is_degree_2(v) ) { CGAL_assertion( v->storage_site().is_point() ); Face_handle fh( incident_faces(v) ); int i = fh->index(v); flip(fh, i); } else if ( degree(v) == 4 ) { Edge_circulator ec = incident_edges(v); for (int i = 0; i < 4; i++) { Edge e = *ec; Edge sym = sym_edge(e); if ( e.first->vertex(e.second) != sym.first->vertex(sym.second) ) { flip(e); break; } ++ec; } } this->_tds.remove_dim_down( v ); return true; } //-------------------------------------------------------------------- //-------------------------------------------------------------------- template<class Gt, class ST, class D_S, class LTag> void Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>:: compute_small_diagram(const Vertex_handle& v, Self& small_d) const { Vertex_circulator vc_start = incident_vertices(v); Vertex_circulator vc = vc_start; // insert all neighboring sites do { if ( !is_infinite(vc) ) { Site_2 t = vc->site(); if ( t.is_input() ) { small_d.insert(t); } else if ( t.is_point() ) { small_d.insert(t.supporting_site(0)); /*Vertex_handle vnear =*/ small_d.insert(t.supporting_site(1)); // vh_small = sdg_small.nearest_neighbor(t, vnear); } else { CGAL_assertion( t.is_segment() ); /*Vertex_handle vnear =*/ small_d.insert(t.supporting_site()); // vh_small = sdg_small.nearest_neighbor(t, vnear); } // CGAL_assertion( vh_small != Vertex_handle() ); // vmap[vh_small] = vh_large; } ++vc; } while ( vc != vc_start ); } //-------------------------------------------------------------------- //-------------------------------------------------------------------- template<class Gt, class ST, class D_S, class LTag> void Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>:: compute_vertex_map(const Vertex_handle& v, const Self& small_d, std::map<Vertex_handle,Vertex_handle>& vmap) const { Vertex_circulator vc_start = incident_vertices(v); Vertex_circulator vc = vc_start; Vertex_handle vh_large, vh_small; do { vh_large = Vertex_handle(vc); if ( is_infinite(vh_large) ) { vh_small = small_d.infinite_vertex(); vmap[vh_small] = vh_large; } else { #if !defined(CGAL_NO_ASSERTIONS) && !defined(NDEBUG) vh_small = Vertex_handle(); #endif Site_2 t = vc->site(); if ( t.is_input() ) { if ( t.is_segment() ) { Vertex_handle vv = small_d.nearest_neighbor( t.source() ); Vertex_circulator vvc_start = small_d.incident_vertices(vv); Vertex_circulator vvc = vvc_start; do { if ( small_d.same_segments(t, vvc) ) { vh_small = vvc; break; } } while ( ++vvc != vvc_start ); CGAL_assertion( small_d.same_segments(t, vh_small) ); } else { CGAL_assertion( t.is_point() ); vh_small = small_d.nearest_neighbor( t.point() ); CGAL_assertion( small_d.same_points(t, vh_small->site()) ); } } else if ( t.is_segment() ) { Vertex_handle vv = small_d.nearest_neighbor( t.source_site(), Vertex_handle() ); Vertex_circulator vvc_start = small_d.incident_vertices(vv); Vertex_circulator vvc = vvc_start; do { if ( small_d.same_segments(t, vvc) ) { vh_small = vvc; break; } } while ( ++vvc != vvc_start ); CGAL_assertion( small_d.same_segments(t, vh_small) ); } else { CGAL_assertion( t.is_point() ); vh_small = small_d.nearest_neighbor( t, Vertex_handle() ); CGAL_assertion( small_d.same_points(t, vh_small->site()) ); } CGAL_assertion( vh_small != Vertex_handle() ); vmap[vh_small] = vh_large; } ++vc; } while ( vc != vc_start ); } //-------------------------------------------------------------------- //-------------------------------------------------------------------- template<class Gt, class ST, class D_S, class LTag> void Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>:: remove_degree_d_vertex(const Vertex_handle& v) { #if 0 Self sdg_small; compute_small_diagram(v, sdg_small); std::map<Vertex_handle,Vertex_handle> vmap; compute_vertex_map(v, sdg_small, vmap); // find nearest neighbor of v in small diagram Site_2 t = v->site(); Vertex_handle vn; CGAL_assertion( t.is_input() ); if ( t.is_point() ) { vn = sdg_small.nearest_neighbor( t.point() ); } else { vn = sdg_small.nearest_neighbor( t.source() ); } CGAL_assertion( vn != Vertex_handle() ); List l; Face_map fm; Sign_map sign_map; sdg_small.find_conflict_region_remove(v, vn, l, fm, sign_map); fm.clear(); sign_map.clear(); equalize_degrees(v, sdg_small, vmap, l); fill_hole(sdg_small, v, l, vmap); l.clear(); return; #else minimize_degree(v); size_type deg = degree(v); if ( deg == 3 ) { remove_degree_3(v); return; } if ( deg == 2 ) { remove_degree_2(v); return; } Self sdg_small; compute_small_diagram(v, sdg_small); if ( sdg_small.number_of_vertices() <= 2 ) { CGAL_assertion( sdg_small.number_of_vertices() == 2 ); CGAL_assertion( deg == 4 ); Edge_circulator ec_start = incident_edges(v); Edge_circulator ec = ec_start; do { if ( is_infinite(*ec) ) { break; } ++ec; } while ( ec != ec_start ); CGAL_assertion( is_infinite(ec) ); flip(*ec); remove_degree_3(v); return; } std::map<Vertex_handle,Vertex_handle> vmap; compute_vertex_map(v, sdg_small, vmap); // find nearest neighbor of v in small diagram Site_2 t = v->site(); Vertex_handle vn; CGAL_assertion( t.is_input() ); // here we find a site in the small diagram that serves as a // starting point for finding all conflicts. // To do that we find the nearest neighbor of t if t is a point; // t is guarranteed to have a conflict with its nearest neighbor // If t is a segment, then one endpoint of t is enough; t is // guarranteed to have a conflict with the Voronoi edges around // this endpoint if ( t.is_point() ) { vn = sdg_small.nearest_neighbor( t.point() ); } else { vn = sdg_small.nearest_neighbor( t.source() ); } CGAL_assertion( vn != Vertex_handle() ); List l; Face_map fm; Sign_map sign_map; sdg_small.find_conflict_region_remove(v, vn, l, fm, sign_map); fill_hole(sdg_small, v, l, vmap); l.clear(); fm.clear(); sign_map.clear(); #endif } //-------------------------------------------------------------------- //-------------------------------------------------------------------- template<class Gt, class ST, class D_S, class LTag> bool Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>:: remove_base(const Vertex_handle& v) { Storage_site_2 ssv = v->storage_site(); CGAL_precondition( ssv.is_input() ); // first consider the case where we have up to 2 points size_type n = number_of_vertices(); if ( n == 1 ) { return remove_first(v); } else if ( n == 2 ) { return remove_second(v); } // secondly check if the point to be deleted is adjacent to a segment if ( ssv.is_point() ) { Vertex_circulator vc_start = incident_vertices(v); Vertex_circulator vc = vc_start; do { Storage_site_2 ss = vc->storage_site(); if ( ss.is_segment() && is_endpoint_of_segment(ssv, ss) ) { return false; } ++vc; } while ( vc != vc_start ); } // now do the deletion if ( n == 3 ) { return remove_third(v); } size_type deg = degree(v); if ( deg == 2 ) { remove_degree_2(v); } else if ( deg == 3 ) { remove_degree_3(v); } else { remove_degree_d_vertex(v); } return true; } //-------------------------------------------------------------------- //-------------------------------------------------------------------- template<class Gt, class ST, class D_S, class LTag> bool Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>:: remove(const Vertex_handle& v) { CGAL_precondition( !is_infinite(v) ); const Storage_site_2& ss = v->storage_site(); if ( !ss.is_input() ) { return false; } Point_handle h1, h2; bool is_point = ss.is_point(); if ( is_point ) { h1 = ss.point(); } else { CGAL_assertion( ss.is_segment() ); h1 = ss.source_of_supporting_site(); h2 = ss.target_of_supporting_site(); } bool success = remove_base(v); if ( success ) { // unregister the input site if ( is_point ) { unregister_input_site( h1 ); } else { unregister_input_site( h1, h2 ); } } return success; } //-------------------------------------------------------------------- //-------------------------------------------------------------------- // combinatorial operations //-------------------------------------------------------------------- //-------------------------------------------------------------------- //-------------------------------------------------------------------- //-------------------------------------------------------------------- // point location //-------------------------------------------------------------------- //-------------------------------------------------------------------- template<class Gt, class ST, class D_S, class LTag> typename Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>::Vertex_handle Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>:: nearest_neighbor(const Site_2& p, Vertex_handle start_vertex) const { CGAL_precondition( p.is_point() ); if ( number_of_vertices() == 0 ) { return Vertex_handle(); } if ( start_vertex == Vertex_handle() ) { start_vertex = finite_vertex(); } // if ( start_vertex == NULL ) { return start_vertex; } Vertex_handle vclosest; Vertex_handle v = start_vertex; if ( number_of_vertices() < 3 ) { vclosest = v; Finite_vertices_iterator vit = finite_vertices_begin(); for (; vit != finite_vertices_end(); ++vit) { Vertex_handle v1(vit); if ( v1 != vclosest /*&& !is_infinite(v1)*/ ) { Site_2 t0 = vclosest->site(); Site_2 t1 = v1->site(); if ( side_of_bisector(t0, t1, p) == ON_NEGATIVE_SIDE ) { vclosest = v1; } } } return vclosest; } do { vclosest = v; Site_2 t0 = v->site(); // if ( t0.is_point() && same_points(p, t0) ) { // return vclosest; // } Vertex_circulator vc_start = incident_vertices(v); Vertex_circulator vc = vc_start; do { if ( !is_infinite(vc) ) { Vertex_handle v1(vc); Site_2 t1 = v1->site(); Oriented_side os = side_of_bisector(t0, t1, p); if ( os == ON_NEGATIVE_SIDE ) { v = v1; break; } } ++vc; } while ( vc != vc_start ); } while ( vclosest != v ); return vclosest; } //---------------------------------------------------------------------- //---------------------------------------------------------------------- // methods for the predicates //---------------------------------------------------------------------- //---------------------------------------------------------------------- template<class Gt, class ST, class D_S, class LTag> Sign Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>:: incircle(const Face_handle& f, const Site_2& q) const { if ( !is_infinite(f) ) { return incircle(f->vertex(0)->site(), f->vertex(1)->site(), f->vertex(2)->site(), q); } int inf_i(-1); // to avoid compiler warning for (int i = 0; i < 3; i++) { if ( is_infinite(f->vertex(i)) ) { inf_i = i; break; } } return incircle( f->vertex( ccw(inf_i) )->site(), f->vertex( cw(inf_i) )->site(), q ); } template<class Gt, class ST, class D_S, class LTag> Sign Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>:: incircle(const Vertex_handle& v0, const Vertex_handle& v1, const Vertex_handle& v2, const Vertex_handle& v) const { CGAL_precondition( !is_infinite(v) ); if ( !is_infinite(v0) && !is_infinite(v1) && !is_infinite(v2) ) { return incircle(v0->site(), v1->site(), v2->site(), v->site()); } if ( is_infinite(v0) ) { CGAL_precondition( !is_infinite(v1) && !is_infinite(v2) ); return incircle( v1->site(), v2->site(), v->site()); } if ( is_infinite(v1) ) { CGAL_precondition( !is_infinite(v0) && !is_infinite(v2) ); return incircle( v2->site(), v0->site(), v->site()); } CGAL_assertion( is_infinite(v2) ); CGAL_precondition( !is_infinite(v0) && !is_infinite(v1) ); return incircle( v0->site(), v1->site(), v->site()); } // this the finite edge interior predicate for a degenerate edge template<class Gt, class ST, class D_S, class LTag> bool Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>:: finite_edge_interior(const Face_handle& f, int i, const Site_2& q, Sign sgn, int) const { if ( !is_infinite( this->_tds.mirror_vertex(f, i) ) ) { CGAL_precondition( is_infinite(f->vertex(i)) ); Face_handle g = f->neighbor(i); int j = this->_tds.mirror_index(f, i); return finite_edge_interior(g, j, q, sgn, 0 /* degenerate */); } CGAL_precondition( is_infinite( this->_tds.mirror_vertex(f, i) ) ); Site_2 t1 = f->vertex( ccw(i) )->site(); Site_2 t2 = f->vertex( cw(i) )->site(); if ( is_infinite(f->vertex(i)) ) { return finite_edge_interior(t1, t2, q, sgn); } Site_2 t3 = f->vertex(i)->site(); return finite_edge_interior(t1, t2, t3, q, sgn); } template<class Gt, class ST, class D_S, class LTag> bool Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>:: finite_edge_interior(const Vertex_handle& v1, const Vertex_handle& v2, const Vertex_handle& v3, const Vertex_handle& v4, const Vertex_handle& v, Sign sgn, int) const { CGAL_precondition( !is_infinite(v1) && !is_infinite(v2) && !is_infinite(v) ); if ( !is_infinite( v4 ) ) { CGAL_precondition( is_infinite(v3) ); return finite_edge_interior(v2, v1, v4, v3, v, sgn, 0 /* degenerate */); } CGAL_precondition( is_infinite( v4 ) ); Site_2 t1 = v1->site(); Site_2 t2 = v2->site(); Site_2 q = v->site(); if ( is_infinite(v3) ) { return finite_edge_interior(t1, t2, q, sgn); } Site_2 t3 = v3->site(); return finite_edge_interior(t1, t2, t3, q, sgn); } template<class Gt, class ST, class D_S, class LTag> bool Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>:: infinite_edge_interior(const Face_handle& f, int i, const Site_2& q, Sign sgn) const { if ( !is_infinite( f->vertex(ccw(i)) ) ) { CGAL_precondition( is_infinite( f->vertex(cw(i)) ) ); Face_handle g = f->neighbor(i); int j = this->_tds.mirror_index(f, i); return infinite_edge_interior(g, j, q, sgn); } CGAL_precondition( is_infinite( f->vertex(ccw(i)) ) ); Site_2 t2 = f->vertex( cw(i) )->site(); Site_2 t3 = f->vertex( i )->site(); Site_2 t4 = this->_tds.mirror_vertex(f, i)->site(); return infinite_edge_interior(t2, t3, t4, q, sgn); } template<class Gt, class ST, class D_S, class LTag> bool Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>:: infinite_edge_interior(const Vertex_handle& v1, const Vertex_handle& v2, const Vertex_handle& v3, const Vertex_handle& v4, const Vertex_handle& v, Sign sgn) const { CGAL_precondition( !is_infinite(v3) && !is_infinite(v4) && !is_infinite(v) ); if ( !is_infinite( v1 ) ) { CGAL_precondition( is_infinite( v2 ) ); return infinite_edge_interior(v2, v1, v4, v3, v, sgn); } CGAL_precondition( is_infinite( v1 ) ); Site_2 t2 = v2->site(); Site_2 t3 = v3->site(); Site_2 t4 = v4->site(); Site_2 q = v->site(); return infinite_edge_interior(t2, t3, t4, q, sgn); } template<class Gt, class ST, class D_S, class LTag> bool Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>:: edge_interior(const Vertex_handle& v1, const Vertex_handle& v2, const Vertex_handle& v3, const Vertex_handle& v4, const Vertex_handle& v, Sign sgn) const { CGAL_precondition( !is_infinite(v) ); bool is_inf_v1 = is_infinite(v1); bool is_inf_v2 = is_infinite(v2); bool is_inf_v3 = is_infinite(v3); bool is_inf_v4 = is_infinite(v4); bool result; if ( !is_inf_v1 && !is_inf_v2 && !is_inf_v3 && !is_inf_v4 ) { result = finite_edge_interior(v1, v2, v3, v4, v, sgn); } else if ( is_inf_v3 || is_inf_v4 ) { result = finite_edge_interior(v1, v2, v3, v4, v, sgn, 0/* degenerate */); } else { result = infinite_edge_interior(v1, v2, v3, v4, v, sgn); } return result; } template<class Gt, class ST, class D_S, class LTag> bool Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>:: edge_interior(const Face_handle& f, int i, const Site_2& q, Sign sgn) const { Face_handle g = f->neighbor(i); bool is_inf_f = is_infinite(f); bool is_inf_g = is_infinite(g); bool result; if ( !is_inf_f && !is_inf_g ) { result = finite_edge_interior(f, i, q, sgn); } else if ( !is_inf_f || !is_inf_g ) { result = finite_edge_interior(f, i, q, sgn, 0 /* denegerate */); } else { if ( !is_infinite(f, i) ) { result = finite_edge_interior(f, i, q, sgn, 0 /* degenerate */); } else { result = infinite_edge_interior(f, i, q, sgn); } } return result; } template<class Gt, class ST, class D_S, class LTag> typename Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>::Arrangement_type Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>:: arrangement_type(const Site_2& p, const Site_2& q) const { typedef typename Geom_traits::Arrangement_type_2 AT2; typedef typename AT2::result_type Arrangement_type; Arrangement_type res = geom_traits().arrangement_type_2_object()(p, q); // The valeus that have to be treated are the following: // DISJOINT, TOUCH_1, TOUCH_2, CROSSING, IDENTICAL, INTERIOR, // TOUCH_11_INTERIOR_1, TOUCH_12_INTERIOR_1, TOUCH_21_INTERIOR_1 and // TOUCH_22_INTERIOR_1. // // The remaining values will either never appear because of one of // the following reasons: // 1. we insert the endpoints of the segments first and then the // interior (OVERLAPPING_*, INTERIOR_*, TOUCH_*_INTERIOR_2). // 2. the values have no meaning since we consider the segments to // be open (TOUCH_INTERIOR_*). In this case, the conflict will // appear when we test with the endpoint. // 3. a conflict will first happen with an endpoint before testing // for the segment (TOUCH_2*_INTERIOR_1). In this case the // segment to be inserted will first find an endpoint in its // interior before actually finding that there is another segment // it overlaps with. CGAL_assertion( res != AT2::INTERIOR_1 ); CGAL_assertion( res != AT2::INTERIOR_2 ); CGAL_assertion( res != AT2::OVERLAPPING_11 ); CGAL_assertion( res != AT2::OVERLAPPING_12 ); CGAL_assertion( res != AT2::OVERLAPPING_21 ); CGAL_assertion( res != AT2::OVERLAPPING_22 ); CGAL_assertion( res != AT2::TOUCH_11_INTERIOR_2 ); CGAL_assertion( res != AT2::TOUCH_21_INTERIOR_2 ); CGAL_assertion( res != AT2::TOUCH_12_INTERIOR_2 ); CGAL_assertion( res != AT2::TOUCH_22_INTERIOR_2 ); CGAL_assertion( res != AT2::TOUCH_21_INTERIOR_1 ); CGAL_assertion( res != AT2::TOUCH_22_INTERIOR_1 ); if ( res == AT2::TOUCH_INTERIOR_12 || res == AT2::TOUCH_INTERIOR_21 || res == AT2::TOUCH_INTERIOR_11 || res == AT2::TOUCH_INTERIOR_22 ) { return AT2::DISJOINT; } if ( res == AT2::TOUCH_11 || res == AT2::TOUCH_12 || res == AT2::TOUCH_21 || res == AT2::TOUCH_22 ) { return AT2::DISJOINT; } return res; } //-------------------------------------------------------------------- //-------------------------------------------------------------------- // embedding and visualization methods and constructions for primal // and dual //-------------------------------------------------------------------- //-------------------------------------------------------------------- // primal template<class Gt, class ST, class D_S, class LTag> Object Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>:: primal(const Edge e) const { typedef typename Gt::Line_2 Line_2; typedef typename Gt::Ray_2 Ray_2; CGAL_precondition( !is_infinite(e) ); if ( this->dimension() == 1 ) { Site_2 p = (e.first)->vertex(cw(e.second))->site(); Site_2 q = (e.first)->vertex(ccw(e.second))->site(); Line_2 l = construct_sdg_bisector_2_object()(p,q); return make_object(l); } // dimension == 2 // none of the two adjacent faces is infinite if( (!is_infinite(e.first)) && (!is_infinite(e.first->neighbor(e.second))) ) { Site_2 p = (e.first)->vertex( ccw(e.second) )->site(); Site_2 q = (e.first)->vertex( cw(e.second) )->site(); Site_2 r = (e.first)->vertex( e.second )->site(); Site_2 s = this->_tds.mirror_vertex(e.first, e.second)->site(); return construct_sdg_bisector_segment_2_object()(p,q,r,s); } // both of the adjacent faces are infinite if ( is_infinite(e.first) && is_infinite(e.first->neighbor(e.second)) ) { Site_2 p = (e.first)->vertex(cw(e.second))->site(); Site_2 q = (e.first)->vertex(ccw(e.second))->site(); Line_2 l = construct_sdg_bisector_2_object()(p,q); return make_object(l); } // only one of the adjacent faces is infinite CGAL_assertion( is_infinite( e.first ) || is_infinite( e.first->neighbor(e.second) ) ); CGAL_assertion( !(is_infinite( e.first ) && is_infinite( e.first->neighbor(e.second) ) ) ); CGAL_assertion( is_infinite(e.first->vertex(e.second)) || is_infinite(this->_tds.mirror_vertex(e.first, e.second)) ); Edge ee = e; if ( is_infinite( e.first->vertex(e.second) ) ) { ee = sym_edge(e); } Site_2 p = ee.first->vertex( ccw(ee.second) )->site(); Site_2 q = ee.first->vertex( cw(ee.second) )->site(); Site_2 r = ee.first->vertex( ee.second )->site(); Ray_2 ray = construct_sdg_bisector_ray_2_object()(p,q,r); return make_object(ray); } //-------------------------------------------------------------------- //-------------------------------------------------------------------- // validity test method //-------------------------------------------------------------------- //-------------------------------------------------------------------- template<class Gt, class ST, class D_S, class LTag> bool Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>:: is_valid(bool verbose, int level) const { if (level < 0) { return true; } if (number_of_vertices() <= 1) { if ( verbose && number_of_vertices() == 1 ) { std::cerr << "SDGDS is ok... " << std::flush; } return true; } // level 0 test: check the TDS bool result = data_structure().is_valid(verbose, level); if ( result && verbose ) { std::cerr << "SDGDS is ok... " << std::flush; } if (level == 0) { return result; } // level 1 test: do the incircle tests if (number_of_vertices() < 3) { return true; } for (All_edges_iterator eit = all_edges_begin(); eit != all_edges_end(); ++eit) { Edge e = *eit; Face_handle f = e.first; Vertex_handle v = this->_tds.mirror_vertex(f, e.second); if ( f->vertex(e.second) == v ) { continue; } if ( !is_infinite(v) ) { result = result && ( incircle(f, v->site()) != NEGATIVE ); } Edge sym_e = sym_edge(e); f = sym_e.first; v = this->_tds.mirror_vertex(f, sym_e.second); if ( !is_infinite(v) ) { result = result && ( incircle(f, v->site()) != NEGATIVE ); } } if ( result && verbose ) { std::cerr << "Segment Delaunay graph is ok..." << std::flush; } if ( !result && verbose ) { std::cerr << "Segment Delaunay graph is NOT valid..." << std::flush; } return result; } //-------------------------------------------------------------------- //-------------------------------------------------------------------- // misc //-------------------------------------------------------------------- //-------------------------------------------------------------------- template<class Gt, class ST, class D_S, class LTag> void Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>:: print_error_message() const { std::cerr << std::endl; std::cerr << "WARNING:" << std::endl; std::cerr << "A segment-segment intersection was found." << std::endl; std::cerr << "The Segment_Delaunay_graph_2 class is not configured" << " to handle this situation." << std::endl; std::cerr << "Please look at the documentation on how to handle" << " this behavior." << std::endl; std::cerr << std::endl; } //-------------------------------------------------------------------- //-------------------------------------------------------------------- // the copy method //-------------------------------------------------------------------- //-------------------------------------------------------------------- template<class Gt, class ST, class D_S, class LTag> typename Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>::Storage_site_2 Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>:: copy_storage_site(const Storage_site_2& ss_other, Handle_map& hm, const Tag_false&) { if ( ss_other.is_segment() ) { Point_handle p0 = hm[ ss_other.source_of_supporting_site() ]; Point_handle p1 = hm[ ss_other.target_of_supporting_site() ]; return st_.construct_storage_site_2_object()(p0, p1); } else { Point_handle p0 = hm[ ss_other.point() ]; return st_.construct_storage_site_2_object()(p0); } } template<class Gt, class ST, class D_S, class LTag> typename Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>::Storage_site_2 Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>:: copy_storage_site(const Storage_site_2& ss_other, Handle_map& hm, const Tag_true&) { if ( ss_other.is_segment() ) { if ( ss_other.is_input() ) { Point_handle p0 = hm[ ss_other.source_of_supporting_site() ]; Point_handle p1 = hm[ ss_other.target_of_supporting_site() ]; return st_.construct_storage_site_2_object()(p0, p1); } else if ( ss_other.is_input(0) ) { Point_handle p0 = hm[ ss_other.source_of_supporting_site() ]; Point_handle p1 = hm[ ss_other.target_of_supporting_site() ]; Point_handle p4 = hm[ ss_other.source_of_crossing_site(1) ]; Point_handle p5 = hm[ ss_other.target_of_crossing_site(1) ]; return st_.construct_storage_site_2_object()(p0, p1, p4, p5, true); } else if ( ss_other.is_input(1) ) { Point_handle p0 = hm[ ss_other.source_of_supporting_site() ]; Point_handle p1 = hm[ ss_other.target_of_supporting_site() ]; Point_handle p2 = hm[ ss_other.source_of_crossing_site(0) ]; Point_handle p3 = hm[ ss_other.target_of_crossing_site(0) ]; return st_.construct_storage_site_2_object()(p0, p1, p2, p3, false); } else { Point_handle p0 = hm[ ss_other.source_of_supporting_site() ]; Point_handle p1 = hm[ ss_other.target_of_supporting_site() ]; Point_handle p2 = hm[ ss_other.source_of_crossing_site(0) ]; Point_handle p3 = hm[ ss_other.target_of_crossing_site(0) ]; Point_handle p4 = hm[ ss_other.source_of_crossing_site(1) ]; Point_handle p5 = hm[ ss_other.target_of_crossing_site(1) ]; return st_.construct_storage_site_2_object()(p0, p1, p2, p3, p4, p5); } } else { if ( ss_other.is_input() ) { Point_handle p0 = hm[ ss_other.point() ]; return st_.construct_storage_site_2_object()(p0); } else { Point_handle p2 = hm[ ss_other.source_of_supporting_site(0) ]; Point_handle p3 = hm[ ss_other.target_of_supporting_site(0) ]; Point_handle p4 = hm[ ss_other.source_of_supporting_site(1) ]; Point_handle p5 = hm[ ss_other.target_of_supporting_site(1) ]; return st_.construct_storage_site_2_object()(p2, p3, p4, p5); } } } template<class Gt, class ST, class D_S, class LTag> void Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>:: copy(Segment_Delaunay_graph_2& other) { // first copy the point container pc_ = other.pc_; // copy storage traits st_ = other.st_; // first create a map between the old point handles and the new ones Handle_map hm; Point_handle it_other = other.pc_.begin(); Point_handle it_this = pc_.begin(); for (; it_other != other.pc_.end(); ++it_other, ++it_this) { hm.insert( Point_handle_pair(it_other, it_this) ); } copy(other, hm); } template<class Gt, class ST, class D_S, class LTag> void Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>:: copy(Segment_Delaunay_graph_2& other, Handle_map& hm) { // second, copy the site representation info for the input sites // using the correct handles (i.e., the handles from the new point // container isc_.clear(); typename Input_sites_container::iterator iit_other = other.isc_.begin(); for (; iit_other != other.isc_.end(); ++iit_other) { Site_rep_2 old_srep = *iit_other; Site_rep_2 new_srep( hm[boost::tuples::get<0>(old_srep)], hm[boost::tuples::get<1>(old_srep)], boost::tuples::get<2>(old_srep) ); isc_.insert( new_srep ); } CGAL_assertion( pc_.size() == other.pc_.size() ); CGAL_assertion( isc_.size() == other.isc_.size() ); #ifndef CGAL_NO_ASSERTIONS { Point_handle it_other = other.pc_.begin(); Point_handle it_this = pc_.begin(); for (; it_other != other.pc_.end(); ++it_other, ++it_this) { CGAL_assertion( *it_other == *it_this ); } } #endif // then copy the diagram DG::operator=(other); // now we have to update the sotrage sites in each vertex of the // diagram and also update the // then update the storage sites for each vertex Intersections_tag itag; Finite_vertices_iterator vit_other = other.finite_vertices_begin(); Finite_vertices_iterator vit_this = finite_vertices_begin(); for (; vit_other != other.finite_vertices_end(); vit_other++, vit_this++) { Storage_site_2 ss_other = vit_other->storage_site(); #ifndef CGAL_NO_ASSERTIONS Storage_site_2 ss_this = vit_this->storage_site(); if ( ss_other.is_segment() ) { CGAL_assertion( ss_this.is_segment() ); CGAL_assertion( same_segments(ss_this.site(), ss_other.site()) ); } else { CGAL_assertion( ss_this.is_point() ); CGAL_assertion( same_points(ss_this.site(), ss_other.site()) ); } #endif Storage_site_2 new_ss_this = copy_storage_site(ss_other, hm, itag); vit_this->set_site( new_ss_this ); } } //-------------------------------------------------------------------- //-------------------------------------------------------------------- // getting endpoints of segments //-------------------------------------------------------------------- //-------------------------------------------------------------------- template<class Gt, class ST, class D_S, class LTag> typename Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>::Vertex_handle Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>:: first_endpoint_of_segment(const Vertex_handle& v) const { CGAL_assertion( v->is_segment() ); Site_2 fe = v->site().source_site(); Vertex_circulator vc_start = incident_vertices(v); Vertex_circulator vc = vc_start; do { // Vertex_handle vv(vc); if ( !is_infinite(vc) && vc->is_point() ) { if ( same_points(fe, vc->site()) ) { return Vertex_handle(vc); } } vc++; } while ( vc != vc_start ); // we should never reach this point CGAL_error(); return Vertex_handle(); } template<class Gt, class ST, class D_S, class LTag> typename Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>::Vertex_handle Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>:: second_endpoint_of_segment(const Vertex_handle& v) const { CGAL_assertion( v->is_segment() ); Site_2 fe = v->site().target_site(); Vertex_circulator vc_start = incident_vertices(v); Vertex_circulator vc = vc_start; do { // Vertex_handle vv(vc); if ( !is_infinite(vc) && vc->is_point() ) { if ( same_points(fe, vc->site()) ) { return Vertex_handle(vc); } } vc++; } while ( vc != vc_start ); // we should never reach this point CGAL_error(); return Vertex_handle(); } //-------------------------------------------------------------------- //-------------------------------------------------------------------- // file I/O //-------------------------------------------------------------------- //-------------------------------------------------------------------- template<class Gt, class ST, class D_S, class LTag> void Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>:: file_output(std::ostream& os, const Storage_site_2& t, Point_handle_mapper& P) const { CGAL_precondition( t.is_defined() ); if ( t.is_point() ) { // 0 for point os << 0; if ( is_ascii(os) ) { os << ' '; } if ( t.is_input() ) { // 0 for input os << 0; if ( is_ascii(os) ) { os << ' '; } os << P[t.point()]; } else { // 1 for non-input os << 1; if ( is_ascii(os) ) { os << ' '; } os << P[t.source_of_supporting_site(0)]; if ( is_ascii(os) ) { os << ' '; } os << P[t.target_of_supporting_site(0)]; if ( is_ascii(os) ) { os << ' '; } os << P[t.source_of_supporting_site(1)]; if ( is_ascii(os) ) { os << ' '; } os << P[t.target_of_supporting_site(1)]; } } else { // t is a segment // 1 for segment os << 1; if ( is_ascii(os) ) { os << ' '; } if ( t.is_input() ) { // 0 for input os << 0; if ( is_ascii(os) ) { os << ' '; } os << P[t.source_of_supporting_site()]; if ( is_ascii(os) ) { os << ' '; } os << P[t.target_of_supporting_site()]; } else if ( t.is_input(0) ) { // 1 for input source os << 1; if ( is_ascii(os) ) { os << ' '; } os << P[t.source_of_supporting_site()]; if ( is_ascii(os) ) { os << ' '; } os << P[t.target_of_supporting_site()]; if ( is_ascii(os) ) { os << ' '; } os << P[t.source_of_crossing_site(1)]; if ( is_ascii(os) ) { os << ' '; } os << P[t.target_of_crossing_site(1)]; } else if ( t.is_input(1) ) { // 2 for input target os << 2; if ( is_ascii(os) ) { os << ' '; } os << P[t.source_of_supporting_site()]; if ( is_ascii(os) ) { os << ' '; } os << P[t.target_of_supporting_site()]; if ( is_ascii(os) ) { os << ' '; } os << P[t.source_of_crossing_site(0)]; if ( is_ascii(os) ) { os << ' '; } os << P[t.target_of_crossing_site(0)]; } else { // 3 for non-input src & trg os << 3; if ( is_ascii(os) ) { os << ' '; } os << P[t.source_of_supporting_site()]; if ( is_ascii(os) ) { os << ' '; } os << P[t.target_of_supporting_site()]; if ( is_ascii(os) ) { os << ' '; } os << P[t.source_of_crossing_site(0)]; if ( is_ascii(os) ) { os << ' '; } os << P[t.target_of_crossing_site(0)]; if ( is_ascii(os) ) { os << ' '; } os << P[t.source_of_crossing_site(1)]; if ( is_ascii(os) ) { os << ' '; } os << P[t.target_of_crossing_site(1)]; } } } template<class Gt, class ST, class D_S, class LTag> void Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>:: file_input(std::istream& is, Storage_site_2& t, const Point_handle_vector& P, const Tag_false&) const { int type, input; is >> type >> input; CGAL_assertion( type == 0 || type == 1 ); CGAL_assertion( input == 0 ); if ( type == 0 ) { // we have an input point size_type p; is >> p; t = st_.construct_storage_site_2_object()(P[p]); } else { CGAL_assertion( type == 1 ); // we have an input segment size_type p1, p2; is >> p1 >> p2; t = st_.construct_storage_site_2_object()(P[p1], P[p2]); } } template<class Gt, class ST, class D_S, class LTag> void Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>:: file_input(std::istream& is, Storage_site_2& t, const Point_handle_vector& P, const Tag_true&) const { int type, input; is >> type >> input; CGAL_assertion( type == 0 || type == 1 ); CGAL_assertion( input >= 0 && input <= 3 ); if ( type == 0 ) { // we have a point if ( input == 0 ) { // we have an input point size_type p; is >> p; t = st_.construct_storage_site_2_object()(P[p]); } else { // we have a point that is the intersection of two segments CGAL_assertion( input == 1 ); size_type p1, p2, q1, q2; is >> p1 >> p2 >> q1 >> q2; t = st_.construct_storage_site_2_object()(P[p1], P[p2], P[q1], P[q2]); } } else { // we have a segment CGAL_assertion( type == 1 ); if ( input == 0 ) { // we have an input segment size_type p1, p2; is >> p1 >> p2; t = st_.construct_storage_site_2_object()(P[p1], P[p2]); } else if ( input < 3 ) { // we have a segment whose source or target is input but not both size_type p1, p2, q1, q2; is >> p1 >> p2 >> q1 >> q2; t = st_.construct_storage_site_2_object()(P[p1], P[p2], P[q1], P[q2], input == 1); } else { // we have a segment whose neither its source nor its target is input CGAL_assertion( input == 3 ); size_type p1, p2, q1, q2, r1, r2; is >> p1 >> p2 >> q1 >> q2 >> r1 >> r2; t = st_.construct_storage_site_2_object()(P[p1], P[p2], P[q1], P[q2], P[r1], P[r2]); } } } //-------------------------------------------------------------------- template<class Gt, class ST, class D_S, class LTag> void Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>:: file_output(std::ostream& os, Point_handle_mapper& P, bool print_point_container) const { // ouput to a file size_type n = this->_tds.number_of_vertices(); size_type m = this->_tds.number_of_full_dim_faces(); CGAL_assertion( n >= 1 ); if( is_ascii(os) ) { os << n << ' ' << m << ' ' << dimension() << std::endl; } else { os << n << m << dimension(); } // points in point container and input sites container if ( print_point_container ) { if ( is_ascii(os) ) { os << std::endl; } os << pc_.size(); if ( is_ascii(os) ) { os << std::endl; } for (const_Point_handle ph = pc_.begin(); ph != pc_.end(); ++ph) { os << *ph; if ( is_ascii(os) ) { os << std::endl; } } // print the input sites container if ( is_ascii(os) ) { os << std::endl; } os << isc_.size(); if ( is_ascii(os) ) { os << std::endl; } for (typename Input_sites_container::const_iterator it = isc_.begin(); it != isc_.end(); ++it) { os << P[boost::tuples::get<0>(*it)]; if ( is_ascii(os) ) { os << " "; } os << P[boost::tuples::get<1>(*it)]; if ( is_ascii(os) ) { os << std::endl; } } } std::map<Vertex_handle,size_type> V; std::map<Face_handle,size_type> F; // first vertex (infinite vertex) size_type inum = 0; V[infinite_vertex()] = inum++; // finite vertices if (is_ascii(os)) os << std::endl; for (Finite_vertices_iterator vit = finite_vertices_begin(); vit != finite_vertices_end(); ++vit) { V[vit] = inum++; // os << vit->site(); file_output(os, vit->storage_site(), P); // write non-combinatorial info of the vertex // os << *vit ; if ( is_ascii(os) ) { os << std::endl; } } if ( is_ascii(os) ) { os << std::endl; } // vertices of the faces inum = 0; int dim = (dimension() == -1 ? 1 : dimension() + 1); for(All_faces_iterator fit = all_faces_begin(); fit != all_faces_end(); ++fit) { F[fit] = inum++; for(int j = 0; j < dim ; ++j) { os << V[ fit->vertex(j) ]; if( is_ascii(os) ) { os << ' '; } } // write non-combinatorial info of the face // os << *fit ; if( is_ascii(os) ) { os << std::endl; } } if( is_ascii(os) ) { os << std::endl; } // neighbor pointers of the faces for( All_faces_iterator it = all_faces_begin(); it != all_faces_end(); ++it) { for(int j = 0; j < dimension()+1; ++j){ os << F[ it->neighbor(j) ]; if( is_ascii(os) ) { os << ' '; } } if( is_ascii(os) ) { os << std::endl; } } if ( is_ascii(os) ) { os << std::endl; } } template<class Gt, class ST, class D_S, class LTag> void Segment_Delaunay_graph_2<Gt,ST,D_S,LTag>:: file_input(std::istream& is, bool read_handle_vector, Point_handle_vector& P) { //input from file size_type n, m; int d; is >> n >> m >> d; CGAL_assertion( n >= 1 ); size_type i = 0; Storage_site_2 ss; if ( read_handle_vector ) { pc_.clear(); size_type np; is >> np; for (; i < np; i++) { Point_2 p; is >> p; std::pair<Point_handle,bool> res = pc_.insert(p); P.push_back(res.first); CGAL_assertion( P[i] == res.first ); } // now read the input sites container isc_.clear(); size_type nisc; is >> nisc; int id1, id2; for (i = 0; i < nisc; i++) { is >> id1 >> id2; isc_.insert( Site_rep_2(P[id1], P[id2], id1 == id2) ); } } if ( n == 1 ) { CGAL_assertion( d == -1 ); if ( number_of_vertices() > 0 ) { clear(); } return; } if ( n == 2 ) { CGAL_assertion( d == 0 ); if ( number_of_vertices() > 0 ) { clear(); } file_input(is, ss, P, Intersections_tag()); insert_first(ss, *ss.point()); return; } if ( n == 3 ) { CGAL_assertion( d == 1 ); if ( number_of_vertices() > 0 ) { clear(); } file_input(is, ss, P, Intersections_tag()); insert_first(ss, *ss.point()); file_input(is, ss, P, Intersections_tag()); insert_second(ss, *ss.point()); return; } if (this->_tds.number_of_vertices() != 0) { this->_tds.clear(); } this->_tds.set_dimension(d); std::vector<Vertex_handle> V(n); std::vector<Face_handle> F(m); // first vertex (infinite vertex) V[0] = this->_tds.create_vertex(); this->set_infinite_vertex(V[0]); i = 1; // read vertices for (; i < n; ++i) { V[i] = this->_tds.create_vertex(); file_input(is, ss, P, Intersections_tag()); V[i]->set_site(ss); // read non-combinatorial info of the vertex // is >> *(V[i]); } // Creation of the faces int index; int dim = (dimension() == -1 ? 1 : dimension() + 1); for (i = 0; i < m; ++i) { F[i] = this->_tds.create_face(); for (int j = 0; j < dim ; ++j){ is >> index; F[i]->set_vertex(j, V[index]); // The face pointer of vertices is set too often, // but otherwise we had to use a further map V[index]->set_face(F[i]); } // read in non-combinatorial info of the face // is >> *(F[i]) ; } // Setting the neighbor pointers for (i = 0; i < m; ++i) { for (int j = 0; j < dimension()+1; ++j){ is >> index; F[i]->set_neighbor(j, F[index]); } } } } //namespace CGAL // EOF
[ "cmrose@lbl.gov" ]
cmrose@lbl.gov
f931c298661803dab5720eca3beca6534316f49a
90b1a86c16b0f7f99cb0bff3f05476dd95bd8697
/source/kdpHistogram.cpp
055c4523c10f33db577e68a479d52f6c7d326f86
[]
no_license
keith-pedersen/libkdp
ade52b70630c2749e10b49c342ef4468f5daa081
99d26540f304ec94e76a967e7b8292b1fc6fd829
refs/heads/master
2020-03-24T16:40:23.029467
2019-01-27T00:40:38
2019-01-27T00:40:38
142,832,010
0
0
null
null
null
null
UTF-8
C++
false
false
37,024
cpp
// Copyright (C) 2016-2018 by Keith Pedersen (Keith.David.Pedersen@gmail.com) // 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 "kdpHistogram.hpp" #include <fstream> #include <limits> #include <iostream> #include <assert.h> #include <algorithm> /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ____ | _ \ __ _ _ __ __ _ ___ | |_) / _` | '_ \ / _` |/ _ \ | _ < (_| | | | | (_| | __/ |_| \_\__,_|_| |_|\__, |\___| |___/ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ template<typename edge_t> kdp::Range<edge_t>::Range():Range(0., 1.) {} template<typename edge_t> kdp::Range<edge_t>::Range(edge_t const min_in, edge_t const max_in): min(min_in), max(max_in) {CheckSortedAndNumeric();} template<typename edge_t> kdp::Range<edge_t>::Range(std::initializer_list<edge_t> const& init) { if(init.size() not_eq 2) throw std::invalid_argument("|Range| initializer_list must have 2 values"); min = *init.begin(); max = *(init.begin() + 1); CheckSortedAndNumeric(); } template<typename edge_t> bool kdp::Range<edge_t>::operator == (Range const& that) const { return (this->min == that.min) and (this->max == that.max); } template<typename edge_t> void kdp::Range<edge_t>::CheckSortedAndNumeric() { if(min > max) throw std::invalid_argument("|Range| min > max"); if(std::isnan(min)) throw std::invalid_argument("|Range| min = nan"); if(std::isnan(max)) throw std::invalid_argument("|Range| max = nan"); } template class kdp::Range<float>; template class kdp::Range<double>; /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ _____ _ _ _ ____ | ___(_)_ __ (_) |_ ___| _ \ __ _ _ __ __ _ ___ | |_ | | '_ \| | __/ _ \ |_) / _` | '_ \ / _` |/ _ \ | _| | | | | | | || __/ _ < (_| | | | | (_| | __/ |_| |_|_| |_|_|\__\___|_| \_\__,_|_| |_|\__, |\___| |___/ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ template<typename edge_t> kdp::FiniteRange<edge_t>::FiniteRange(edge_t const min_in, edge_t const max_in): Range<edge_t>(min_in, max_in) {CheckFinite();} template<typename edge_t> kdp::FiniteRange<edge_t>::FiniteRange(std::initializer_list<edge_t> const& init): Range<edge_t>(init) {CheckFinite();} template<typename edge_t> void kdp::FiniteRange<edge_t>::CheckFinite() { if(std::isinf(this->min)) throw std::invalid_argument("|Range| min = -inf, must be finite"); if(std::isinf(this->max)) throw std::invalid_argument("|Range| max = inf, must be finite"); } template class kdp::FiniteRange<float>; template class kdp::FiniteRange<double>; /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ____ _ ____ | __ )(_)_ __ / ___| _ __ ___ ___ ___ | _ \| | '_ \\___ \| '_ \ / _ \/ __/ __| | |_) | | | | |___) | |_) | __/ (__\__ \ |____/|_|_| |_|____/| .__/ \___|\___|___/ |_| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ kdp::edge_t const kdp::BinSpecs::INF = std::numeric_limits<edge_t>::infinity(); // numBins ctor kdp::BinSpecs::BinSpecs(std::string const& name_in, size_t const numBins_in, std::initializer_list<edge_t> const& range_init, UniformBinType const binType_in): name(name_in), numBins(numBins_in), range(), // Set below, to catch and rethrow exceptions, appending name binWidth(-1.), // Set below, to keep conditional out of init list binType(static_cast<BinType>(static_cast<int>(binType_in))), pinned(PinnedEdge::BOTH) // Only option, given numBins { try { if(numBins == 0) throw std::invalid_argument("not enough bins supplied"); range = range_init; UniformSanityChecks(); binWidth = ((binType == BinType::UNIFORM) ? (range.max - range.min) : std::log(range.max/range.min))/edge_t(numBins); // LOG_UNIFORM FillEdges(false); // fromWidth = false } catch(std::exception& e) { ExceptionHandler(e); } } // width/scale ctor kdp::BinSpecs::BinSpecs(std::string const& name_in, std::initializer_list<edge_t> const& range_init, edge_t widthOrScale, UniformBinType const binType_in, PinnedEdge const pinned_in): name(name_in), numBins(1), // Default value, will determine in FillEdges range(), // Set below, to catch and rethrow exceptions, appending name binWidth(-1.), // Set below, to keep conditional out of init list binType(static_cast<BinType>(static_cast<int>(binType_in))), pinned(pinned_in) { try { range = range_init; UniformSanityChecks(); binWidth = (binType == BinType::UNIFORM) ? widthOrScale : std::log(widthOrScale); FillEdges(true); // fromWidth = true } catch(std::exception& e) { ExceptionHandler(e); } } // NON_UNIFORM ctor kdp::BinSpecs::BinSpecs(std::string const& name_in, std::vector<edge_t> const& edges_in): name(name_in), numBins(edges_in.size() - 1), // this could be very large if edges is empty range(),// If edges_in is empty, trying to construct range would cause SEG_FAULT binWidth(-1.), // nonsensical value binType(BinType::NON_UNIFORM), pinned(PinnedEdge::BOTH) // Only option, given edges { try { if(edges_in.size() < 2) throw std::invalid_argument("< 2 edges supplied, cannot form a bin"); else range = {edges_in.front(), edges_in.back()}; SharedSanityChecks(); // Verify the supplied edges are all finite // DO NOT attempt to fix anything, let the user decide how to fix it // (that way they are not surprised about this behavior under the hood) { auto prevEdge = edges_in.begin(); for(auto thisEdge = prevEdge + 1; thisEdge not_eq edges_in.end(); ++prevEdge, ++thisEdge) { // The duplicate check will only find all duplicates in a sorted list // But an unsorted list will fail the sorting test if(*thisEdge == *prevEdge) throw std::invalid_argument("edge list has duplicates"); if(*thisEdge < *prevEdge) throw std::invalid_argument("edge list not sorted"); if(std::isinf(*thisEdge)) throw std::invalid_argument("supplied edge is +/-inf"); if(std::isnan(*thisEdge)) throw std::invalid_argument("supplied edge is nan"); } } // Copy in input edges, padding infinity on each side edges.reserve(numBins + 2); edges.push_back(-INF); edges.insert(edges.end(), edges_in.begin(), edges_in.end()); edges.push_back(INF); } catch(std::exception& e) { ExceptionHandler(e); } } // Define this, otherwise -Winline complains about not inlining it kdp::BinSpecs::~BinSpecs(){} // Sanity checks used by all three ctors void kdp::BinSpecs::SharedSanityChecks() { if(numBins > BinSpecs::MAX_BINS) throw std::invalid_argument(std::to_string(numBins) + " = too many bins supplied"); } // Sanity checks only used by UNIFORM/NON_UNIFORM void kdp::BinSpecs::UniformSanityChecks() { if(range.min == range.max) // FiniteRange will accept this, but we can't throw std::invalid_argument("min == max, cannot create bins"); SharedSanityChecks(); } // When width/scale is supplied, make sure the resulting numBins is sensible void kdp::BinSpecs::CalculatedNumBinsSanityChecks() { if(numBins == 0) throw std::invalid_argument("Zero bins from width/scale ... this shouldn't happen (code logic error)"); else if(numBins > BinSpecs::MAX_BINS) throw std::invalid_argument(std::to_string(numBins) + " = too many bins from width/scale"); } bool kdp::BinSpecs::operator==(BinSpecs const& that) const { if(this == &that) return true; else { // There must be the same number of bins spanning the same range if((this->numBins == that.numBins) and (this->range == that.range)) { // If either is NON_UNIFORM, the only way to be absolutely sure // is to check edge by edge if((this->binType == BinType::NON_UNIFORM) or (that.binType == BinType::NON_UNIFORM)) { auto itThis = this->edges.begin(); auto itThat = that.edges.begin(); // Keep iterating while both edges are the same and we // haven't hit the end of either list while( (itThis not_eq this->edges.end()) and (itThat not_eq that.edges.end()) and (*itThis == *itThat)) {++itThis; ++itThat;} // If all edges are the same, then both iterators should be // at the end of their lists return (itThis == this->edges.end()) and (itThat == that.edges.end()); } else { // Otherwise, if both are uniform, then as long as they have // identical binWidths and binTypes, they're the same // (even if pinned is different). This is due to the algorithm // which fills the bins, since it only depends on // min, max, numBins, binWidth and binType return ((this->binWidth == that.binWidth) and (this->binType == that.binType)); } } else return false; } } void kdp::BinSpecs::FillEdges(bool const fromWidth) { switch(binType) { case BinType::UNIFORM: if(binWidth <= 0.) throw std::invalid_argument("bin width must be > 0"); Fill_Uniform_Edges(fromWidth); break; case BinType::LOG_UNIFORM: if(range.min <= 0.) throw std::invalid_argument("for LOG_UNIFORM, lower edge must be >= 0"); if(binWidth <= 0.) throw std::invalid_argument("bin scale must be > 1."); Fill_Uniform_Edges(fromWidth); break; default: throw std::runtime_error("BinSpecs: no code to handle a new BinType (my mistake)"); break; } } // ALWAYS FILL UNIFORM EDGES USING (min*i + max*(N-i)) scheme // Introduces rounding error in every edge, but it's always Order(epsilon) // (instead of accumulating as edges are defined incrementally) void kdp::BinSpecs::Fill_Uniform_Edges(bool const fromWidth) { // Critical ASSUMPTION throughout: // if binType != UNIFORM, then binType == LOG_UNIFORM if(fromWidth) { edge_t& min = range.min; edge_t& max = range.max; const edge_t rangeWidth = (binType == BinType::UNIFORM) ? (max - min) : std::log(max/min); if(pinned == PinnedEdge::BOTH) { // If pinning of both edges requested, // change the width by first rounding to an integer number of bins numBins = std::max(size_t(std::round(rangeWidth/binWidth)), size_t(1)); binWidth = rangeWidth/edge_t(numBins); } else { // Otherwise, use just enough bins to accommodate rangeWidth numBins = std::ceil(rangeWidth/binWidth); // Now move min or max if(pinned == PinnedEdge::LEFT) { max = (binType == BinType::UNIFORM) ? (min + numBins*binWidth) : (min * std::exp(numBins*binWidth)); } else if(pinned == PinnedEdge::RIGHT) { min = (binType == BinType::UNIFORM) ? (max - numBins*binWidth) : (max * std::exp(-numBins*binWidth)); } } CalculatedNumBinsSanityChecks(); } const edge_t minLoop = (binType == BinType::UNIFORM) ? range.min : std::log(range.min); const edge_t maxLoop = (binType == BinType::UNIFORM) ? range.max : std::log(range.max); // Reserve 2 extra slots for -inf/inf edges.reserve(numBins + 2); // Pad with infinity before/after edges.push_back(-INF); // For LOG_UNIFORM, add the edge for the zero bin (pseudo-underflow) if(binType == BinType::LOG_UNIFORM) edges.push_back(0.); // Manually push_back min/max, to avoid rounding error edges.push_back(range.min); // Even if using bin width, define edges in terms of num bins // This prevents rounding error from accumulating, so even though // the bins may have slightly uneven width, they are more likely // to exist in the right place. { size_t minCounter = numBins - 1; for(size_t maxCounter = 1; maxCounter < numBins; ++maxCounter, --minCounter) { edge_t thisEdge = (minLoop*minCounter + maxLoop*maxCounter)/edge_t(numBins); if(binType == BinType::LOG_UNIFORM) thisEdge = std::exp(thisEdge); edges.push_back(thisEdge); } } edges.push_back(range.max); edges.push_back(INF); // Account for automatic addition of the zero bin for LOG_UNIFORM // (this must be done here, after the loop, // otherwise too many edges will be added in the loop) if(binType == BinType::LOG_UNIFORM) ++numBins; } void kdp::BinSpecs::ExceptionHandler(std::exception& except) { throw std::invalid_argument("BinSpecs: (" + name + ") ... " + except.what()); } /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ __ __ _ _ _ _____ \ \ / /__(_) __ _| |__ | |_| ____|_ __ _ __ ___ _ __ \ \ /\ / / _ \ |/ _` | '_ \| __| _| | '__| '__/ _ \| '__| \ V V / __/ | (_| | | | | |_| |___| | | | | (_) | | \_/\_/ \___|_|\__, |_| |_|\__|_____|_| |_| \___/|_| |___/ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ kdp::WeightError& kdp::WeightError::operator /= (WeightError const& that) { // We need to avoid 0 / 0 ... this way also catches 0/something if(this->weight > 0.) { // For * and /, *relative* errors add in quadrature // dz/z = sqrt((dx/x)**2 + (dy/y)**2) (x=this, y=that, z = x/y) // dz**2 = (x**2/y**2)*(dx**2/x**2 + dy**2/y**2) // = (dx**2/y**2 + dy**2*x**2/y**4) // = (dx**2 + dy**2*x**2/y**2)/y**2 // Note: a**2/b**2 is more accurate than (a/b)**2 this->error2 = std::fma(that.error2, kdp::Squared(this->weight)/kdp::Squared(that.weight), this->error2)/ kdp::Squared(that.weight); this->weight = this->weight / that.weight; } return *this; } //////////////////////////////////////////////////////////////////////// kdp::WeightError& kdp::WeightError::operator += (WeightError const& that) { // For + and -, *absolute* errors add in quadrature // dz**2 = dx**2 + dy**2 this->error2 += that.error2; this->weight += that.weight; return *this; } /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ _ ______ ____ _ _ _ _ __ __ | |/ / _ \| _ \| | | (_)___| |_ __\ \ / /__ ___ | ' /| | | | |_) | |_| | / __| __/ _ \ \ / / _ \/ __| | . \| |_| | __/| _ | \__ \ || (_) \ V / __/ (__ |_|\_\____/|_| |_| |_|_|___/\__\___/ \_/ \___|\___| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ template<class content> content& kdp::HistoVec<content>::FindBin(edge_t const val) { if(val >= binSpecs.range.max) return this->back(); else { auto bin = this->begin(); if(val >= binSpecs.range.min) { if(binSpecs.binType == BinType::NON_UNIFORM) { /* For non-uniform bins, use std::upper_bound * (first edge > val, which finds the upper edge, so we have to subtract 1). * If no value compares greater, we will land on the overflow bin. * This assumes that upper_bound has the fastest search algorithm * (knowing exactly when to transition from binary to linear search). * Not only is this a good assumption, testing reveals that upper_bound * can be up to twice as fast as the linear search it replaced. */ bin += (size_t(std::upper_bound(binSpecs.edges.cbegin(), binSpecs.edges.cend(), val) - binSpecs.edges.cbegin()) - 1lu); } else { auto leftEdge = minEdge; // For UNIFORM/LOG_UNIFORM bins, no need to search every edge // However, there might be rounding error while calculating the bin. // Start with the calculated/expected bin (minus 1, to catch rounding left error) // and search past it. This will catch bin shifts to the left or right. if(binSpecs.binType == BinType::UNIFORM) { leftEdge += (size_t((val - binSpecs.range.min)/binSpecs.binWidth) - 1); } else if(binSpecs.binType == BinType::LOG_UNIFORM) { ++bin; // minEdge skipped the zero bin // This is actually slower, if there are less than about 100 bins // But it has constant execution time, for larger number of bins leftEdge += (size_t(std::log(val/binSpecs.range.min)/binSpecs.binWidth) - 1); } // Keep moving the left edge until it is to our right // Because +inf is the final value in the edge list, // and we already checked for overflow, // we do not need an extra check to prevent running off the list while(val >= *leftEdge) ++leftEdge; bin += size_t(leftEdge - minEdge); } } else if((binSpecs.binType == BinType::LOG_UNIFORM) and (val >= 0.)) ++bin; // For LOG_UNIFORM, use the zero bin [0, min) assert(bin < this->end()); return *bin; } } template<class content> kdp::HistoVec<content>& kdp::HistoVec<content>::operator/=(HistoVec<content> const& that) { if(this->binSpecs not_eq that.binSpecs) throw std::runtime_error("HistoVec: Cannot divide, incompatible BinSpecs"); auto itDenom = that.begin(); for(auto itNumer = this->begin(); itNumer not_eq this->end(); ++itNumer, ++itDenom) { // This will call this function recursively until content = WeightError // This makes it extremely simple to divide multi-D histograms (*itNumer)/=(*itDenom); } return *this; } template class kdp::HistoVec<kdp::WeightError>; template class kdp::HistoVec<kdp::HistoVec<kdp::WeightError> >; /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ _ _ _ _ | \ | | ___ _ __ _ __ ___ __ _| (_)_______ | \| |/ _ \| '__| '_ ` _ \ / _` | | |_ / _ \ | |\ | (_) | | | | | | | | (_| | | |/ / __/ |_| \_|\___/|_| |_| |_| |_|\__,_|_|_/___\___| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ // Have to declare as kdp:operator, otherwise defined in global scope kdp::Normalize kdp::operator&(Normalize const lhs, Normalize const rhs) { return static_cast<Normalize> (static_cast<norm_t>(lhs) & static_cast<norm_t>(rhs)); } kdp::Normalize kdp::operator|(Normalize const lhs, Normalize const rhs) { return static_cast<Normalize> (static_cast<norm_t>(lhs) | static_cast<norm_t>(rhs)); } /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ _ ______ ____ _ _ _ _ _ | |/ / _ \| _ \| | | (_)___| |_ ___ __ _ _ __ __ _ _ __ ___ | |__ __ _ ___ ___ | ' /| | | | |_) | |_| | / __| __/ _ \ / _` | '__/ _` | '_ ` _ \ | '_ \ / _` / __|/ _ \ | . \| |_| | __/| _ | \__ \ || (_) | (_| | | | (_| | | | | | | | |_) | (_| \__ \ __/ |_|\_\____/|_| |_| |_|_|___/\__\___/ \__, |_| \__,_|_| |_| |_|___|_.__/ \__,_|___/\___| |___/ |_____| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ std::set<std::string> kdp::Histogram_base::fileNameMutex; kdp::Histogram_base::Histogram_base(std::string const& fileName_in, weight_t const totalWeight_in, weight_t const writeScale_in, Normalize const norm_in): fileName(fileName_in), totalWeight(totalWeight_in), writeScale(writeScale_in), norm(norm_in), written(false) { // If fileName is blank, then this is a non-writing histogram // (used only for reading or adding to other histograms) if(fileName_in.size()) { // nameMutex resturns false in the 2nd position if the name has already been used if(not (fileNameMutex.insert(fileName).second)) RTExcept("another KDPHistogram is already using this fileName"); // Clear the file, if it already exists, and ensure we have write privileges if(not(std::ofstream(fileName.c_str(), std::ios::out | std::ios::trunc))) RTExcept("cannot open file (" + fileName +") for writing"); // Now remove the empty file, in case the histogram isn't used // (because then it won't be written, which will be easier to detect // if there is no file there std::remove(fileName.c_str()); } } void kdp::Histogram_base::RTExcept(std::string const& info) const { throw std::runtime_error(ExceptionPrefix() + info); } std::string kdp::Histogram_base::ExceptionPrefix() const { return "KDPHistogram: (" + fileName + ") ... "; } void kdp::Histogram_base::CheckWeightError(weight_t const weight, weight_t const error) const { if(std::isinf(weight)) RTExcept("binning weight is inf"); if(std::isnan(weight)) RTExcept("binning weight is nan"); if(weight <= 0.) RTExcept("binning weight is <= 0"); if(std::isinf(error)) RTExcept("binning error is inf"); if(std::isnan(error)) RTExcept("binning error is nan"); if(error < 0.) RTExcept("binning error is < 0"); } // This must be called from the derived classes, because Write is virtual void kdp::Histogram_base::AutomaticWrite() { try { // Don't erase fileName, so we don't screw ourselves within a single run // fileNameMutex.erase(fileName); // Write if no write was manual requested, and if weight has been binned, // AND if we have been supplied a non-empty fileName if((not written) and (totalWeight > 0.) and bool(fileName.size())) this->Write(); // This should not throw an exception, but it might } catch(std::exception const& e) { std::cerr << "Error during Histogram1 deconstruction (probably Write())\n\n"; std::cerr << e.what(); } } void kdp::Histogram_base::WriteHeader(std::ofstream& outFile, std::string const& className) { const std::string blankLine = "#\n"; char outBuff[1024]; // should be long enough for one line (ASSUMPTION) outFile << "# Histogram generated by (" + className + "), "; outFile << "in a format easily recognized by gnuplot.\n"; outFile << blankLine; sprintf(outBuff, "# Total weight binned: %.16e \n", totalWeight); outFile << outBuff; outFile << blankLine; if(bool(norm & Normalize::UNITARY)) { outFile << "# histogram is UNITARY (bin weights, including under/over, "; outFile << "are divided by total weight)\n"; } if(bool(norm & Normalize::INTEGRATABLE)) { outFile << "# histogram is INTEGRATEABLE (bins weights divided by bin width)\n"; } if(norm == Normalize::PDF) { outFile << "# ... therefore histogram is a probability distribution (PDF)\n"; } outFile << blankLine; } /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ _ ______ ____ _ _ _ _ _ | |/ / _ \| _ \| | | (_)___| |_ ___ __ _ _ __ __ _ _ __ ___ / | | ' /| | | | |_) | |_| | / __| __/ _ \ / _` | '__/ _` | '_ ` _ \| | | . \| |_| | __/| _ | \__ \ || (_) | (_| | | | (_| | | | | | | | |_|\_\____/|_| |_| |_|_|___/\__\___/ \__, |_| \__,_|_| |_| |_|_| |___/ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ const std::string kdp::Histogram1::FILE_EXTENSION = ".histo1D"; // An empty set of active names // Private ctor, for constructing a full object kdp::Histogram1::Histogram1(std::string const& name, weight_t const totalWeight_in, weight_t const writeScale_in, Normalize const norm_in, HistoVec<WeightError>&& disowned): Histogram_base(name + Histogram1::FILE_EXTENSION, totalWeight_in, writeScale_in, norm_in), hist(std::move(disowned)) {} // ctor given writeScale kdp::Histogram1::Histogram1(std::string const& name, BinSpecs const& xBinSpecs, weight_t const writeScale_in, Normalize const norm_in): Histogram1(name, 0., writeScale_in, norm_in, std::move(HistoVec<WeightError>(xBinSpecs))) {} // ctor given norm kdp::Histogram1::Histogram1(std::string const& name, BinSpecs const& xBinSpecs, Normalize const norm_in): Histogram1(name, xBinSpecs, 1., norm_in) {} kdp::Histogram1::Histogram1(BinSpecs const& xBinSpecs, Normalize const norm_in): Histogram_base(std::string(), 0., 1., norm_in), hist(xBinSpecs) {} void kdp::Histogram1::Fill(edge_t const x, weight_t const weight, weight_t const error) { // x can be infinite, but it cannot be nan if(std::isnan(x)) RTExcept("trying to bin nan (x)"); CheckWeightError(weight, error); totalWeight += weight; WeightError& bin = hist.FindBin(x); bin.weight += weight; bin.error2 += error*error; } kdp::Histogram1& kdp::Histogram1::operator += (Histogram1 const& that) { // Cannot divide histograms unless they have identical BinSpecs if(this->hist.binSpecs not_eq that.hist.binSpecs) RTExcept("Cannot add (" + that.fileName + ") to (" + this->fileName + ") ... incompatible bin specs."); for(size_t i = 0; i < hist.size(); ++i) hist[i] += that.hist[i]; totalWeight += that.totalWeight; return *this; } // Divide two histograms to create a new histogram with their ratio void kdp::Histogram1::WriteRatio(Histogram1 const& that, std::string const& newName) const { // Cannot divide histograms unless they have identical BinSpecs if(this->hist.binSpecs not_eq that.hist.binSpecs) RTExcept("Cannot divide (" + this->fileName + ") by (" + that.fileName + ") ... incompatible bin specs."); //HistoVec<WeightError> ratio = this->hist; auto ratio = this->hist; ratio /= that.hist; // Create and immediately destroy (and write) the histogram // Pass a unit weight (no normalization, so it won't change anything) // b/c histo won't auto-write unless it thinks something's there Histogram1 ratioHist(newName, 1., 1., Normalize::NO, std::move(ratio)); } void kdp::Histogram1::Write() { if(fileName.empty()) RTExcept("No file path supplied; nowhere to write"); // We already checked we could write to the file, // there are no exceptions to generate, and we shouldn't encounter any std::ofstream outFile; outFile.open(fileName.c_str(), std::ios::out | std::ios::trunc); if(outFile) { BinSpecs const& binSpecs = hist.binSpecs; std::vector<edge_t> edges = binSpecs.edges; assert(hist.size() == edges.size() - 1); const bool divideByWeight = bool(norm & Normalize::UNITARY); const bool divideByWidth = bool(norm & Normalize::INTEGRATABLE); const bool uniform = (binSpecs.binType == BinType::UNIFORM); const weight_t normWeight = divideByWeight ? totalWeight : 1.; char outBuff[1024]; // should be long enough for one line (ASSUMPTION) WriteHeader(outFile, "Histogram1"); if(uniform) { outFile << "# first/last bins are under/over, respectively \n\n"; // Change the edges we use, so we don't need fancy code edges.front() = binSpecs.range.min - binSpecs.binWidth; edges.back() = binSpecs.range.max + binSpecs.binWidth; } else // write under/overflow in the header { sprintf(outBuff, "# Under (wgt/err): %.16e %.16e \n", (writeScale * hist.front().weight) / normWeight, (writeScale * std::sqrt(hist.front().error2)) / normWeight); outFile << outBuff; sprintf(outBuff, "# Over (wgt/err): %.16e %.16e \n\n", (writeScale * hist.back().weight) / normWeight, (writeScale * std::sqrt(hist.back().error2)) / normWeight); outFile << outBuff; } const int uniformShift = (uniform ? 0 : 1); auto const endBin = hist.end() - uniformShift; auto leftEdge = edges.begin() + uniformShift; auto rightEdge = leftEdge + 1; outFile << "# x pdf(x) pdfError(x) cdf(x) pdf-error pdf+error\n"; weight_t cumulative = 0.; for(auto thisBin = hist.begin() + uniformShift; thisBin not_eq endBin; ++thisBin) { const weight_t thisWeight = thisBin->weight; const weight_t thisError = std::sqrt(thisBin->error2); const edge_t thisBinDenom = normWeight * (divideByWidth ? (*rightEdge - *leftEdge) : 1.); cumulative += thisWeight; sprintf(outBuff, "% .6e % .6e % .6e % .6e % .6e % .6e\n", 0.5*(*rightEdge + *leftEdge), (writeScale*thisWeight)/thisBinDenom, (writeScale*thisError)/thisBinDenom, cumulative/totalWeight, (writeScale*(thisWeight-thisError))/thisBinDenom, (writeScale*(thisWeight+thisError))/thisBinDenom); outFile << outBuff; leftEdge = rightEdge; ++rightEdge; } outFile.close(); written = true; } } /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ _ ______ ____ _ _ _ _ ____ | |/ / _ \| _ \| | | (_)___| |_ ___ __ _ _ __ __ _ _ __ ___ |___ \ | ' /| | | | |_) | |_| | / __| __/ _ \ / _` | '__/ _` | '_ ` _ \ __) | | . \| |_| | __/| _ | \__ \ || (_) | (_| | | | (_| | | | | | |/ __/ |_|\_\____/|_| |_| |_|_|___/\__\___/ \__, |_| \__,_|_| |_| |_|_____| |___/ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ const std::string kdp::Histogram2::FILE_EXTENSION = ".histo2D"; // An empty set of active names // Private ctor, for constructing a full object kdp::Histogram2::Histogram2(std::string const& name, weight_t const totalWeight_in, weight_t const writeScale_in, Normalize const norm_in, HistoVec<HistoVec<WeightError> >&& disowned): Histogram_base(name + Histogram2::FILE_EXTENSION, totalWeight_in, writeScale_in, norm_in), hist(std::move(disowned)) {} // Public ctor, through which all other public ctors flow kdp::Histogram2::Histogram2(std::string const& name, BinSpecs const& xBinSpecs, BinSpecs const& yBinSpecs, weight_t const writeScale_in, Normalize const norm_in): Histogram2(name, 0., writeScale_in, norm_in, std::move(HistoVec<HistoVec<WeightError> >(xBinSpecs, yBinSpecs))) {} // Minimal ctor (writeScale = 1., norm = PDF) kdp::Histogram2::Histogram2(std::string const& name, BinSpecs const& xBinSpecs, BinSpecs const& yBinSpecs, Normalize const norm_in): Histogram2(name, xBinSpecs, yBinSpecs, 1., norm_in) {} void kdp::Histogram2::Fill(edge_t const x, edge_t const y, weight_t const weight, weight_t const error) { if(std::isnan(x)) RTExcept("trying to bin nan (x)"); if(std::isnan(y)) RTExcept("trying to bin nan (y)"); CheckWeightError(weight, error); totalWeight += weight; WeightError& bin = hist.FindBin(x).FindBin(y); bin.weight += weight; bin.error2 += error*error; } // Divide two histograms to create a new histogram with their ratio void kdp::Histogram2::WriteRatio(Histogram2 const& that, std::string const& newName) const { // Cannot divide histograms unless they have identical BinSpecs if((this->hist.binSpecs not_eq that.hist.binSpecs) or (this->hist.front().binSpecs not_eq that.hist.front().binSpecs)) RTExcept("Cannot divide (" + this->fileName + ") by (" + that.fileName + ") ... incompatible bin specs."); //HistoVec<HistoVec<WeightError> > ratio = this->hist; auto ratio = this->hist; ratio /= that.hist; // Create and immediately destroy (and write) the histogram // Pass a unit weight, no normalization or writeScale, // but it won't auto-write unless it thinks something's there Histogram2 ratioHist(newName, 1., 1., Normalize::NO, std::move(ratio)); } void kdp::Histogram2::Write() { // We already checked we could write to the file, // there are no exceptions to generate, and we shouldn't encounter any std::ofstream outFile; outFile.open(fileName.c_str(), std::ios::out | std::ios::trunc); if(outFile) { BinSpecs const& binSpecsX = hist.binSpecs; BinSpecs const& binSpecsY = hist.front().binSpecs; std::vector<edge_t> edgesX = binSpecsX.edges; std::vector<edge_t> edgesY = binSpecsY.edges; const bool divideByWeight = bool(norm & Normalize::UNITARY); const bool divideByWidth = bool(norm & Normalize::INTEGRATABLE); const bool uniformX = (binSpecsX.binType == BinType::UNIFORM); const bool uniformY = (binSpecsY.binType == BinType::UNIFORM); const weight_t normWeight = divideByWeight ? totalWeight : 1.; char outBuff[1024]; // should be long enough for one line (ASSUMPTION) WriteHeader(outFile, "Histogram2"); if(uniformX) { outFile << "# first/last x-bins are under/over, respectively \n"; // Change the edges we use, so we don't need fancy code edgesX.front() = binSpecsX.range.min - binSpecsX.binWidth; edgesX.back() = binSpecsX.range.max + binSpecsX.binWidth; } else WriteUnderOverX(outFile, normWeight); if(uniformY) { outFile << "# first/last y-bins are under/over, respectively \n"; // Change the edges we use, so we don't need fancy code edgesY.front() = binSpecsY.range.min - binSpecsY.binWidth; edgesY.back() = binSpecsY.range.max + binSpecsY.binWidth; } else WriteUnderOverY(outFile, normWeight); outFile << "# WARNING: data configured for gnuplot splot or splot with pm3d; \ the interpolation mesh is probably not being displayed accurately.\n"; outFile << "# To properly display in gnuplot, you must use \ \"set pm3d corners2color c1\"\n"; outFile << "#\n#\n"; const int uniformShiftX = (uniformX ? 0 : 1); const int uniformShiftY = (uniformY ? 0 : 1); auto const endHistoX = hist.end() - uniformShiftX; auto leftEdgeX = edgesX.begin() + uniformShiftX; auto rightEdgeX = leftEdgeX + 1; outFile << "# x y pdf(x) pdfError(x)\n"; for(auto thisHistoX = hist.begin() + uniformShiftX; thisHistoX not_eq endHistoX; ++thisHistoX) { //const edge_t xPos = 0.5*(*rightEdgeX + *leftEdgeX); // gnuplot assumes you are giving it corners, not central positions const edge_t xPos = *leftEdgeX; const edge_t xWidth = (*rightEdgeX - *leftEdgeX); auto const endBinY = thisHistoX->end() - uniformShiftY; auto leftEdgeY = edgesY.begin() + uniformShiftY; auto rightEdgeY = leftEdgeY + 1; for(auto thisBinY = thisHistoX->begin() + uniformShiftY; thisBinY not_eq endBinY; ++thisBinY) { const weight_t thisWeight = thisBinY->weight; const weight_t thisError = std::sqrt(thisBinY->error2); const edge_t thisBinDenom = normWeight * (divideByWidth ? xWidth*(*rightEdgeY - *leftEdgeY) : 1.); sprintf(outBuff, "% .6e % .6e % .6e % .6e\n", xPos, //0.5*(*rightEdgeY + *leftEdgeY), // gnuplot assumes you are giving it corners, not central positions *leftEdgeY, (writeScale*thisWeight)/thisBinDenom, (writeScale*thisError)/thisBinDenom); outFile << outBuff; leftEdgeY = rightEdgeY; ++rightEdgeY; } // gnuplot assumes you are giving it corners, not central positions sprintf(outBuff, "% .6e % .6e % .6e % .6e\n", xPos, //0.5*(*rightEdgeY + *leftEdgeY), // gnuplot assumes you are giving it corners, not central positions *leftEdgeY, 0., 0.); outFile << outBuff; // gnuplot requires blank line in between x-values outFile << "\n"; leftEdgeX = rightEdgeX; ++rightEdgeX; } // gnuplot assumes you are giving it corners, not central positions // Therefore, we must supply the upper boundaries for(auto leftEdgeY = edgesY.begin() + uniformShiftY; leftEdgeY not_eq edgesY.end() - uniformShiftY; ++leftEdgeY) { sprintf(outBuff, "% .6e % .6e % .6e % .6e\n", *leftEdgeX, *leftEdgeY, 0., 0.); outFile << outBuff; } outFile.close(); written = true; } } void kdp::Histogram2::WriteUnderOverX(std::ofstream& outFile, weight_t const normWeight) { outFile << "#\n"; char buffer[1024]; assert(hist.front().size() == hist.back().size()); assert(hist.front().size() == hist.front().binSpecs.edges.size() - 1); auto itUnder = hist.front().begin(); auto itOver = hist.back().begin(); auto leftEdge = hist.front().binSpecs.edges.begin(); auto rightEdge = leftEdge + 1; auto const underEnd = hist.front().end(); while(itUnder not_eq underEnd) { sprintf(buffer, "# x under-over (y-pos | under | over) %.7e %.7e %.7e\n", 0.5+(*leftEdge + *rightEdge), (writeScale * itUnder->weight) / normWeight, (writeScale * itOver->weight) / normWeight); outFile << buffer; ++itUnder; ++itOver; leftEdge = rightEdge; ++rightEdge; } } void kdp::Histogram2::WriteUnderOverY(std::ofstream& outFile, weight_t const normWeight) { outFile << "#\n"; char buffer[1024]; // Just assume each vector has the same weight assert(hist.size() == hist.binSpecs.edges.size() - 1); auto leftEdge = hist.binSpecs.edges.begin(); auto rightEdge = leftEdge + 1; for(auto itXhist = hist.begin(); itXhist not_eq hist.end(); ++itXhist) { sprintf(buffer, "# y under-over (x-pos | under | over) %.7e %.7e %.7e\n", 0.5+(*leftEdge + *rightEdge), (writeScale * (itXhist->front().weight)) / normWeight, (writeScale * (itXhist->back().weight)) / normWeight); outFile << buffer; leftEdge = rightEdge; ++rightEdge; } }
[ "kpeders1@hawk.iit.edu" ]
kpeders1@hawk.iit.edu
03ae6d0aad26417884105d807f020981b7733a85
4503b4ec29e9a30d26c433bac376f2bddaefd9e5
/boost_1_56_0_WinCE/boost/numeric/odeint/external/openmp/openmp_range_algebra.hpp
6df2553040f7f71976e223f1406c80a50f9e6f05
[]
no_license
SwunZH/ecocommlibs
0a872e0bbecbb843a0584fb787cf0c5e8a2a270b
4cff09ff1e479f5f519f207262a61ee85f543b3a
refs/heads/master
2021-01-25T12:02:39.067444
2018-02-23T07:04:43
2018-02-23T07:04:43
123,447,012
1
0
null
2018-03-01T14:37:53
2018-03-01T14:37:53
null
UTF-8
C++
false
false
18,352
hpp
/* [auto_generated] boost/numeric/odeint/external/openmp/openmp_range_algebra.hpp [begin_description] Range algebra for OpenMP. [end_description] Copyright 2013 Karsten Ahnert Copyright 2013 Mario Mulansky Copyright 2013 Pascal Germroth 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_NUMERIC_ODEINT_EXTERNAL_OPENMP_OPENMP_RANGE_ALGEBRA_HPP_INCLUDED #define BOOST_NUMERIC_ODEINT_EXTERNAL_OPENMP_OPENMP_RANGE_ALGEBRA_HPP_INCLUDED #include <boost/assert.hpp> #include <boost/range.hpp> #include <boost/numeric/odeint/algebra/norm_result_type.hpp> #include <boost/numeric/odeint/util/n_ary_helper.hpp> namespace boost { namespace numeric { namespace odeint { /** \brief OpenMP-parallelized range algebra. * * State must be a model of Random Access Range. */ struct openmp_range_algebra { #if __cplusplus >= 201103L // C++11 supports _Pragma #define BOOST_ODEINT_GEN_LOCAL(z, n, unused) \ BOOST_ASSERT_MSG( len == boost::size(s ## n), "All state ranges must have the same size." ); \ typename boost::range_iterator<S ## n>::type beg ## n = boost::begin(s ## n); #define BOOST_ODEINT_GEN_BODY(n) \ const size_t len = boost::size(s0); \ BOOST_PP_REPEAT(n, BOOST_ODEINT_GEN_LOCAL, ~) \ _Pragma("omp parallel for schedule(runtime)") \ for( size_t i = 0 ; i < len ; i++ ) \ op( BOOST_PP_ENUM_BINARY_PARAMS(n, beg, [i] BOOST_PP_INTERCEPT) ); BOOST_ODEINT_GEN_FOR_EACH(BOOST_ODEINT_GEN_BODY) #undef BOOST_ODEINT_GEN_BODY #undef BOOST_ODEINT_GEN_LOCAL #else template< class S0 , class Op > static void for_each1 ( S0 &s0 , Op op ) { const size_t len = boost::size(s0); typename boost::range_iterator<S0>::type beg0 = boost::begin(s0); #pragma omp parallel for schedule(runtime) for( size_t i = 0 ; i < len ; i++ ) op( beg0 [i] ); } template< class S0 , class S1 , class Op > static void for_each2 ( S0 &s0 , S1 &s1 , Op op ) { const size_t len = boost::size(s0); typename boost::range_iterator<S0>::type beg0 = boost::begin(s0); typename boost::range_iterator<S1>::type beg1 = boost::begin(s1); #pragma omp parallel for schedule(runtime) for( size_t i = 0 ; i < len ; i++ ) op( beg0 [i] , beg1 [i] ); } template< class S0 , class S1 , class S2 , class Op > static void for_each3 ( S0 &s0 , S1 &s1 , S2 &s2 , Op op ) { const size_t len = boost::size(s0); typename boost::range_iterator<S0>::type beg0 = boost::begin(s0); typename boost::range_iterator<S1>::type beg1 = boost::begin(s1); typename boost::range_iterator<S2>::type beg2 = boost::begin(s2); #pragma omp parallel for schedule(runtime) for( size_t i = 0 ; i < len ; i++ ) op( beg0 [i] , beg1 [i] , beg2 [i] ); } template< class S0 , class S1 , class S2 , class S3 , class Op > static void for_each4 ( S0 &s0 , S1 &s1 , S2 &s2 , S3 &s3 , Op op ) { const size_t len = boost::size(s0); typename boost::range_iterator<S0>::type beg0 = boost::begin(s0); typename boost::range_iterator<S1>::type beg1 = boost::begin(s1); typename boost::range_iterator<S2>::type beg2 = boost::begin(s2); typename boost::range_iterator<S3>::type beg3 = boost::begin(s3); #pragma omp parallel for schedule(runtime) for( size_t i = 0 ; i < len ; i++ ) op( beg0 [i] , beg1 [i] , beg2 [i] , beg3 [i] ); } template< class S0 , class S1 , class S2 , class S3 , class S4 , class Op > static void for_each5 ( S0 &s0 , S1 &s1 , S2 &s2 , S3 &s3 , S4 &s4 , Op op ) { const size_t len = boost::size(s0); typename boost::range_iterator<S0>::type beg0 = boost::begin(s0); typename boost::range_iterator<S1>::type beg1 = boost::begin(s1); typename boost::range_iterator<S2>::type beg2 = boost::begin(s2); typename boost::range_iterator<S3>::type beg3 = boost::begin(s3); typename boost::range_iterator<S4>::type beg4 = boost::begin(s4); #pragma omp parallel for schedule(runtime) for( size_t i = 0 ; i < len ; i++ ) op( beg0 [i] , beg1 [i] , beg2 [i] , beg3 [i] , beg4 [i] ); } template< class S0 , class S1 , class S2 , class S3 , class S4 , class S5 , class Op > static void for_each6 ( S0 &s0 , S1 &s1 , S2 &s2 , S3 &s3 , S4 &s4 , S5 &s5 , Op op ) { const size_t len = boost::size(s0); typename boost::range_iterator<S0>::type beg0 = boost::begin(s0); typename boost::range_iterator<S1>::type beg1 = boost::begin(s1); typename boost::range_iterator<S2>::type beg2 = boost::begin(s2); typename boost::range_iterator<S3>::type beg3 = boost::begin(s3); typename boost::range_iterator<S4>::type beg4 = boost::begin(s4); typename boost::range_iterator<S5>::type beg5 = boost::begin(s5); #pragma omp parallel for schedule(runtime) for( size_t i = 0 ; i < len ; i++ ) op( beg0 [i] , beg1 [i] , beg2 [i] , beg3 [i] , beg4 [i] , beg5 [i] ); } template< class S0 , class S1 , class S2 , class S3 , class S4 , class S5 , class S6 , class Op > static void for_each7 ( S0 &s0 , S1 &s1 , S2 &s2 , S3 &s3 , S4 &s4 , S5 &s5 , S6 &s6 , Op op ) { const size_t len = boost::size(s0); typename boost::range_iterator<S0>::type beg0 = boost::begin(s0); typename boost::range_iterator<S1>::type beg1 = boost::begin(s1); typename boost::range_iterator<S2>::type beg2 = boost::begin(s2); typename boost::range_iterator<S3>::type beg3 = boost::begin(s3); typename boost::range_iterator<S4>::type beg4 = boost::begin(s4); typename boost::range_iterator<S5>::type beg5 = boost::begin(s5); typename boost::range_iterator<S6>::type beg6 = boost::begin(s6); #pragma omp parallel for schedule(runtime) for( size_t i = 0 ; i < len ; i++ ) op( beg0 [i] , beg1 [i] , beg2 [i] , beg3 [i] , beg4 [i] , beg5 [i] , beg6 [i] ); } template< class S0 , class S1 , class S2 , class S3 , class S4 , class S5 , class S6 , class S7 , class Op > static void for_each8 ( S0 &s0 , S1 &s1 , S2 &s2 , S3 &s3 , S4 &s4 , S5 &s5 , S6 &s6 , S7 &s7 , Op op ) { const size_t len = boost::size(s0); typename boost::range_iterator<S0>::type beg0 = boost::begin(s0); typename boost::range_iterator<S1>::type beg1 = boost::begin(s1); typename boost::range_iterator<S2>::type beg2 = boost::begin(s2); typename boost::range_iterator<S3>::type beg3 = boost::begin(s3); typename boost::range_iterator<S4>::type beg4 = boost::begin(s4); typename boost::range_iterator<S5>::type beg5 = boost::begin(s5); typename boost::range_iterator<S6>::type beg6 = boost::begin(s6); typename boost::range_iterator<S7>::type beg7 = boost::begin(s7); #pragma omp parallel for schedule(runtime) for( size_t i = 0 ; i < len ; i++ ) op( beg0 [i] , beg1 [i] , beg2 [i] , beg3 [i] , beg4 [i] , beg5 [i] , beg6 [i] , beg7 [i] ); } template< class S0 , class S1 , class S2 , class S3 , class S4 , class S5 , class S6 , class S7 , class S8 , class Op > static void for_each9 ( S0 &s0 , S1 &s1 , S2 &s2 , S3 &s3 , S4 &s4 , S5 &s5 , S6 &s6 , S7 &s7 , S8 &s8 , Op op ) { const size_t len = boost::size(s0); typename boost::range_iterator<S0>::type beg0 = boost::begin(s0); typename boost::range_iterator<S1>::type beg1 = boost::begin(s1); typename boost::range_iterator<S2>::type beg2 = boost::begin(s2); typename boost::range_iterator<S3>::type beg3 = boost::begin(s3); typename boost::range_iterator<S4>::type beg4 = boost::begin(s4); typename boost::range_iterator<S5>::type beg5 = boost::begin(s5); typename boost::range_iterator<S6>::type beg6 = boost::begin(s6); typename boost::range_iterator<S7>::type beg7 = boost::begin(s7); typename boost::range_iterator<S8>::type beg8 = boost::begin(s8); #pragma omp parallel for schedule(runtime) for( size_t i = 0 ; i < len ; i++ ) op( beg0 [i] , beg1 [i] , beg2 [i] , beg3 [i] , beg4 [i] , beg5 [i] , beg6 [i] , beg7 [i] , beg8 [i] ); } template< class S0 , class S1 , class S2 , class S3 , class S4 , class S5 , class S6 , class S7 , class S8 , class S9 , class Op > static void for_each10 ( S0 &s0 , S1 &s1 , S2 &s2 , S3 &s3 , S4 &s4 , S5 &s5 , S6 &s6 , S7 &s7 , S8 &s8 , S9 &s9 , Op op ) { const size_t len = boost::size(s0); typename boost::range_iterator<S0>::type beg0 = boost::begin(s0); typename boost::range_iterator<S1>::type beg1 = boost::begin(s1); typename boost::range_iterator<S2>::type beg2 = boost::begin(s2); typename boost::range_iterator<S3>::type beg3 = boost::begin(s3); typename boost::range_iterator<S4>::type beg4 = boost::begin(s4); typename boost::range_iterator<S5>::type beg5 = boost::begin(s5); typename boost::range_iterator<S6>::type beg6 = boost::begin(s6); typename boost::range_iterator<S7>::type beg7 = boost::begin(s7); typename boost::range_iterator<S8>::type beg8 = boost::begin(s8); typename boost::range_iterator<S9>::type beg9 = boost::begin(s9); #pragma omp parallel for schedule(runtime) for( size_t i = 0 ; i < len ; i++ ) op( beg0 [i] , beg1 [i] , beg2 [i] , beg3 [i] , beg4 [i] , beg5 [i] , beg6 [i] , beg7 [i] , beg8 [i] , beg9 [i] ); } template< class S0 , class S1 , class S2 , class S3 , class S4 , class S5 , class S6 , class S7 , class S8 , class S9 , class S10 , class Op > static void for_each11 ( S0 &s0 , S1 &s1 , S2 &s2 , S3 &s3 , S4 &s4 , S5 &s5 , S6 &s6 , S7 &s7 , S8 &s8 , S9 &s9 , S10 &s10 , Op op ) { const size_t len = boost::size(s0); typename boost::range_iterator<S0>::type beg0 = boost::begin(s0); typename boost::range_iterator<S1>::type beg1 = boost::begin(s1); typename boost::range_iterator<S2>::type beg2 = boost::begin(s2); typename boost::range_iterator<S3>::type beg3 = boost::begin(s3); typename boost::range_iterator<S4>::type beg4 = boost::begin(s4); typename boost::range_iterator<S5>::type beg5 = boost::begin(s5); typename boost::range_iterator<S6>::type beg6 = boost::begin(s6); typename boost::range_iterator<S7>::type beg7 = boost::begin(s7); typename boost::range_iterator<S8>::type beg8 = boost::begin(s8); typename boost::range_iterator<S9>::type beg9 = boost::begin(s9); typename boost::range_iterator<S10>::type beg10 = boost::begin(s10); #pragma omp parallel for schedule(runtime) for( size_t i = 0 ; i < len ; i++ ) op( beg0 [i] , beg1 [i] , beg2 [i] , beg3 [i] , beg4 [i] , beg5 [i] , beg6 [i] , beg7 [i] , beg8 [i] , beg9 [i] , beg10 [i] ); } template< class S0 , class S1 , class S2 , class S3 , class S4 , class S5 , class S6 , class S7 , class S8 , class S9 , class S10 , class S11 , class Op > static void for_each12 ( S0 &s0 , S1 &s1 , S2 &s2 , S3 &s3 , S4 &s4 , S5 &s5 , S6 &s6 , S7 &s7 , S8 &s8 , S9 &s9 , S10 &s10 , S11 &s11 , Op op ) { const size_t len = boost::size(s0); typename boost::range_iterator<S0>::type beg0 = boost::begin(s0); typename boost::range_iterator<S1>::type beg1 = boost::begin(s1); typename boost::range_iterator<S2>::type beg2 = boost::begin(s2); typename boost::range_iterator<S3>::type beg3 = boost::begin(s3); typename boost::range_iterator<S4>::type beg4 = boost::begin(s4); typename boost::range_iterator<S5>::type beg5 = boost::begin(s5); typename boost::range_iterator<S6>::type beg6 = boost::begin(s6); typename boost::range_iterator<S7>::type beg7 = boost::begin(s7); typename boost::range_iterator<S8>::type beg8 = boost::begin(s8); typename boost::range_iterator<S9>::type beg9 = boost::begin(s9); typename boost::range_iterator<S10>::type beg10 = boost::begin(s10); typename boost::range_iterator<S11>::type beg11 = boost::begin(s11); #pragma omp parallel for schedule(runtime) for( size_t i = 0 ; i < len ; i++ ) op( beg0 [i] , beg1 [i] , beg2 [i] , beg3 [i] , beg4 [i] , beg5 [i] , beg6 [i] , beg7 [i] , beg8 [i] , beg9 [i] , beg10 [i] , beg11 [i] ); } template< class S0 , class S1 , class S2 , class S3 , class S4 , class S5 , class S6 , class S7 , class S8 , class S9 , class S10 , class S11 , class S12 , class Op > static void for_each13 ( S0 &s0 , S1 &s1 , S2 &s2 , S3 &s3 , S4 &s4 , S5 &s5 , S6 &s6 , S7 &s7 , S8 &s8 , S9 &s9 , S10 &s10 , S11 &s11 , S12 &s12 , Op op ) { const size_t len = boost::size(s0); typename boost::range_iterator<S0>::type beg0 = boost::begin(s0); typename boost::range_iterator<S1>::type beg1 = boost::begin(s1); typename boost::range_iterator<S2>::type beg2 = boost::begin(s2); typename boost::range_iterator<S3>::type beg3 = boost::begin(s3); typename boost::range_iterator<S4>::type beg4 = boost::begin(s4); typename boost::range_iterator<S5>::type beg5 = boost::begin(s5); typename boost::range_iterator<S6>::type beg6 = boost::begin(s6); typename boost::range_iterator<S7>::type beg7 = boost::begin(s7); typename boost::range_iterator<S8>::type beg8 = boost::begin(s8); typename boost::range_iterator<S9>::type beg9 = boost::begin(s9); typename boost::range_iterator<S10>::type beg10 = boost::begin(s10); typename boost::range_iterator<S11>::type beg11 = boost::begin(s11); typename boost::range_iterator<S12>::type beg12 = boost::begin(s12); #pragma omp parallel for schedule(runtime) for( size_t i = 0 ; i < len ; i++ ) op( beg0 [i] , beg1 [i] , beg2 [i] , beg3 [i] , beg4 [i] , beg5 [i] , beg6 [i] , beg7 [i] , beg8 [i] , beg9 [i] , beg10 [i] , beg11 [i] , beg12 [i] ); } template< class S0 , class S1 , class S2 , class S3 , class S4 , class S5 , class S6 , class S7 , class S8 , class S9 , class S10 , class S11 , class S12 , class S13 , class Op > static void for_each14 ( S0 &s0 , S1 &s1 , S2 &s2 , S3 &s3 , S4 &s4 , S5 &s5 , S6 &s6 , S7 &s7 , S8 &s8 , S9 &s9 , S10 &s10 , S11 &s11 , S12 &s12 , S13 &s13 , Op op ) { const size_t len = boost::size(s0); typename boost::range_iterator<S0>::type beg0 = boost::begin(s0); typename boost::range_iterator<S1>::type beg1 = boost::begin(s1); typename boost::range_iterator<S2>::type beg2 = boost::begin(s2); typename boost::range_iterator<S3>::type beg3 = boost::begin(s3); typename boost::range_iterator<S4>::type beg4 = boost::begin(s4); typename boost::range_iterator<S5>::type beg5 = boost::begin(s5); typename boost::range_iterator<S6>::type beg6 = boost::begin(s6); typename boost::range_iterator<S7>::type beg7 = boost::begin(s7); typename boost::range_iterator<S8>::type beg8 = boost::begin(s8); typename boost::range_iterator<S9>::type beg9 = boost::begin(s9); typename boost::range_iterator<S10>::type beg10 = boost::begin(s10); typename boost::range_iterator<S11>::type beg11 = boost::begin(s11); typename boost::range_iterator<S12>::type beg12 = boost::begin(s12); typename boost::range_iterator<S13>::type beg13 = boost::begin(s13); #pragma omp parallel for schedule(runtime) for( size_t i = 0 ; i < len ; i++ ) op( beg0 [i] , beg1 [i] , beg2 [i] , beg3 [i] , beg4 [i] , beg5 [i] , beg6 [i] , beg7 [i] , beg8 [i] , beg9 [i] , beg10 [i] , beg11 [i] , beg12 [i] , beg13 [i] ); } template< class S0 , class S1 , class S2 , class S3 , class S4 , class S5 , class S6 , class S7 , class S8 , class S9 , class S10 , class S11 , class S12 , class S13 , class S14 , class Op > static void for_each15 ( S0 &s0 , S1 &s1 , S2 &s2 , S3 &s3 , S4 &s4 , S5 &s5 , S6 &s6 , S7 &s7 , S8 &s8 , S9 &s9 , S10 &s10 , S11 &s11 , S12 &s12 , S13 &s13 , S14 &s14 , Op op ) { const size_t len = boost::size(s0); typename boost::range_iterator<S0>::type beg0 = boost::begin(s0); typename boost::range_iterator<S1>::type beg1 = boost::begin(s1); typename boost::range_iterator<S2>::type beg2 = boost::begin(s2); typename boost::range_iterator<S3>::type beg3 = boost::begin(s3); typename boost::range_iterator<S4>::type beg4 = boost::begin(s4); typename boost::range_iterator<S5>::type beg5 = boost::begin(s5); typename boost::range_iterator<S6>::type beg6 = boost::begin(s6); typename boost::range_iterator<S7>::type beg7 = boost::begin(s7); typename boost::range_iterator<S8>::type beg8 = boost::begin(s8); typename boost::range_iterator<S9>::type beg9 = boost::begin(s9); typename boost::range_iterator<S10>::type beg10 = boost::begin(s10); typename boost::range_iterator<S11>::type beg11 = boost::begin(s11); typename boost::range_iterator<S12>::type beg12 = boost::begin(s12); typename boost::range_iterator<S13>::type beg13 = boost::begin(s13); typename boost::range_iterator<S14>::type beg14 = boost::begin(s14); #pragma omp parallel for schedule(runtime) for( size_t i = 0 ; i < len ; i++ ) op( beg0 [i] , beg1 [i] , beg2 [i] , beg3 [i] , beg4 [i] , beg5 [i] , beg6 [i] , beg7 [i] , beg8 [i] , beg9 [i] , beg10 [i] , beg11 [i] , beg12 [i] , beg13 [i] , beg14 [i] ); } #endif template< class S > static typename norm_result_type< S >::type norm_inf( const S &s ) { using std::max; using std::abs; typedef typename norm_result_type< S >::type result_type; result_type init = static_cast< result_type >( 0 ); const size_t len = boost::size(s); typename boost::range_iterator<S>::type beg = boost::begin(s); # pragma omp parallel for reduction(max: init) schedule(dynamic) for( size_t i = 0 ; i < len ; ++i ) init = max( init , abs( beg[i] ) ); return init; } }; } } } #endif
[ "lycos7x@3e9e098e-e079-49b3-9d2b-ee27db7392fb" ]
lycos7x@3e9e098e-e079-49b3-9d2b-ee27db7392fb
ea040ae3d0c9228c1dfec95128fb32e5aeda2a29
84db845cc485c91e6dbc44e4944a85d27518c9a8
/2018/2018_Jul/Week4/WF/wf_I_hdoj4642.cpp
8b5eb95565527533ea170fefd760320422962bdc
[]
no_license
sunyinkai/ACM_ICPC
c13398c6963f0267db282e71d11baaf7ff619c71
8e54240df29b4a722efd27b5866384ba84f859a4
refs/heads/master
2021-07-07T07:39:36.553203
2020-07-26T06:50:54
2020-07-26T06:50:54
158,057,635
2
0
null
null
null
null
UTF-8
C++
false
false
246
cpp
#include<cstdio> int main(){ int T;scanf("%d",&T); while(T--){ int N,M;scanf("%d%d",&N,&M); int num; for(int i=0;i<N;++i) for(int j=0;j<M;++j) scanf("%d",&num); if(num&1)printf("Alice\n"); else printf("Bob\n"); } return 0; }
[ "1091491336@qq.com" ]
1091491336@qq.com
cd80871c28454c48040719b15f7501bb732a6bf5
751f0297891d8ea6975842e887689b7024c32fda
/Source/bmalloc/bmalloc/SmallLine.h
e044e70dfb9299f6969cff4e739eacfefa60bab6
[]
no_license
gskachkov/webkit
4d162c15a2db7d9455fe2200c7ffa2002f34a59a
c9aeb6d32e22bfa22ad468324f3e0ea48354badb
refs/heads/master
2023-03-01T05:32:31.643945
2016-04-13T18:24:52
2016-04-13T18:24:52
30,821,838
0
0
null
2015-02-15T08:15:59
2015-02-15T08:15:58
null
UTF-8
C++
false
false
2,319
h
/* * Copyright (C) 2014-2016 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. 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 SmallLine_h #define SmallLine_h #include "BAssert.h" #include "Mutex.h" #include "ObjectType.h" #include <mutex> namespace bmalloc { class SmallLine { public: static const unsigned char maxRefCount = std::numeric_limits<unsigned char>::max(); static_assert(smallLineSize / alignment < maxRefCount, "maximum object count must fit in Line"); static SmallLine* get(void*); void ref(std::lock_guard<StaticMutex>&, unsigned char); bool deref(std::lock_guard<StaticMutex>&); unsigned refCount(std::lock_guard<StaticMutex>&) { return m_refCount; } char* begin(); char* end(); private: unsigned char m_refCount; }; inline void SmallLine::ref(std::lock_guard<StaticMutex>&, unsigned char refCount) { BASSERT(!m_refCount); m_refCount = refCount; } inline bool SmallLine::deref(std::lock_guard<StaticMutex>&) { BASSERT(m_refCount); --m_refCount; return !m_refCount; } } // namespace bmalloc #endif // SmallLine_h
[ "ggaren@apple.com@268f45cc-cd09-0410-ab3c-d52691b4dbfc" ]
ggaren@apple.com@268f45cc-cd09-0410-ab3c-d52691b4dbfc
eda02bf7db83d6bf3105dcc429ca94f232bc6562
b7ee5b78d5e48ba336e0a252cfe99c76def8f27d
/src/renderers/samplerrenderer.h
b27bd53b231f086d0a57ad5786b718c83a73bf74
[ "BSD-2-Clause" ]
permissive
mgharbi/rendernet_pbrt
f09796532600b1cd876b4a02bb1c80ecf2fb6ed7
8dce288eea765f0e472af6906968dcd6e2b1f7c7
refs/heads/master
2020-03-31T18:03:51.772096
2019-04-21T13:33:31
2019-04-21T13:33:31
152,445,182
2
0
null
null
null
null
UTF-8
C++
false
false
3,312
h
/* pbrt source code Copyright(c) 1998-2012 Matt Pharr and Greg Humphreys. This file is part of pbrt. 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. 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. */ #if defined(_MSC_VER) #pragma once #endif #ifndef PBRT_RENDERERS_SAMPLERRENDERER_H #define PBRT_RENDERERS_SAMPLERRENDERER_H // renderers/samplerrenderer.h* #include "pbrt.h" #include "renderer.h" #include "parallel.h" // SamplerRenderer Declarations class SamplerRenderer : public Renderer { public: // SamplerRenderer Public Methods SamplerRenderer(Sampler *s, Camera *c, SurfaceIntegrator *si, VolumeIntegrator *vi, bool visIds); ~SamplerRenderer(); void Render(const Scene *scene); Spectrum Li(const Scene *scene, const RayDifferential &ray, const Sample *sample, RNG &rng, MemoryArena &arena, Intersection *isect = NULL, Spectrum *T = NULL) const; Spectrum Transmittance(const Scene *scene, const RayDifferential &ray, const Sample *sample, RNG &rng, MemoryArena &arena) const; private: // SamplerRenderer Private Data bool visualizeObjectIds; Sampler *sampler; Camera *camera; SurfaceIntegrator *surfaceIntegrator; VolumeIntegrator *volumeIntegrator; }; // SamplerRendererTask Declarations class SamplerRendererTask : public Task { public: // SamplerRendererTask Public Methods SamplerRendererTask(const Scene *sc, Renderer *ren, Camera *c, ProgressReporter &pr, Sampler *ms, Sample *sam, bool visIds, int tn, int tc) : reporter(pr) { scene = sc; renderer = ren; camera = c; mainSampler = ms; origSample = sam; visualizeObjectIds = visIds; taskNum = tn; taskCount = tc; } void Run(); private: // SamplerRendererTask Private Data const Scene *scene; const Renderer *renderer; Camera *camera; Sampler *mainSampler; ProgressReporter &reporter; Sample *origSample; bool visualizeObjectIds; int taskNum, taskCount; }; #endif // PBRT_RENDERERS_SAMPLERRENDERER_H
[ "gharbi@mit.edu" ]
gharbi@mit.edu
48f19691a6a9c816e6c741dfe21e8e2c00c9813a
c9787aef563b1cb6a24a3ec4c09e5f4535a28c46
/pp5_AlejandroCoronado/mips.cc
84509743fde8d4449c4f3bb29a35d4202648d2aa
[]
no_license
coronate-zz/compiladorDecaf
3fa0c927b8e24a78414df253b69cc18d47fb6636
2d2fb3c24b47279db402f7a9e7bdc45a0b7ec8e8
refs/heads/master
2021-06-16T11:16:55.003205
2017-05-26T08:47:44
2017-05-26T08:47:44
83,354,158
0
1
null
null
null
null
UTF-8
C++
false
false
15,356
cc
#include <stdarg.h> #include <cstring> #include "mips.h" // Helper to check if two variable locations are one and the same // (same name, segment, and offset) static bool LocationsAreSame(Location *var1, Location *var2) { return (var1 == var2 || (var1 && var2 && !strcmp(var1->GetName(), var2->GetName()) && var1->GetSegment() == var2->GetSegment() && var1->GetOffset() == var2->GetOffset())); } /* Method: SpillRegister * --------------------- * Used to spill a register from reg to dst. All it does is emit a store * from that register to its location on the stack. */ void Mips::SpillRegister(Location *dst, Register reg) { Assert(dst); const char *offsetFromWhere = dst->GetSegment() == fpRelative ? regs[fp].name : regs[gp].name; Assert(dst->GetOffset() % 4 == 0); // all variables are 4 bytes in size Emit("sw %s, %d(%s)\t# spill %s from %s to %s%+d", regs[reg].name, dst->GetOffset(), offsetFromWhere, dst->GetName(), regs[reg].name, offsetFromWhere,dst->GetOffset()); } /* Method: FillRegister * -------------------- * Fill a register from location src into reg. * Simply load a word into a register. */ void Mips::FillRegister(Location *src, Register reg) { Assert(src); const char *offsetFromWhere = src->GetSegment() == fpRelative ? regs[fp].name : regs[gp].name; Assert(src->GetOffset() % 4 == 0); // all variables are 4 bytes in size Emit("lw %s, %d(%s)\t# fill %s to %s from %s%+d", regs[reg].name, src->GetOffset(), offsetFromWhere, src->GetName(), regs[reg].name, offsetFromWhere,src->GetOffset()); } /* Method: Emit * ------------ * General purpose helper used to emit assembly instructions in * a reasonable tidy manner. Takes printf-style formatting strings * and variable arguments. */ void Mips::Emit(const char *fmt, ...) { va_list args; char buf[1024]; va_start(args, fmt); vsprintf(buf, fmt, args); va_end(args); if (buf[strlen(buf) - 1] != ':') printf("\t"); // don't tab in labels if (buf[0] != '#') printf(" "); // outdent comments a little printf("%s", buf); if (buf[strlen(buf)-1] != '\n') printf("\n"); // end with a newline } /* Method: EmitLoadConstant * ------------------------ * Used to assign variable an integer constant value. Slaves dst into * a register (using GetRegister above) and then emits an li (load * immediate) instruction with the constant value. */ void Mips::EmitLoadConstant(Location *dst, int val) { Register r = rd; Emit("li %s, %d\t\t# load constant value %d into %s", regs[r].name, val, val, regs[r].name); SpillRegister(dst, rd); } /* Method: EmitLoadStringConstant * ------------------------------ * Used to assign a variable a pointer to string constant. Emits * assembly directives to create a new null-terminated string in the * data segment and assigns it a unique label. Slaves dst into a register * and loads that label address into the register. */ void Mips::EmitLoadStringConstant(Location *dst, const char *str) { static int strNum = 1; char label[16]; sprintf(label, "_string%d", strNum++); Emit(".data\t\t\t# create string constant marked with label"); Emit("%s: .asciiz %s", label, str); Emit(".text"); EmitLoadLabel(dst, label); } /* Method: EmitLoadLabel * --------------------- * Used to load a label (ie address in text/data segment) into a variable. * Slaves dst into a register and emits an la (load address) instruction */ void Mips::EmitLoadLabel(Location *dst, const char *label) { Emit("la %s, %s\t# load label", regs[rd].name, label); SpillRegister(dst, rd); } /* Method: EmitCopy * ---------------- * Used to copy the value of one variable to another. Slaves both * src and dst into registers and then emits a move instruction to * copy the contents from src to dst. */ void Mips::EmitCopy(Location *dst, Location *src) { FillRegister(src, rd); SpillRegister(dst, rd); } /* Method: EmitLoad * ---------------- * Used to assign dst the contents of memory at the address in reference, * potentially with some positive/negative offset (defaults to 0). * Slaves both ref and dst to registers, then emits a lw instruction * using constant-offset addressing mode y(rx) which accesses the address * at an offset of y bytes from the address currently contained in rx. */ void Mips::EmitLoad(Location *dst, Location *reference, int offset) { FillRegister(reference, rs); Emit("lw %s, %d(%s) \t# load with offset", regs[rd].name, offset, regs[rs].name); SpillRegister(dst, rd); } /* Method: EmitStore * ----------------- * Used to write value to memory at the address in reference, * potentially with some positive/negative offset (defaults to 0). * Slaves both ref and dst to registers, then emits a sw instruction * using constant-offset addressing mode y(rx) which writes to the address * at an offset of y bytes from the address currently contained in rx. */ void Mips::EmitStore(Location *reference, Location *value, int offset) { FillRegister(value, rs); FillRegister(reference, rd); Emit("sw %s, %d(%s) \t# store with offset", regs[rs].name, offset, regs[rd].name); } /* Method: EmitBinaryOp * -------------------- * Used to perform a binary operation on 2 operands and store result * in dst. All binary forms for arithmetic, logical, relational, equality * use this method. Slaves both operands and dst to registers, then * emits the appropriate instruction by looking up the mips name * for the particular op code. */ void Mips::EmitBinaryOp(BinaryOp::OpCode code, Location *dst, Location *op1, Location *op2) { FillRegister(op1, rs); FillRegister(op2, rt); Emit("%s %s, %s, %s\t", NameForTac(code), regs[rd].name, regs[rs].name, regs[rt].name); SpillRegister(dst, rd); } /* Method: EmitLabel * ----------------- * Used to emit label marker. Before a label, we spill all registers since * we can't be sure what the situation upon arriving at this label (ie * starts new basic block), and rather than try to be clever, we just * wipe the slate clean. */ void Mips::EmitLabel(const char *label) { Emit("%s:", label); } /* Method: EmitGoto * ---------------- * Used for an unconditional transfer to a named label. Before a goto, * we spill all registers, since we don't know what the situation is * we are heading to (ie this ends current basic block) and rather than * try to be clever, we just wipe slate clean. */ void Mips::EmitGoto(const char *label) { Emit("b %s\t\t# unconditional branch", label); } /* Method: EmitIfZ * --------------- * Used for a conditional branch based on value of test variable. * We slave test var to register and use in the emitted test instruction, * either beqz. See comments above on Goto for why we spill * all registers here. */ void Mips::EmitIfZ(Location *test, const char *label) { FillRegister(test, rs); Emit("beqz %s, %s\t# branch if %s is zero ", regs[rs].name, label, test->GetName()); } /* Method: EmitParam * ----------------- * Used to push a parameter on the stack in anticipation of upcoming * function call. Decrements the stack pointer by 4. Slaves argument into * register and then stores contents to location just made at end of * stack. */ void Mips::EmitParam(Location *arg) { Emit("subu $sp, $sp, 4\t# decrement sp to make space for param"); FillRegister(arg, rs); Emit("sw %s, 4($sp)\t# copy param value to stack", regs[rs].name); } /* Method: EmitCallInstr * --------------------- * Used to effect a function call. All necessary arguments should have * already been pushed on the stack, this is the last step that * transfers control from caller to callee. See comments on Goto method * above for why we spill all registers before making the jump. We issue * jal for a label, a jalr if address in register. Both will save the * return address in $ra. If there is an expected result passed, we slave * the var to a register and copy function return value from $v0 into that * register. */ void Mips::EmitCallInstr(Location *result, const char *fn, bool isLabel) { Emit("%s %-15s\t# jump to function", isLabel? "jal": "jalr", fn); if (result != NULL) { Emit("move %s, %s\t\t# copy function return value from $v0", regs[rd].name, regs[v0].name); SpillRegister(result, rd); } } // Two covers for the above method for specific LCall/ACall variants void Mips::EmitLCall(Location *dst, const char *label) { EmitCallInstr(dst, label, true); } void Mips::EmitACall(Location *dst, Location *fn) { FillRegister(fn, rs); EmitCallInstr(dst, regs[rs].name, false); } /* * We remove all parameters from the stack after a completed call * by adjusting the stack pointer upwards. */ void Mips::EmitPopParams(int bytes) { if (bytes != 0) Emit("add $sp, $sp, %d\t# pop params off stack", bytes); } /* Method: EmitReturn * ------------------ * Used to emit code for returning from a function (either from an * explicit return or falling off the end of the function body). * If there is an expression to return, we slave that variable into * a register and move its contents to $v0 (the standard register for * function result). Before exiting, we spill dirty registers (to * commit contents of slaved registers to memory, necessary for * consistency, see comments at SpillForEndFunction above). We also * do the last part of the callee's job in function call protocol, * which is to remove our locals/temps from the stack, remove * saved registers ($fp and $ra) and restore previous values of * $fp and $ra so everything is returned to the state we entered. * We then emit jr to jump to the saved $ra. */ void Mips::EmitReturn(Location *returnVal) { if (returnVal != NULL) { FillRegister(returnVal, rd); Emit("move $v0, %s\t\t# assign return value into $v0", regs[rd].name); } Emit("move $sp, $fp\t\t# pop callee frame off stack"); Emit("lw $ra, -4($fp)\t# restore saved ra"); Emit("lw $fp, 0($fp)\t# restore saved fp"); Emit("jr $ra\t\t# return from function"); } /* Method: EmitBeginFunction * ------------------------- * Used to handle the callee's part of the function call protocol * upon entering a new function. We decrement the $sp to make space * and then save the current values of $fp and $ra (since we are * going to change them), then set up the $fp and bump the $sp down * to make space for all our locals/temps. */ void Mips::EmitBeginFunction(int stackFrameSize) { Assert(stackFrameSize >= 0); Emit("subu $sp, $sp, 8\t# decrement sp to make space to save ra, fp"); Emit("sw $fp, 8($sp)\t# save fp"); Emit("sw $ra, 4($sp)\t# save ra"); Emit("addiu $fp, $sp, 8\t# set up new fp"); if (stackFrameSize != 0) Emit( "subu $sp, $sp, %d\t# decrement sp to make space for locals/temps", stackFrameSize); } /* Method: EmitEndFunction * ----------------------- * Used to end the body of a function. Does an implicit return in fall off * case to clean up stack frame, return to caller etc. See comments on * EmitReturn above. */ void Mips::EmitEndFunction() { Emit("# (below handles reaching end of fn body with no explicit return)"); EmitReturn(NULL); } /* Method: EmitVTable * ------------------ * Used to layout a vtable. Uses assembly directives to set up new * entry in data segment, emits label, and lays out the function * labels one after another. */ void Mips::EmitVTable(const char *label, List<const char*> *methodLabels) { Emit(".data"); Emit(".align 2"); Emit("%s:\t\t# label for class %s vtable", label, label); for (int i = 0; i < methodLabels->NumElements(); i++) Emit(".word %s\n", methodLabels->Nth(i)); Emit(".text"); } /* Method: EmitPreamble * -------------------- * Used to emit the starting sequence needed for a program. Not much * here, but need to indicate what follows is in text segment and * needs to be aligned on word boundary. main is our only global symbol. */ void Mips::EmitPreamble() { Emit("# standard Decaf preamble "); Emit(".text"); Emit(".align 2"); Emit(".globl main"); } /* Method: NameForTac * ------------------ * Returns the appropriate MIPS instruction (add, seq, etc.) for * a given BinaryOp:OpCode (BinaryOp::Add, BinaryOp:Equals, etc.). * Asserts if asked for name of an unset/out of bounds code. */ const char *Mips::NameForTac(BinaryOp::OpCode code) { Assert(code >=0 && code < BinaryOp::NumOps); const char *name = mipsName[code]; Assert(name != NULL); return name; } /* Constructor * ---------- * Constructor sets up the mips names and register descriptors to * the initial starting state. */ Mips::Mips() { mipsName[BinaryOp::Add] = "add"; mipsName[BinaryOp::Sub] = "sub"; mipsName[BinaryOp::Mul] = "mul"; mipsName[BinaryOp::Div] = "div"; mipsName[BinaryOp::Mod] = "rem"; mipsName[BinaryOp::Eq] = "seq"; mipsName[BinaryOp::Ne] = "sne"; mipsName[BinaryOp::Lt] = "slt"; mipsName[BinaryOp::Le] = "sle"; mipsName[BinaryOp::Gt] = "sgt"; mipsName[BinaryOp::Ge] = "sge"; mipsName[BinaryOp::And] = "and"; mipsName[BinaryOp::Or] = "or"; regs[zero] = (RegContents){false, NULL, "$zero", false}; regs[at] = (RegContents){false, NULL, "$at", false}; regs[v0] = (RegContents){false, NULL, "$v0", false}; regs[v1] = (RegContents){false, NULL, "$v1", false}; regs[a0] = (RegContents){false, NULL, "$a0", false}; regs[a1] = (RegContents){false, NULL, "$a1", false}; regs[a2] = (RegContents){false, NULL, "$a2", false}; regs[a3] = (RegContents){false, NULL, "$a3", false}; regs[k0] = (RegContents){false, NULL, "$k0", false}; regs[k1] = (RegContents){false, NULL, "$k1", false}; regs[gp] = (RegContents){false, NULL, "$gp", false}; regs[sp] = (RegContents){false, NULL, "$sp", false}; regs[fp] = (RegContents){false, NULL, "$fp", false}; regs[ra] = (RegContents){false, NULL, "$ra", false}; regs[t0] = (RegContents){false, NULL, "$t0", true}; regs[t1] = (RegContents){false, NULL, "$t1", true}; regs[t2] = (RegContents){false, NULL, "$t2", true}; regs[t3] = (RegContents){false, NULL, "$t3", true}; regs[t4] = (RegContents){false, NULL, "$t4", true}; regs[t5] = (RegContents){false, NULL, "$t5", true}; regs[t6] = (RegContents){false, NULL, "$t6", true}; regs[t7] = (RegContents){false, NULL, "$t7", true}; regs[t8] = (RegContents){false, NULL, "$t8", true}; regs[t9] = (RegContents){false, NULL, "$t9", true}; regs[s0] = (RegContents){false, NULL, "$s0", true}; regs[s1] = (RegContents){false, NULL, "$s1", true}; regs[s2] = (RegContents){false, NULL, "$s2", true}; regs[s3] = (RegContents){false, NULL, "$s3", true}; regs[s4] = (RegContents){false, NULL, "$s4", true}; regs[s5] = (RegContents){false, NULL, "$s5", true}; regs[s6] = (RegContents){false, NULL, "$s6", true}; regs[s7] = (RegContents){false, NULL, "$s7", true}; rs = t0; rt = t1; rd = t2; } const char *Mips::mipsName[BinaryOp::NumOps];
[ "acoronadn@gmail.com" ]
acoronadn@gmail.com
e3ddc06da817b5b6fff697c858b4e2b1c41e14ed
427419228ca489739e16c380d7bc68a6ef509e5a
/A_Colorful_Stones_Simplified_Edition_.cpp
d575549318212f810f562f4ef50aa95b16266e17
[]
no_license
wolverinezgit/cpsolutions
d5dca485190a27f4d27e9610cd6ea02d98a50072
e0e695036cbd4c51ec9bf57d585b40204c8566a1
refs/heads/main
2023-03-10T12:31:27.848231
2021-02-18T13:04:00
2021-02-18T13:04:00
332,387,127
2
0
null
null
null
null
UTF-8
C++
false
false
550
cpp
#pragma GCC optimize("Ofast") #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,fma") #pragma GCC optimize("unroll-loops") #include <bits/stdc++.h> using namespace std; typedef long long ll; #define mp make_pair #define pb push_back #define fast_cin() ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL) int main() { fast_cin(); ll t,i,n,j,flag=0,mx=0,mn=1e9+7; string s1, s2; cin >> s1 >> s2; ll p1 = 0; for (i = 0; i < s2.length();i++) { if(s1[p1]==s2[i]) p1++; } cout << p1 + 1 << endl; return 0; }
[ "iamharsh05@gmail.com" ]
iamharsh05@gmail.com