blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
115 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
a4a187bb9a450ff9e07fc25d21889040d3594384
634b22b2690d05dbd6f7d6ef680db98cea7b85da
/src/test/getarg_tests.cpp
20e19e2915396c9049ae43bbb7df1869923f91a1
[ "MIT" ]
permissive
XGSTeam/nacacoin
f770a3e0275205395ddb88f26d946a271954e43c
69c2ba19e1ea0c30e7bcc90ef6f0571be6a5c0c9
refs/heads/master
2023-04-20T20:24:49.054365
2021-04-26T22:00:00
2021-04-26T22:00:00
289,020,782
1
3
MIT
2020-10-04T18:45:41
2020-08-20T13:59:13
C++
UTF-8
C++
false
false
5,339
cpp
// Copyright (c) 2012-2018 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 <util.h> #include <test/test_bitcoin.h> #include <string> #include <vector> #include <boost/algorithm/string.hpp> #include <boost/test/unit_test.hpp> BOOST_FIXTURE_TEST_SUITE(getarg_tests, BasicTestingSetup) static void ResetArgs(const std::string& strArg) { std::vector<std::string> vecArg; if (strArg.size()) boost::split(vecArg, strArg, boost::is_space(), boost::token_compress_on); // Insert dummy executable name: vecArg.insert(vecArg.begin(), "testnacacoin"); // Convert to char*: std::vector<const char*> vecChar; for (std::string& s : vecArg) vecChar.push_back(s.c_str()); std::string error; gArgs.ParseParameters(vecChar.size(), vecChar.data(), error); } static void SetupArgs(const std::vector<std::string>& args) { gArgs.ClearArgs(); for (const std::string& arg : args) { gArgs.AddArg(arg, "", false, OptionsCategory::OPTIONS); } } BOOST_AUTO_TEST_CASE(boolarg) { SetupArgs({"-foo"}); ResetArgs("-foo"); BOOST_CHECK(gArgs.GetBoolArg("-foo", false)); BOOST_CHECK(gArgs.GetBoolArg("-foo", true)); BOOST_CHECK(!gArgs.GetBoolArg("-fo", false)); BOOST_CHECK(gArgs.GetBoolArg("-fo", true)); BOOST_CHECK(!gArgs.GetBoolArg("-fooo", false)); BOOST_CHECK(gArgs.GetBoolArg("-fooo", true)); ResetArgs("-foo=0"); BOOST_CHECK(!gArgs.GetBoolArg("-foo", false)); BOOST_CHECK(!gArgs.GetBoolArg("-foo", true)); ResetArgs("-foo=1"); BOOST_CHECK(gArgs.GetBoolArg("-foo", false)); BOOST_CHECK(gArgs.GetBoolArg("-foo", true)); // New 0.6 feature: auto-map -nosomething to !-something: ResetArgs("-nofoo"); BOOST_CHECK(!gArgs.GetBoolArg("-foo", false)); BOOST_CHECK(!gArgs.GetBoolArg("-foo", true)); ResetArgs("-nofoo=1"); BOOST_CHECK(!gArgs.GetBoolArg("-foo", false)); BOOST_CHECK(!gArgs.GetBoolArg("-foo", true)); ResetArgs("-foo -nofoo"); // -nofoo should win BOOST_CHECK(!gArgs.GetBoolArg("-foo", false)); BOOST_CHECK(!gArgs.GetBoolArg("-foo", true)); ResetArgs("-foo=1 -nofoo=1"); // -nofoo should win BOOST_CHECK(!gArgs.GetBoolArg("-foo", false)); BOOST_CHECK(!gArgs.GetBoolArg("-foo", true)); ResetArgs("-foo=0 -nofoo=0"); // -nofoo=0 should win BOOST_CHECK(gArgs.GetBoolArg("-foo", false)); BOOST_CHECK(gArgs.GetBoolArg("-foo", true)); // New 0.6 feature: treat -- same as -: ResetArgs("--foo=1"); BOOST_CHECK(gArgs.GetBoolArg("-foo", false)); BOOST_CHECK(gArgs.GetBoolArg("-foo", true)); ResetArgs("--nofoo=1"); BOOST_CHECK(!gArgs.GetBoolArg("-foo", false)); BOOST_CHECK(!gArgs.GetBoolArg("-foo", true)); } BOOST_AUTO_TEST_CASE(stringarg) { SetupArgs({"-foo", "-bar"}); ResetArgs(""); BOOST_CHECK_EQUAL(gArgs.GetArg("-foo", ""), ""); BOOST_CHECK_EQUAL(gArgs.GetArg("-foo", "eleven"), "eleven"); ResetArgs("-foo -bar"); BOOST_CHECK_EQUAL(gArgs.GetArg("-foo", ""), ""); BOOST_CHECK_EQUAL(gArgs.GetArg("-foo", "eleven"), ""); ResetArgs("-foo="); BOOST_CHECK_EQUAL(gArgs.GetArg("-foo", ""), ""); BOOST_CHECK_EQUAL(gArgs.GetArg("-foo", "eleven"), ""); ResetArgs("-foo=11"); BOOST_CHECK_EQUAL(gArgs.GetArg("-foo", ""), "11"); BOOST_CHECK_EQUAL(gArgs.GetArg("-foo", "eleven"), "11"); ResetArgs("-foo=eleven"); BOOST_CHECK_EQUAL(gArgs.GetArg("-foo", ""), "eleven"); BOOST_CHECK_EQUAL(gArgs.GetArg("-foo", "eleven"), "eleven"); } BOOST_AUTO_TEST_CASE(intarg) { SetupArgs({"-foo", "-bar"}); ResetArgs(""); BOOST_CHECK_EQUAL(gArgs.GetArg("-foo", 11), 11); BOOST_CHECK_EQUAL(gArgs.GetArg("-foo", 0), 0); ResetArgs("-foo -bar"); BOOST_CHECK_EQUAL(gArgs.GetArg("-foo", 11), 0); BOOST_CHECK_EQUAL(gArgs.GetArg("-bar", 11), 0); ResetArgs("-foo=11 -bar=12"); BOOST_CHECK_EQUAL(gArgs.GetArg("-foo", 0), 11); BOOST_CHECK_EQUAL(gArgs.GetArg("-bar", 11), 12); ResetArgs("-foo=NaN -bar=NotANumber"); BOOST_CHECK_EQUAL(gArgs.GetArg("-foo", 1), 0); BOOST_CHECK_EQUAL(gArgs.GetArg("-bar", 11), 0); } BOOST_AUTO_TEST_CASE(doubledash) { SetupArgs({"-foo", "-bar"}); ResetArgs("--foo"); BOOST_CHECK_EQUAL(gArgs.GetBoolArg("-foo", false), true); ResetArgs("--foo=verbose --bar=1"); BOOST_CHECK_EQUAL(gArgs.GetArg("-foo", ""), "verbose"); BOOST_CHECK_EQUAL(gArgs.GetArg("-bar", 0), 1); } BOOST_AUTO_TEST_CASE(boolargno) { SetupArgs({"-foo", "-bar"}); ResetArgs("-nofoo"); BOOST_CHECK(!gArgs.GetBoolArg("-foo", true)); BOOST_CHECK(!gArgs.GetBoolArg("-foo", false)); ResetArgs("-nofoo=1"); BOOST_CHECK(!gArgs.GetBoolArg("-foo", true)); BOOST_CHECK(!gArgs.GetBoolArg("-foo", false)); ResetArgs("-nofoo=0"); BOOST_CHECK(gArgs.GetBoolArg("-foo", true)); BOOST_CHECK(gArgs.GetBoolArg("-foo", false)); ResetArgs("-foo --nofoo"); // --nofoo should win BOOST_CHECK(!gArgs.GetBoolArg("-foo", true)); BOOST_CHECK(!gArgs.GetBoolArg("-foo", false)); ResetArgs("-nofoo -foo"); // foo always wins: BOOST_CHECK(gArgs.GetBoolArg("-foo", true)); BOOST_CHECK(gArgs.GetBoolArg("-foo", false)); } BOOST_AUTO_TEST_SUITE_END()
[ "lemurnaca@nacacoin.org" ]
lemurnaca@nacacoin.org
0a584812f29f308bbab2032c16044ecd1b9fe8ca
d0cf18d4f92ce8fed1f1329569a1c3c4274b329e
/src/main.cc
ae341307e22e8ce4bc08dbfad0e1a24d3016127c
[]
no_license
anderspitman/cpp_bootstrap
fdc8b410d6d3550e96e1261d672d5140cf45367b
5c8016a8c90e5a59900f40233c39b1464f89aead
refs/heads/master
2021-05-04T10:55:00.268438
2016-02-10T23:37:18
2016-02-10T23:37:18
51,481,152
0
0
null
null
null
null
UTF-8
C++
false
false
151
cc
#include <iostream> #include "program.h" using namespace std; int main(int argc, char **argv) { string hi = sayHi(); cout << hi << endl; }
[ "tapitman11@gmail.com" ]
tapitman11@gmail.com
ae9a60811a149139d9cd268d3890c52458a538d4
649304876c4b4dac148022240ab0f72980121592
/include/falcon/controller/pid.hpp
7d45d346385ebce0fc33acd1308312459041cf94
[]
no_license
RReichert/Falcon
9c358ab26201a6c3e24895e609e34b2e19cc3e2b
16d79ea6987da188b9381f3053ec700a1b53bac0
refs/heads/master
2016-09-08T01:40:27.297214
2014-02-07T12:05:02
2014-02-07T12:18:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
283
hpp
#pragma once #include <boost/array.hpp> #include "falcon/controller/controller.hpp" class PID : public Controller{ public: void getTorque(const boost::array<double, 3> (&currentAngles), const boost::array<double, 3> (&desiredAngles), boost::array<double, 3> (&torque)); };
[ "reichert.rodrigo@gmail.com" ]
reichert.rodrigo@gmail.com
e4ad343d9dd60382b22461fe1030757ee574fceb
fe3cc6465e2ed72565c03f7952b337e6b5875425
/OpenFOAM_Examples/Quasi_DNS_Dowtherm_Mixed_Conv/Stable_RANSCase1/99.6/nut
68b0ed3119ee65103b4a6f3fcda2f81efdecfea8
[]
no_license
EXthan/turbulenceModelling
185772aac79c2a3e6b3620b5b5e285304c1b2de0
fdb66b497c15db1a570edb05a0cd83ed93df68c8
refs/heads/master
2022-12-04T20:47:50.965306
2020-08-24T02:34:23
2020-08-24T02:34:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
31,985
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: v1906 | | \\ / A nd | Web: www.OpenFOAM.com | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volScalarField; location "99.6"; object nut; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 2 -1 0 0 0 0]; internalField nonuniform List<scalar> 2528 ( 1.3129e-11 1.20164e-11 1.17444e-11 1.47494e-11 2.76094e-11 2.02653e-11 2.46824e-11 2.37457e-11 3.28058e-10 2.06208e-10 2.97082e-10 2.19888e-10 2.26279e-09 1.44706e-09 2.07854e-09 1.49786e-09 9.23633e-09 6.11521e-09 8.60207e-09 6.18449e-09 2.68707e-08 1.84527e-08 2.52823e-08 1.82375e-08 6.19243e-08 4.39609e-08 5.85424e-08 4.25186e-08 1.20432e-07 8.79002e-08 1.13784e-07 8.34667e-08 2.06004e-07 1.53728e-07 1.93715e-07 1.43916e-07 3.19143e-07 2.42345e-07 2.97911e-07 2.24596e-07 4.57795e-07 3.52413e-07 4.23602e-07 3.24379e-07 6.18556e-07 4.81312e-07 5.66899e-07 4.40982e-07 7.89598e-07 6.19931e-07 7.15707e-07 5.64892e-07 9.66891e-07 7.63598e-07 8.65983e-07 6.92243e-07 1.15724e-06 9.20085e-07 1.02347e-06 8.29107e-07 1.36013e-06 1.09018e-06 1.18762e-06 9.75679e-07 1.57573e-06 1.27429e-06 1.35754e-06 1.13175e-06 1.80337e-06 1.47175e-06 1.5318e-06 1.29699e-06 2.04204e-06 1.68108e-06 1.7087e-06 1.47096e-06 2.28899e-06 1.89925e-06 1.88657e-06 1.65306e-06 2.54003e-06 2.12292e-06 2.06535e-06 1.84249e-06 2.7933e-06 2.35044e-06 2.24878e-06 2.0382e-06 3.04836e-06 2.5807e-06 2.44417e-06 2.23893e-06 3.30462e-06 2.8123e-06 2.6552e-06 2.44336e-06 3.5614e-06 3.04355e-06 2.86923e-06 2.65004e-06 3.80982e-06 3.27352e-06 3.05632e-06 2.85724e-06 4.04715e-06 3.50153e-06 3.19867e-06 3.06228e-06 4.28206e-06 3.72754e-06 3.32829e-06 3.26418e-06 4.51438e-06 3.95168e-06 3.51149e-06 3.46212e-06 4.74394e-06 4.17168e-06 3.76098e-06 3.65597e-06 4.97059e-06 4.38261e-06 3.96275e-06 3.8464e-06 5.19414e-06 4.58225e-06 4.10857e-06 4.03446e-06 5.41428e-06 4.77482e-06 4.24793e-06 4.22073e-06 5.63042e-06 4.96872e-06 4.38017e-06 4.40477e-06 5.8416e-06 5.17029e-06 4.50431e-06 4.58628e-06 6.04628e-06 5.37733e-06 4.61887e-06 4.76658e-06 6.24222e-06 5.57341e-06 4.72178e-06 4.94625e-06 6.4264e-06 5.72448e-06 4.8105e-06 5.11335e-06 6.59494e-06 5.79536e-06 4.88368e-06 5.27681e-06 6.73662e-06 5.7921e-06 4.13047e-06 5.41713e-06 6.17311e-06 5.79126e-06 3.15035e-06 5.49272e-06 4.41127e-06 5.91141e-06 3.09239e-06 5.58396e-06 3.68634e-06 6.23699e-06 3.95947e-06 5.76404e-06 4.22295e-06 6.73064e-06 5.18115e-06 6.02128e-06 6.04476e-06 7.214e-06 5.24083e-06 6.21242e-06 7.92791e-06 7.41584e-06 5.29835e-06 6.35894e-06 8.17833e-06 7.58814e-06 5.35153e-06 6.50222e-06 8.4272e-06 7.75106e-06 5.401e-06 6.64137e-06 8.67282e-06 7.90329e-06 5.4458e-06 6.7754e-06 8.91861e-06 8.04335e-06 5.48424e-06 6.90425e-06 9.16054e-06 8.17009e-06 5.51548e-06 7.02786e-06 9.39841e-06 8.28285e-06 5.54139e-06 7.14536e-06 9.63397e-06 8.38148e-06 5.56506e-06 7.25737e-06 9.87041e-06 8.46582e-06 5.58213e-06 7.36651e-06 1.01124e-05 8.53519e-06 5.58797e-06 7.47539e-06 1.03688e-05 8.58975e-06 5.58517e-06 7.58663e-06 1.06473e-05 6.61134e-06 5.57599e-06 7.70336e-06 1.09493e-05 5.50122e-06 5.56152e-06 7.82873e-06 1.12723e-05 6.63982e-06 5.54138e-06 7.96354e-06 1.16139e-05 8.68387e-06 5.51472e-06 8.10726e-06 1.1972e-05 8.71769e-06 5.48171e-06 8.26077e-06 1.23443e-05 8.75977e-06 5.44403e-06 8.42618e-06 1.2728e-05 8.80609e-06 5.40606e-06 8.60535e-06 1.31201e-05 8.85833e-06 5.37272e-06 8.79985e-06 1.35171e-05 8.91796e-06 5.34679e-06 9.01073e-06 1.39148e-05 8.98615e-06 5.3295e-06 9.23836e-06 1.43092e-05 9.06335e-06 5.32071e-06 9.48232e-06 1.46961e-05 9.14596e-06 5.31891e-06 9.74124e-06 1.50703e-05 9.23391e-06 5.32289e-06 1.00138e-05 1.54276e-05 9.32741e-06 5.33215e-06 1.02966e-05 1.57623e-05 9.42555e-06 5.34592e-06 1.05836e-05 1.60746e-05 9.52763e-06 5.36309e-06 1.08705e-05 1.63592e-05 9.63183e-06 5.38233e-06 1.11521e-05 1.6609e-05 9.73496e-06 5.40238e-06 1.14218e-05 1.68198e-05 9.83262e-06 5.42222e-06 1.1674e-05 1.69876e-05 9.91912e-06 5.44103e-06 1.19015e-05 1.71087e-05 9.98978e-06 5.45817e-06 1.20996e-05 1.71801e-05 1.00368e-05 5.47197e-06 1.22642e-05 1.72008e-05 1.00532e-05 5.47999e-06 1.23959e-05 4.59397e-13 4.40441e-12 5.47868e-12 3.3971e-12 3.1664e-12 1.09016e-11 1.20192e-11 7.18705e-12 5.74501e-11 1.47156e-10 1.49937e-10 8.8496e-11 4.30706e-10 1.06361e-09 1.06381e-09 6.35783e-10 1.90837e-09 4.56117e-09 4.48875e-09 2.73281e-09 6.11159e-09 1.39972e-08 1.35413e-08 8.44541e-09 1.56594e-08 3.40177e-08 3.23406e-08 2.07642e-08 3.39704e-08 6.95058e-08 6.49868e-08 4.30991e-08 6.46222e-08 1.242e-07 1.14396e-07 7.84997e-08 1.10454e-07 1.99715e-07 1.81578e-07 1.28945e-07 1.72812e-07 2.95445e-07 2.65639e-07 1.9499e-07 2.51298e-07 4.09172e-07 3.64379e-07 2.75853e-07 3.44072e-07 5.37878e-07 4.74962e-07 3.69806e-07 4.48452e-07 6.7839e-07 5.8196e-07 4.74632e-07 5.60198e-07 8.15303e-07 6.92585e-07 5.8321e-07 6.60251e-07 9.56298e-07 8.08606e-07 6.8956e-07 7.62289e-07 1.1022e-06 9.29721e-07 8.00028e-07 8.6679e-07 1.25266e-06 1.0553e-06 9.1468e-07 9.73576e-07 1.40666e-06 1.18475e-06 1.03279e-06 1.08216e-06 1.56326e-06 1.31755e-06 1.15355e-06 1.19205e-06 1.72161e-06 1.45331e-06 1.27617e-06 1.30289e-06 1.88109e-06 1.59179e-06 1.39997e-06 1.41452e-06 2.04127e-06 1.73298e-06 1.52437e-06 1.52734e-06 2.20196e-06 1.87713e-06 1.64895e-06 1.64247e-06 2.36297e-06 2.02452e-06 1.77343e-06 1.76159e-06 2.52264e-06 2.1749e-06 1.89765e-06 1.8847e-06 2.68229e-06 2.32615e-06 2.02164e-06 2.00255e-06 2.84238e-06 2.47436e-06 2.14542e-06 2.1146e-06 3.00266e-06 2.62149e-06 2.26741e-06 2.21839e-06 3.16248e-06 2.77055e-06 2.38575e-06 2.31204e-06 3.32124e-06 2.92556e-06 2.50293e-06 2.39775e-06 3.47847e-06 3.08899e-06 2.61933e-06 2.48371e-06 3.63322e-06 3.26096e-06 2.73471e-06 2.58476e-06 3.78302e-06 3.44179e-06 2.84878e-06 2.72139e-06 3.92216e-06 3.63529e-06 2.96107e-06 2.91306e-06 4.04131e-06 3.84986e-06 3.07031e-06 3.16085e-06 4.13063e-06 4.0956e-06 3.17305e-06 3.43104e-06 4.18967e-06 4.37684e-06 3.26206e-06 3.67974e-06 4.24161e-06 4.68288e-06 3.32686e-06 3.84391e-06 4.3297e-06 4.98443e-06 3.35873e-06 3.96016e-06 4.48167e-06 5.2283e-06 3.36276e-06 3.82029e-06 4.68414e-06 5.43429e-06 3.37088e-06 3.50621e-06 4.89945e-06 5.62455e-06 3.42934e-06 3.32175e-06 5.09508e-06 5.75529e-06 3.55342e-06 3.49049e-06 5.2647e-06 5.89949e-06 3.71523e-06 4.00752e-06 5.43547e-06 6.08283e-06 3.88193e-06 4.6145e-06 5.65148e-06 6.29432e-06 4.03963e-06 4.91934e-06 5.93249e-06 6.50641e-06 4.18834e-06 5.04139e-06 6.23623e-06 6.70197e-06 4.32493e-06 5.15318e-06 6.36921e-06 6.88334e-06 4.42964e-06 5.25261e-06 6.33235e-06 7.03829e-06 4.468e-06 5.33661e-06 5.78803e-06 7.13325e-06 4.4216e-06 5.40086e-06 5.13421e-06 7.19877e-06 4.32912e-06 4.76223e-06 4.90944e-06 6.61602e-06 4.28131e-06 3.441e-06 5.40611e-06 5.41706e-06 4.35602e-06 2.73283e-06 6.47222e-06 4.34964e-06 4.54878e-06 2.73747e-06 7.15708e-06 3.92028e-06 4.75931e-06 3.44575e-06 7.2518e-06 4.22315e-06 4.88308e-06 4.7351e-06 7.34276e-06 5.30047e-06 4.91814e-06 5.72177e-06 7.42964e-06 6.88924e-06 4.91905e-06 5.76213e-06 7.51055e-06 8.1248e-06 4.90522e-06 5.79438e-06 7.58142e-06 8.37542e-06 4.88254e-06 5.81712e-06 7.63891e-06 8.58775e-06 4.85034e-06 5.82968e-06 7.67993e-06 8.80008e-06 4.80858e-06 5.8302e-06 7.70044e-06 9.01073e-06 4.75765e-06 5.81414e-06 7.69105e-06 9.21745e-06 4.69776e-06 5.77916e-06 4.90799e-06 9.41658e-06 4.62906e-06 5.72583e-06 3.5696e-06 9.60063e-06 4.55331e-06 5.65502e-06 3.86216e-06 9.48692e-06 4.47319e-06 5.56774e-06 5.70631e-06 8.53347e-06 4.39212e-06 5.46524e-06 7.48045e-06 8.71989e-06 4.31412e-06 5.35081e-06 7.43181e-06 1.01707e-05 4.24436e-06 5.22527e-06 7.36186e-06 1.03121e-05 4.18852e-06 5.09059e-06 7.26267e-06 1.04201e-05 4.15242e-06 4.95004e-06 7.13183e-06 1.05187e-05 4.14333e-06 4.80767e-06 6.97216e-06 1.06126e-05 4.1653e-06 4.66901e-06 6.78866e-06 1.0706e-05 4.2195e-06 4.53983e-06 6.58588e-06 1.08049e-05 4.30565e-06 4.42651e-06 6.36934e-06 1.0914e-05 4.42141e-06 1.17083e-11 7.42871e-12 8.8982e-12 9.49734e-12 2.52444e-11 1.25871e-11 1.67141e-11 1.65549e-11 3.11166e-10 1.35736e-10 1.88302e-10 1.78569e-10 2.1867e-09 9.80958e-10 1.3291e-09 1.26378e-09 9.06232e-09 4.24868e-09 5.59988e-09 5.34801e-09 2.66169e-08 1.30969e-08 1.68284e-08 1.61031e-08 6.14569e-08 3.17921e-08 3.99247e-08 3.82329e-08 1.18866e-07 6.46178e-08 7.95141e-08 7.62199e-08 2.01074e-07 1.14588e-07 1.38553e-07 1.33055e-07 3.06992e-07 1.82671e-07 2.17679e-07 2.09574e-07 4.33194e-07 2.67824e-07 3.15462e-07 3.04586e-07 5.75427e-07 3.67585e-07 4.29132e-07 4.15514e-07 7.12412e-07 4.77503e-07 5.50411e-07 5.39285e-07 8.55789e-07 5.82719e-07 6.7023e-07 6.58858e-07 1.00758e-06 6.94739e-07 7.98642e-07 7.84334e-07 1.16703e-06 8.13192e-07 9.35312e-07 9.168e-07 1.33351e-06 9.37421e-07 1.0797e-06 1.05545e-06 1.5067e-06 1.06693e-06 1.23126e-06 1.19959e-06 1.68693e-06 1.20147e-06 1.38915e-06 1.34856e-06 1.87538e-06 1.34109e-06 1.55239e-06 1.50166e-06 2.07319e-06 1.48619e-06 1.72101e-06 1.65842e-06 2.27837e-06 1.63691e-06 1.89866e-06 1.81925e-06 2.48251e-06 1.79205e-06 2.09496e-06 1.98641e-06 2.6753e-06 1.9497e-06 2.32169e-06 2.16365e-06 2.86171e-06 2.11232e-06 2.57633e-06 2.35242e-06 3.07848e-06 2.29318e-06 2.82004e-06 2.54573e-06 3.37527e-06 2.51273e-06 2.98806e-06 2.728e-06 3.75763e-06 2.77705e-06 3.05347e-06 2.89884e-06 4.11989e-06 3.02564e-06 3.08684e-06 3.0884e-06 4.36317e-06 3.21616e-06 3.21706e-06 3.33833e-06 4.6038e-06 3.40867e-06 3.53529e-06 3.6306e-06 4.84055e-06 3.60241e-06 4.00562e-06 3.82074e-06 5.07127e-06 3.7952e-06 4.45778e-06 4.01021e-06 4.90272e-06 3.98402e-06 4.71011e-06 4.19922e-06 4.37105e-06 4.16495e-06 4.9416e-06 4.38608e-06 4.09448e-06 4.33362e-06 5.17281e-06 4.56832e-06 4.60154e-06 4.35502e-06 5.403e-06 4.74235e-06 5.95769e-06 3.49348e-06 5.63165e-06 4.90359e-06 6.5987e-06 2.76283e-06 5.85835e-06 5.04683e-06 6.84302e-06 2.80124e-06 6.08252e-06 4.69814e-06 7.08138e-06 3.90335e-06 6.30354e-06 3.50216e-06 7.31096e-06 5.40655e-06 6.52061e-06 2.78828e-06 7.53024e-06 5.62867e-06 6.73266e-06 3.10149e-06 7.74373e-06 5.85083e-06 6.93876e-06 4.92633e-06 7.95463e-06 6.0761e-06 7.13796e-06 5.83393e-06 8.16237e-06 6.30138e-06 7.32851e-06 5.97773e-06 8.36617e-06 6.52443e-06 7.50793e-06 6.13851e-06 8.56548e-06 6.74374e-06 7.67281e-06 6.31635e-06 8.75995e-06 6.95856e-06 7.81869e-06 6.50908e-06 8.94948e-06 7.17083e-06 7.93984e-06 6.71315e-06 9.13433e-06 7.3804e-06 8.02938e-06 6.92497e-06 9.31509e-06 7.5873e-06 8.08005e-06 7.13747e-06 9.49276e-06 7.79159e-06 8.08585e-06 7.34363e-06 9.66889e-06 7.99329e-06 7.8086e-06 7.54236e-06 9.8556e-06 8.19215e-06 4.96243e-06 7.73499e-06 1.00606e-05 8.38776e-06 3.14293e-06 7.92319e-06 1.02925e-05 8.57968e-06 3.17151e-06 8.10879e-06 1.05557e-05 8.76783e-06 5.71905e-06 8.29336e-06 1.0848e-05 8.9524e-06 7.96027e-06 8.47797e-06 1.11669e-05 9.13335e-06 8.09339e-06 8.66344e-06 1.15103e-05 9.31065e-06 8.24025e-06 8.85127e-06 1.18757e-05 9.48441e-06 8.39346e-06 9.0419e-06 1.22601e-05 9.65504e-06 8.54911e-06 9.23649e-06 1.26601e-05 9.82313e-06 8.70449e-06 9.43582e-06 1.30718e-05 9.98893e-06 8.85732e-06 9.64028e-06 1.34906e-05 1.01521e-05 9.00588e-06 9.84986e-06 1.3911e-05 1.03101e-05 9.14896e-06 1.00641e-05 1.43267e-05 1.04607e-05 9.2854e-06 1.02822e-05 1.47306e-05 1.06026e-05 9.41453e-06 1.05026e-05 1.51133e-05 1.07334e-05 9.53573e-06 1.07242e-05 1.54662e-05 1.08521e-05 9.6479e-06 1.09457e-05 1.57761e-05 1.09588e-05 9.74951e-06 1.1165e-05 1.60356e-05 1.10533e-05 9.83231e-06 1.13795e-05 1.62342e-05 1.11347e-05 9.88933e-06 1.15867e-05 1.63635e-05 1.12017e-05 9.92126e-06 1.17801e-05 1.6435e-05 1.12511e-05 9.92941e-06 1.19577e-05 1.64706e-05 1.12775e-05 9.91479e-06 1.21128e-05 1.64728e-05 1.12771e-05 9.87833e-06 1.22436e-05 1.6439e-05 1.12412e-05 9.8208e-06 1.23468e-05 8.68375e-12 1.11002e-11 1.60196e-11 8.63042e-12 9.87397e-12 1.68923e-11 2.74083e-11 1.27606e-11 4.2067e-11 1.5983e-10 2.81666e-10 9.87853e-11 2.58044e-10 1.12755e-09 1.94862e-09 6.63224e-10 1.07486e-09 4.80467e-09 8.05607e-09 2.77301e-09 3.27839e-09 1.4595e-08 2.36793e-08 8.38435e-09 8.00816e-09 3.49833e-08 5.48888e-08 2.02097e-08 1.65973e-08 7.04113e-08 1.06957e-07 4.12038e-08 3.03269e-08 1.24065e-07 1.82881e-07 7.38857e-08 5.02018e-08 1.97199e-07 2.82965e-07 1.19796e-07 7.68249e-08 2.89232e-07 4.05426e-07 1.79293e-07 1.10389e-07 3.98348e-07 5.47366e-07 2.51685e-07 1.50757e-07 5.22172e-07 7.05676e-07 3.35581e-07 1.97582e-07 6.5194e-07 8.69161e-07 4.2924e-07 2.50435e-07 7.86434e-07 1.04095e-06 5.28418e-07 3.08899e-07 9.31645e-07 1.22509e-06 6.27002e-07 3.72635e-07 1.08763e-06 1.42117e-06 7.31556e-07 4.41417e-07 1.25431e-06 1.62876e-06 8.42194e-07 5.15119e-07 1.43166e-06 1.84743e-06 9.58685e-07 5.93385e-07 1.61968e-06 2.07676e-06 1.0808e-06 6.76164e-07 1.81857e-06 2.31606e-06 1.20834e-06 7.63462e-07 2.02872e-06 2.56382e-06 1.34111e-06 8.55324e-07 2.25063e-06 2.81723e-06 1.47892e-06 9.51816e-07 2.48379e-06 3.07303e-06 1.62164e-06 1.05302e-06 2.72487e-06 3.31614e-06 1.76919e-06 1.15899e-06 2.96024e-06 3.55943e-06 1.92145e-06 1.26972e-06 3.18672e-06 3.80274e-06 2.07779e-06 1.38513e-06 3.41573e-06 4.04556e-06 2.23625e-06 1.50503e-06 3.64688e-06 4.28718e-06 2.39307e-06 1.62914e-06 3.87951e-06 4.52694e-06 2.53877e-06 1.75718e-06 4.11299e-06 4.76409e-06 2.68251e-06 1.88885e-06 4.3467e-06 4.99785e-06 2.82477e-06 2.02382e-06 4.58009e-06 5.22737e-06 2.96506e-06 2.16178e-06 4.81266e-06 5.45177e-06 3.1029e-06 2.30235e-06 5.04402e-06 5.67015e-06 3.2379e-06 2.44493e-06 5.27388e-06 5.88162e-06 3.36973e-06 2.58831e-06 5.50212e-06 6.08529e-06 3.49822e-06 2.73033e-06 5.72876e-06 6.28036e-06 3.62337e-06 2.86811e-06 5.95396e-06 6.46617e-06 3.74543e-06 3.00767e-06 6.17777e-06 6.63421e-06 3.865e-06 3.14914e-06 6.39968e-06 6.78321e-06 3.98301e-06 3.29311e-06 6.61849e-06 6.95851e-06 4.10066e-06 3.44063e-06 6.83302e-06 7.14744e-06 4.2188e-06 3.59185e-06 7.04244e-06 7.29922e-06 4.33705e-06 3.74539e-06 7.2457e-06 7.4394e-06 4.45408e-06 3.90056e-06 7.44282e-06 7.56738e-06 4.56863e-06 4.05648e-06 7.63432e-06 7.68252e-06 4.67992e-06 4.21169e-06 7.81878e-06 7.78435e-06 4.78762e-06 4.36365e-06 7.99504e-06 7.87227e-06 4.89203e-06 4.50428e-06 8.16228e-06 7.94501e-06 4.99278e-06 4.6331e-06 8.32035e-06 8.00131e-06 5.08915e-06 4.7488e-06 8.46924e-06 8.04107e-06 5.18021e-06 4.84974e-06 8.60917e-06 8.06572e-06 5.26496e-06 4.7421e-06 8.74059e-06 8.07821e-06 5.34238e-06 3.5391e-06 8.86418e-06 8.08304e-06 5.4118e-06 2.62276e-06 8.98096e-06 8.08611e-06 5.47306e-06 2.49304e-06 9.09215e-06 8.09271e-06 5.52579e-06 3.27244e-06 9.19836e-06 8.10369e-06 5.56982e-06 4.95675e-06 9.29894e-06 8.11644e-06 5.60526e-06 5.37754e-06 9.39251e-06 8.1287e-06 5.63259e-06 5.44379e-06 9.47786e-06 8.13926e-06 5.65213e-06 5.49845e-06 9.55377e-06 8.14769e-06 5.66408e-06 5.53418e-06 9.61904e-06 8.15441e-06 5.66857e-06 5.54893e-06 9.67237e-06 8.16064e-06 5.66537e-06 5.54073e-06 9.71017e-06 8.16823e-06 5.65429e-06 5.50783e-06 9.73155e-06 8.17959e-06 5.63518e-06 5.44873e-06 9.73597e-06 8.19767e-06 5.60811e-06 5.36237e-06 9.72246e-06 8.22346e-06 5.5732e-06 5.24808e-06 9.68908e-06 8.25785e-06 5.5308e-06 5.10553e-06 9.63394e-06 8.30345e-06 5.48158e-06 4.93504e-06 9.55518e-06 8.36292e-06 5.42795e-06 4.73634e-06 9.45102e-06 8.43877e-06 5.37095e-06 4.51005e-06 9.31984e-06 8.53326e-06 5.31213e-06 4.0156e-06 9.16021e-06 8.64815e-06 5.25379e-06 3.13387e-06 8.97101e-06 8.7846e-06 5.19833e-06 2.52948e-06 8.75291e-06 8.94289e-06 5.14889e-06 2.34939e-06 8.5069e-06 9.12229e-06 5.10916e-06 2.47298e-06 8.23631e-06 9.32092e-06 5.08306e-06 2.36429e-06 7.94473e-06 9.53581e-06 5.0743e-06 1.71704e-05 1.0029e-05 5.48111e-06 1.24895e-05 1.70855e-05 9.9561e-06 5.47554e-06 1.25367e-05 1.6953e-05 9.86479e-06 5.46302e-06 1.25341e-05 1.67796e-05 9.7702e-06 5.44221e-06 1.24791e-05 1.65723e-05 9.66641e-06 5.413e-06 1.23775e-05 1.63376e-05 9.55393e-06 5.3755e-06 1.22442e-05 1.60815e-05 9.43558e-06 5.32995e-06 1.20878e-05 1.58093e-05 9.31609e-06 5.27652e-06 1.19135e-05 1.55247e-05 9.20109e-06 5.21536e-06 1.17266e-05 1.52423e-05 9.09634e-06 5.14663e-06 1.15314e-05 1.49602e-05 9.005e-06 5.07115e-06 1.13318e-05 1.46763e-05 6.64074e-06 4.99085e-06 1.11313e-05 1.43883e-05 3.93685e-06 4.90578e-06 1.09331e-05 1.40947e-05 3.87179e-06 4.81737e-06 1.07409e-05 1.3795e-05 6.89117e-06 4.72781e-06 1.05586e-05 1.34884e-05 9.04639e-06 4.63972e-06 1.03893e-05 1.31728e-05 9.11327e-06 4.55497e-06 1.02342e-05 1.28473e-05 9.14851e-06 4.47518e-06 6.64757e-06 1.25123e-05 9.14834e-06 4.40079e-06 4.32093e-06 1.21683e-05 9.11049e-06 4.33346e-06 4.84158e-06 1.18167e-05 9.0361e-06 4.28021e-06 9.69142e-06 1.14581e-05 8.92993e-06 4.24553e-06 9.82718e-06 1.10934e-05 8.79718e-06 4.22638e-06 9.83435e-06 1.07235e-05 8.64297e-06 4.22009e-06 9.8097e-06 1.03498e-05 8.4732e-06 4.21782e-06 9.74977e-06 9.97358e-06 8.29157e-06 4.20993e-06 9.65468e-06 9.59632e-06 8.10115e-06 4.19698e-06 9.5265e-06 9.21931e-06 7.90442e-06 4.17862e-06 9.36872e-06 8.84377e-06 7.70326e-06 4.15382e-06 9.18465e-06 8.4708e-06 7.49911e-06 4.12965e-06 8.97797e-06 8.10135e-06 7.293e-06 4.10544e-06 8.75216e-06 7.73627e-06 7.08566e-06 4.08062e-06 8.51065e-06 7.36979e-06 6.87762e-06 4.05485e-06 8.2567e-06 6.46172e-06 6.66925e-06 4.02771e-06 7.99325e-06 5.42736e-06 6.46091e-06 3.99863e-06 7.7229e-06 4.81935e-06 6.25214e-06 3.96705e-06 7.44788e-06 4.83864e-06 6.04259e-06 3.93249e-06 7.16991e-06 5.18782e-06 5.83218e-06 3.89452e-06 6.89057e-06 5.24381e-06 5.61851e-06 3.85284e-06 6.61142e-06 4.94021e-06 5.40206e-06 3.80713e-06 6.33379e-06 4.44284e-06 5.1835e-06 3.75697e-06 6.05895e-06 3.91752e-06 4.96358e-06 3.70178e-06 5.78627e-06 3.46743e-06 4.74301e-06 3.64088e-06 5.51341e-06 3.17409e-06 4.52255e-06 3.56481e-06 5.24104e-06 3.00501e-06 4.30285e-06 3.46566e-06 4.97028e-06 2.87101e-06 3.87139e-06 3.33952e-06 4.70221e-06 2.71358e-06 3.31422e-06 3.1895e-06 4.4096e-06 2.52557e-06 2.88873e-06 3.03725e-06 3.93399e-06 2.32344e-06 2.75085e-06 2.89937e-06 3.40089e-06 2.11847e-06 2.83271e-06 2.77446e-06 2.99195e-06 1.89192e-06 2.91745e-06 2.65258e-06 2.79906e-06 1.68413e-06 2.84157e-06 2.52764e-06 2.75016e-06 1.50245e-06 2.63476e-06 2.39935e-06 2.7023e-06 1.34092e-06 2.39067e-06 2.26893e-06 2.56113e-06 1.19382e-06 2.14692e-06 2.13585e-06 2.33765e-06 1.05773e-06 1.92197e-06 1.99542e-06 2.09432e-06 9.30894e-07 1.72923e-06 1.85088e-06 1.8747e-06 8.12476e-07 1.55873e-06 1.70599e-06 1.6824e-06 7.01955e-07 1.39921e-06 1.5616e-06 1.50692e-06 5.98688e-07 1.24507e-06 1.4179e-06 1.3399e-06 4.99898e-07 1.09529e-06 1.2751e-06 1.17839e-06 3.96847e-07 9.50693e-07 1.13361e-06 1.02253e-06 3.05206e-07 8.12238e-07 9.94168e-07 8.73277e-07 2.26256e-07 6.8053e-07 8.57771e-07 7.31205e-07 1.60825e-07 5.55426e-07 7.25631e-07 5.96139e-07 1.0904e-07 4.22521e-07 5.99097e-07 4.50392e-07 7.01655e-08 3.01992e-07 4.78908e-07 3.20191e-07 4.26437e-08 2.01196e-07 3.56145e-07 2.12034e-07 2.43518e-08 1.23206e-07 2.39479e-07 1.29042e-07 1.29818e-08 6.84469e-08 1.45554e-07 7.13095e-08 6.40083e-09 3.41185e-08 7.81178e-08 3.54363e-08 2.87809e-09 1.51024e-08 3.62182e-08 1.56933e-08 1.15412e-09 5.84866e-09 1.42274e-08 6.10576e-09 3.98251e-10 1.9264e-09 4.62469e-09 2.02842e-09 1.11437e-10 5.11179e-10 1.1894e-09 5.44651e-10 2.27853e-11 9.86595e-11 2.20331e-10 1.06611e-10 2.83198e-12 1.14323e-11 2.43222e-11 1.25185e-11 2.31353e-13 7.52178e-13 1.42639e-12 7.91947e-13 1.27856e-13 3.29571e-13 5.42857e-13 3.1281e-13 4.33564e-06 6.14613e-06 1.10371e-05 4.56245e-06 4.27352e-06 5.92422e-06 1.11709e-05 4.72012e-06 4.24573e-06 5.7141e-06 1.13069e-05 4.88579e-06 4.25448e-06 5.5225e-06 1.14408e-05 5.05368e-06 4.30073e-06 5.35451e-06 1.15685e-05 5.21912e-06 4.3827e-06 5.21351e-06 1.16816e-05 5.37818e-06 4.49569e-06 5.10157e-06 1.17748e-05 5.52752e-06 4.63388e-06 5.01983e-06 1.18425e-05 5.66432e-06 4.7904e-06 4.97117e-06 1.18795e-05 5.78619e-06 4.9587e-06 4.95818e-06 1.18858e-05 5.89119e-06 5.13165e-06 4.98099e-06 1.18654e-05 5.97786e-06 5.30202e-06 5.04076e-06 1.18196e-05 6.04532e-06 5.46685e-06 5.14073e-06 1.17478e-05 6.09328e-06 5.62497e-06 5.2878e-06 1.16499e-05 6.12308e-06 5.76921e-06 5.48164e-06 1.15265e-05 6.13898e-06 5.89449e-06 5.70251e-06 1.13797e-05 6.14578e-06 5.99927e-06 5.93266e-06 1.12126e-05 6.14745e-06 6.08348e-06 6.15968e-06 1.1028e-05 6.14858e-06 6.1473e-06 6.37403e-06 1.08346e-05 6.15395e-06 6.19115e-06 6.56853e-06 1.06307e-05 6.16798e-06 6.21557e-06 6.73803e-06 9.15092e-06 6.18173e-06 6.22131e-06 6.87916e-06 6.72595e-06 6.22458e-06 6.20922e-06 6.99009e-06 5.20254e-06 6.26861e-06 6.18033e-06 7.07021e-06 5.07905e-06 6.30334e-06 6.1358e-06 7.12013e-06 6.27014e-06 6.32676e-06 6.07695e-06 7.14187e-06 8.26199e-06 6.33475e-06 6.00522e-06 7.13775e-06 9.42541e-06 6.3245e-06 5.92249e-06 7.11037e-06 9.31738e-06 6.29451e-06 5.83141e-06 7.06247e-06 9.19207e-06 6.24454e-06 5.73433e-06 6.99755e-06 9.0352e-06 6.17544e-06 5.63191e-06 6.91957e-06 8.8498e-06 6.08746e-06 5.52323e-06 6.83032e-06 8.63905e-06 5.98121e-06 5.40795e-06 6.72895e-06 8.40491e-06 5.85835e-06 5.28738e-06 6.61447e-06 8.10201e-06 5.71999e-06 5.16355e-06 6.48592e-06 7.71546e-06 5.56644e-06 5.03416e-06 6.34293e-06 7.38339e-06 5.3999e-06 4.89237e-06 6.18387e-06 7.08147e-06 5.22221e-06 4.73971e-06 6.01072e-06 6.77012e-06 5.03494e-06 4.57744e-06 5.82565e-06 6.44344e-06 4.83945e-06 4.40673e-06 5.63055e-06 6.11602e-06 4.63701e-06 4.22872e-06 5.42714e-06 5.79922e-06 4.42879e-06 4.04459e-06 5.21689e-06 5.49444e-06 4.21605e-06 3.85551e-06 5.00116e-06 5.19843e-06 4.00015e-06 3.66264e-06 4.77229e-06 4.90859e-06 3.78239e-06 3.46701e-06 4.52832e-06 4.62442e-06 3.56399e-06 3.26961e-06 4.28164e-06 4.34707e-06 3.34613e-06 3.07139e-06 4.03497e-06 4.07841e-06 3.11782e-06 2.87328e-06 3.78613e-06 3.81928e-06 2.88802e-06 2.67623e-06 3.53227e-06 3.56839e-06 2.6597e-06 2.48112e-06 3.27577e-06 3.32349e-06 2.43461e-06 2.28884e-06 3.02313e-06 3.08323e-06 2.21516e-06 2.10019e-06 2.77966e-06 2.84758e-06 2.00324e-06 1.91589e-06 2.54648e-06 2.61686e-06 1.80156e-06 1.7366e-06 2.32041e-06 2.38867e-06 1.61207e-06 1.55219e-06 2.1043e-06 2.16688e-06 1.43518e-06 1.36242e-06 1.8978e-06 1.95472e-06 1.27027e-06 1.18586e-06 1.70035e-06 1.75243e-06 1.11654e-06 1.02599e-06 1.5119e-06 1.5598e-06 9.73464e-07 8.81835e-07 1.33269e-06 1.37677e-06 8.40764e-07 7.51348e-07 1.16311e-06 1.20347e-06 7.18286e-07 6.33119e-07 1.00353e-06 1.04017e-06 6.05829e-07 5.26155e-07 8.54318e-07 8.87178e-07 5.02719e-07 4.29214e-07 7.15758e-07 7.44801e-07 4.0243e-07 3.32747e-07 5.87519e-07 6.12731e-07 3.08144e-07 2.46796e-07 4.63061e-07 4.84669e-07 2.26721e-07 1.74515e-07 3.43469e-07 3.60552e-07 1.59138e-07 1.16633e-07 2.41246e-07 2.54147e-07 1.05739e-07 7.30257e-08 1.58625e-07 1.67832e-07 6.59878e-08 4.24778e-08 9.64613e-08 1.02595e-07 3.83805e-08 2.27756e-08 5.36119e-08 5.73742e-08 2.06444e-08 1.11624e-08 2.69287e-08 2.90216e-08 1.01768e-08 4.94192e-09 1.20754e-08 1.31139e-08 4.53968e-09 1.93887e-09 4.74972e-09 5.20006e-09 1.79607e-09 6.52481e-10 1.5901e-09 1.75536e-09 6.09665e-10 1.78121e-10 4.29396e-10 4.77953e-10 1.67875e-10 3.58469e-11 8.4944e-11 9.52664e-11 3.40929e-11 4.71348e-12 1.05742e-11 1.18877e-11 4.55016e-12 7.64821e-13 1.22126e-12 1.31116e-12 7.75707e-13 6.1813e-13 8.5456e-13 8.89478e-13 6.38328e-13 1.63515e-05 1.11624e-05 9.74888e-06 1.2421e-05 1.6193e-05 1.10287e-05 9.66821e-06 1.24563e-05 1.59869e-05 1.08632e-05 9.58108e-06 1.24473e-05 1.57366e-05 1.06965e-05 9.4848e-06 1.23953e-05 1.54496e-05 1.05294e-05 9.37654e-06 1.23087e-05 1.51359e-05 1.03541e-05 9.25602e-06 1.21956e-05 1.48075e-05 1.01692e-05 9.12475e-06 1.20604e-05 1.44762e-05 9.97642e-06 8.98355e-06 1.19071e-05 1.41537e-05 9.78005e-06 8.83312e-06 1.17388e-05 1.38542e-05 9.587e-06 8.67389e-06 1.15585e-05 1.07957e-05 9.40892e-06 8.5058e-06 1.13687e-05 6.08183e-06 7.93207e-06 8.32806e-06 1.11718e-05 4.77504e-06 3.97297e-06 8.13891e-06 1.09696e-05 5.82111e-06 3.30722e-06 7.93539e-06 1.07627e-05 9.49599e-06 4.49855e-06 7.71314e-06 1.05519e-05 1.36638e-05 7.61358e-06 7.46681e-06 1.03402e-05 1.39328e-05 1.0113e-05 7.20723e-06 1.01323e-05 1.39364e-05 1.02506e-05 6.96672e-06 9.93541e-06 1.38573e-05 1.03292e-05 6.7465e-06 9.48115e-06 1.37097e-05 1.03495e-05 6.54001e-06 5.56792e-06 1.35013e-05 1.03161e-05 6.34553e-06 3.8681e-06 1.32442e-05 1.02341e-05 6.1673e-06 4.06484e-06 1.2949e-05 1.01097e-05 6.01245e-06 5.88762e-06 1.26243e-05 9.95253e-06 5.87855e-06 8.54181e-06 1.22775e-05 9.76657e-06 3.06339e-06 9.74376e-06 1.19158e-05 9.55637e-06 2.29253e-06 9.7518e-06 1.05018e-05 9.32695e-06 2.90704e-06 9.71329e-06 7.44988e-06 9.07979e-06 4.71179e-06 9.63377e-06 6.18378e-06 7.13963e-06 6.17003e-06 9.51887e-06 6.66844e-06 5.07831e-06 6.20743e-06 9.37169e-06 8.35509e-06 4.90183e-06 6.20791e-06 9.19581e-06 9.66358e-06 6.22548e-06 6.17083e-06 8.99484e-06 9.46087e-06 7.77139e-06 6.10572e-06 8.77224e-06 9.15541e-06 7.74533e-06 6.01963e-06 8.53206e-06 8.83226e-06 7.55655e-06 5.9185e-06 8.27956e-06 8.49871e-06 7.34871e-06 5.80668e-06 8.01728e-06 8.16384e-06 7.1277e-06 5.6871e-06 7.74753e-06 7.82879e-06 6.89667e-06 5.56167e-06 7.47241e-06 7.49549e-06 6.65828e-06 5.43154e-06 7.19351e-06 7.16506e-06 6.4144e-06 5.29736e-06 6.91216e-06 6.8367e-06 6.16677e-06 5.15934e-06 6.62958e-06 6.51044e-06 5.91698e-06 5.01736e-06 6.34662e-06 6.1858e-06 5.66606e-06 4.87123e-06 6.06381e-06 5.86201e-06 5.41465e-06 4.72071e-06 5.78149e-06 5.53943e-06 5.16317e-06 4.56562e-06 5.4999e-06 5.21803e-06 4.91188e-06 4.30157e-06 5.21939e-06 4.89767e-06 4.66103e-06 3.91953e-06 4.94036e-06 4.57857e-06 4.41091e-06 3.67481e-06 4.66285e-06 4.26093e-06 4.16196e-06 3.59515e-06 4.38702e-06 3.94526e-06 3.91359e-06 3.57258e-06 4.11315e-06 3.63226e-06 3.6657e-06 3.48373e-06 3.84159e-06 3.32276e-06 3.41958e-06 3.29448e-06 3.5725e-06 3.01776e-06 3.17552e-06 3.05329e-06 3.30409e-06 2.71843e-06 2.93375e-06 2.81518e-06 3.03697e-06 2.42615e-06 2.69469e-06 2.59979e-06 2.77219e-06 2.14248e-06 2.45822e-06 2.40047e-06 2.51098e-06 1.86919e-06 2.22415e-06 2.20434e-06 2.25462e-06 1.60822e-06 1.98669e-06 2.00912e-06 2.00447e-06 1.36172e-06 1.75383e-06 1.81592e-06 1.75981e-06 1.13185e-06 1.52999e-06 1.62638e-06 1.52292e-06 9.20745e-07 1.31794e-06 1.44173e-06 1.30024e-06 7.30397e-07 1.11958e-06 1.26289e-06 1.09409e-06 5.62575e-07 9.36104e-07 1.09082e-06 8.97338e-07 4.18627e-07 7.58698e-07 9.26588e-07 7.15746e-07 2.99249e-07 5.93276e-07 7.71463e-07 5.51323e-07 2.04203e-07 4.44684e-07 6.26783e-07 4.06535e-07 1.32178e-07 3.16057e-07 4.93008e-07 2.84059e-07 8.06375e-08 2.1035e-07 3.55021e-07 1.85874e-07 4.60672e-08 1.29279e-07 2.35941e-07 1.12469e-07 2.44712e-08 7.23369e-08 1.42107e-07 6.21511e-08 1.19789e-08 3.6362e-08 7.58247e-08 3.10041e-08 5.33237e-09 1.62101e-08 3.50612e-08 1.37954e-08 2.11347e-09 6.30373e-09 1.37642e-08 5.38396e-09 7.20577e-10 2.079e-09 4.47304e-09 1.7898e-09 1.99538e-10 5.51847e-10 1.1492e-09 4.80401e-10 4.06632e-11 1.07012e-10 2.12686e-10 9.44576e-11 5.26813e-12 1.29416e-11 2.38549e-11 1.16579e-11 6.76052e-13 1.37458e-12 1.94195e-12 1.31727e-12 4.8789e-13 9.13196e-13 1.18404e-12 8.99355e-13 1.91931e-06 7.63861e-06 9.76378e-06 5.08608e-06 1.46654e-06 7.32785e-06 9.99662e-06 5.11629e-06 1.03535e-06 7.02231e-06 1.022e-05 5.16065e-06 6.48734e-07 6.73208e-06 1.04322e-05 5.21532e-06 3.27021e-07 6.46439e-06 1.06324e-05 5.27777e-06 9.81214e-08 6.22525e-06 1.08193e-05 5.34514e-06 1.93572e-08 6.01934e-06 1.09899e-05 5.41392e-06 8.80442e-08 5.85001e-06 1.11419e-05 5.48175e-06 8.0345e-08 5.71931e-06 1.12734e-05 5.54685e-06 7.77011e-08 5.63147e-06 1.13831e-05 5.60785e-06 7.7829e-08 5.58772e-06 1.14701e-05 5.66363e-06 8.3181e-09 5.58378e-06 1.15339e-05 5.71335e-06 2.69397e-07 5.61626e-06 1.15746e-05 5.75635e-06 6.38908e-07 5.68939e-06 1.15923e-05 5.79213e-06 1.02971e-06 5.80518e-06 1.15876e-05 5.82025e-06 1.40136e-06 5.9473e-06 1.15616e-05 5.84042e-06 1.74125e-06 6.10004e-06 1.15163e-05 5.85504e-06 2.04638e-06 6.25199e-06 1.1454e-05 5.84765e-06 2.31765e-06 6.39558e-06 1.13749e-05 5.4267e-06 2.5575e-06 6.52588e-06 1.1279e-05 5.07412e-06 2.76882e-06 6.6397e-06 1.11664e-05 5.12494e-06 2.93493e-06 6.73526e-06 1.1037e-05 5.54399e-06 3.05049e-06 6.81192e-06 1.08899e-05 5.99636e-06 3.13448e-06 6.86686e-06 1.07249e-05 6.04659e-06 3.18579e-06 6.90064e-06 1.0542e-05 6.07506e-06 3.24562e-06 6.91439e-06 1.03425e-05 6.09295e-06 3.3596e-06 6.90923e-06 1.01305e-05 6.09768e-06 3.51522e-06 6.8862e-06 9.91205e-06 6.08514e-06 3.64737e-06 6.84625e-06 9.6895e-06 6.02112e-06 3.71748e-06 6.78999e-06 9.46307e-06 5.95248e-06 3.71061e-06 6.71764e-06 9.23256e-06 5.87341e-06 3.62852e-06 6.57242e-06 8.99836e-06 5.78282e-06 3.51447e-06 6.39783e-06 8.75984e-06 5.68335e-06 3.41379e-06 6.21715e-06 8.51695e-06 5.54514e-06 3.34384e-06 5.99736e-06 8.27009e-06 5.3132e-06 3.30182e-06 5.73267e-06 7.82327e-06 4.99518e-06 3.27643e-06 5.46902e-06 7.27424e-06 4.66931e-06 3.2529e-06 5.25349e-06 6.77477e-06 4.41094e-06 3.2181e-06 5.09615e-06 6.416e-06 4.24431e-06 3.16683e-06 4.97473e-06 6.18384e-06 4.14506e-06 3.10096e-06 4.85835e-06 6.0086e-06 4.06948e-06 3.02497e-06 4.72635e-06 5.82898e-06 3.98044e-06 2.94314e-06 4.57321e-06 5.62016e-06 3.86067e-06 2.85824e-06 4.40309e-06 5.38699e-06 3.71188e-06 2.77081e-06 4.22208e-06 5.14361e-06 3.54511e-06 2.67979e-06 4.03455e-06 4.89907e-06 3.37103e-06 2.5841e-06 3.84439e-06 4.65461e-06 3.19549e-06 2.4834e-06 3.65651e-06 4.40824e-06 3.02046e-06 2.37787e-06 3.47473e-06 4.15981e-06 2.84685e-06 2.26757e-06 3.29834e-06 3.91168e-06 2.67603e-06 2.15098e-06 3.12291e-06 3.66652e-06 2.50834e-06 2.01981e-06 2.94434e-06 3.42564e-06 2.33926e-06 1.87838e-06 2.76108e-06 3.18894e-06 2.16786e-06 1.74066e-06 2.57342e-06 2.95565e-06 1.99843e-06 1.6072e-06 2.38079e-06 2.7247e-06 1.8313e-06 1.47632e-06 2.18355e-06 2.4932e-06 1.66668e-06 1.34658e-06 1.98864e-06 2.26483e-06 1.50511e-06 1.21737e-06 1.79761e-06 2.04186e-06 1.34721e-06 1.08886e-06 1.61083e-06 1.82517e-06 1.19364e-06 9.61609e-07 1.42872e-06 1.61544e-06 1.04507e-06 8.34942e-07 1.25202e-06 1.41344e-06 9.02223e-07 6.88025e-07 1.0818e-06 1.22015e-06 7.6077e-07 5.48595e-07 9.19217e-07 1.03663e-06 6.12278e-07 4.20497e-07 7.64177e-07 8.63312e-07 4.75542e-07 3.07604e-07 6.00696e-07 6.87598e-07 3.53887e-07 2.1312e-07 4.49977e-07 5.21166e-07 2.50306e-07 1.38818e-07 3.18691e-07 3.74633e-07 1.66851e-07 8.44582e-08 2.10804e-07 2.52243e-07 1.03967e-07 4.77403e-08 1.28557e-07 1.56895e-07 6.01214e-08 2.49472e-08 7.13965e-08 8.89002e-08 3.20577e-08 1.1973e-08 3.5719e-08 4.52984e-08 1.56493e-08 5.21837e-09 1.59213e-08 2.04971e-08 6.91724e-09 2.02447e-09 6.2222e-09 8.10216e-09 2.71573e-09 6.75354e-10 2.07046e-09 2.71883e-09 9.15681e-10 1.82573e-10 5.55321e-10 7.34025e-10 2.50097e-10 3.59648e-11 1.08355e-10 1.44084e-10 4.98188e-11 4.20482e-12 1.2671e-11 1.7025e-11 5.95031e-12 2.09528e-13 8.01119e-13 1.18764e-12 3.76649e-13 3.5811e-14 3.17316e-13 5.56102e-13 1.43025e-13 ) ; boundaryField { leftWall { type nutUWallFunction; Cmu 0.09; kappa 0.41; E 9.8; value uniform 0; } rightWall { type nutUWallFunction; Cmu 0.09; kappa 0.41; E 9.8; value uniform 0; } leftSides_periodic0 { type cyclic; } leftSides_periodic1 { type cyclic; } rightSides_periodic0 { type cyclic; } rightSides_periodic1 { type cyclic; } leftInOut_periodic0 { type cyclic; } leftInOut_periodic1 { type cyclic; } rightInOut_periodic0 { type cyclic; } rightInOut_periodic1 { type cyclic; } } // ************************************************************************* //
[ "tong011@e.ntu.edu.sg" ]
tong011@e.ntu.edu.sg
b145a1d94f9e0d51e9c6bd9b8e35e77fcc2327df
8d5fe26b90cf4115cb6ba1c702502b507cf4f40b
/iPrintableDocumentDeal/MsOffice/Excel2010/CDialogs.h
54ca22f22b6388e886b24c5d6b5be4c812a48be5
[]
no_license
radtek/vs2015PackPrj
c6c6ec475014172c1dfffab98dd03bd7e257b273
605b49fab23cb3c4a427d48080ffa5e0807d79a7
refs/heads/master
2022-04-03T19:50:37.865876
2020-01-16T10:09:37
2020-01-16T10:09:37
null
0
0
null
null
null
null
GB18030
C++
false
false
1,670
h
// 从类型库向导中用“添加类”创建的计算机生成的 IDispatch 包装类 #import "C:\\Program Files (x86)\\Microsoft Office\\Office14\\EXCEL.EXE" no_namespace // CDialogs 包装类 class CDialogs : public COleDispatchDriver { public: CDialogs(){} // 调用 COleDispatchDriver 默认构造函数 CDialogs(LPDISPATCH pDispatch) : COleDispatchDriver(pDispatch) {} CDialogs(const CDialogs& dispatchSrc) : COleDispatchDriver(dispatchSrc) {} // 属性 public: // 操作 public: // Dialogs 方法 public: LPDISPATCH get_Application() { LPDISPATCH result; InvokeHelper(0x94, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); return result; } long get_Creator() { long result; InvokeHelper(0x95, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } LPDISPATCH get_Parent() { LPDISPATCH result; InvokeHelper(0x96, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); return result; } long get_Count() { long result; InvokeHelper(0x76, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } LPDISPATCH get_Item(long Index) { LPDISPATCH result; static BYTE parms[] = VTS_I4 ; InvokeHelper(0xaa, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, parms, Index); return result; } LPDISPATCH get__Default(long Index) { LPDISPATCH result; static BYTE parms[] = VTS_I4 ; InvokeHelper(0x0, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, parms, Index); return result; } LPUNKNOWN get__NewEnum() { LPUNKNOWN result; InvokeHelper(0xfffffffc, DISPATCH_PROPERTYGET, VT_UNKNOWN, (void*)&result, NULL); return result; } // Dialogs 属性 public: };
[ "1007482035@qq.com" ]
1007482035@qq.com
ac92d11ad062043d979dc9cf757c2bc524a2730f
a4cc03a687fec33fb986990cf053c1a04804b6f1
/allwinner/bluetooth/ampak/3rdparty/embedded/bsa_examples/linux/libbtapp/include/bluetooth_socket.h
28a7cbb5289c3adc4000c7d41856da0ef0cb2bcb
[]
no_license
lindenis-org/lindenis-v833-package
93768d5ab5c6af90e67bca2b4ed22552ab5d8ae8
220e01731729a86a0aac2a9f65e20a0176af4588
refs/heads/master
2023-05-11T22:20:40.949440
2021-05-26T09:42:15
2021-05-27T08:24:18
371,616,812
6
2
null
null
null
null
UTF-8
C++
false
false
4,026
h
#ifndef __BLUETOOTH_SOCKET_H__ #define __BLUETOOTH_SOCKET_H__ #include <string.h> #include <pthread.h> #include <errno.h> #include <signal.h> #include <unistd.h> #include <unistd.h> #define BT_NAME_PATH_LEN 256 #ifndef BT_ADDR_LEN #define BT_ADDR_LEN 6 typedef unsigned char BT_ADDR[BT_ADDR_LEN]; #endif #define BT_AVK_ENABLE 1 #define BT_HS_ENABLE 1 #define BT_BLE_ENABLE 1 enum BT_EVENT{ BT_AVK_CONNECTED_EVT = 0, BT_AVK_DISCONNECTED_EVT, BT_AVK_START_EVT, /* stream data transfer started */ BT_AVK_STOP_EVT, /* stream data transfer stopped */ BT_AVK_CONNECT_COMPLETED_EVT, BT_HS_CONNECTED_EVT = 0xf0, BT_HS_DISCONNECTED_EVT, BT_HS_RING_EVT, BT_HS_OK_EVT, BT_DISCOVER_COMPLETE, BT_HS_ERROR_EVT }; enum BLE_EVENT{ BLE_SE_CONNECTED_EVT = 0, BLE_SE_DISCONNECTED_EVT = 1, BLE_SE_READ_EVT = 2, BLE_SE_WRITE_EVT }; typedef void (tBtCallback)(BT_EVENT event, void *reply, int *len); typedef void (tBleCallback)(BLE_EVENT event, void *reply, int *len); #ifndef AVK_MUSIC_INFO_LEN_MAX #define AVK_MUSIC_INFO_LEN_MAX 102 #endif typedef struct{ unsigned char title[AVK_MUSIC_INFO_LEN_MAX]; unsigned char artist[AVK_MUSIC_INFO_LEN_MAX]; unsigned char album[AVK_MUSIC_INFO_LEN_MAX]; }tBT_AVK_MUSIC_INFO; typedef struct{ int server_num; int service_num; int char_attr_num; char *attr_uuid; unsigned char *value; int len; }tBleCallbackData; class c_bt { public: c_bt(); virtual ~c_bt(); private: char bt_wd[256]; tBtCallback *pBtCb; tBleCallback *pBleCb; int bt_on_status; public: int bt_on(char *bt_addr); int bt_on_no_avrcp(char *bt_addr); int bt_off(); int set_bt_name(const char *bt_name); // strlen(bt_name) <= MAX_DATA_T_LEN-1 int get_bd_addr(unsigned char bd_addr[]); int set_dev_discoverable(int enable); int set_dev_connectable(int enable); int start_discovery(int time); int get_disc_results(char *disc_results, int *len); int connect_auto(); int connect_dev_by_addr(BT_ADDR bt_addr); int disconnect(); int reset_avk_status(); int avk_play(); int avk_pause(); int avk_stop(); int avk_close_pcm_alsa(); int avk_resume_pcm_alsa(); int avk_previous(); int avk_next(); int avk_set_volume_up(); int avk_set_volume_down(); int avk_get_music_info(tBT_AVK_MUSIC_INFO *p_avk_music_info); int hs_pick_up(); int hs_hung_up(); void set_callback(tBtCallback *pCb); void event_callback(BT_EVENT bt_event, void *reply, int *len); int ble_server_register(unsigned short uuid, tBleCallback *p_cback); int ble_server_deregister(int server_num); int ble_server_create_service(int server_num, const char *service_uuid128, int char_num, int is_primary); int ble_server_add_char(int server_num, int service_num, const char *char_uuid128, int is_descript, unsigned short attribute_permission, unsigned short characteristic_property); int ble_server_start_service(int server_num, int srvc_attr_num); int ble_server_config_adv_data(const char *srvc_uuid128_array, unsigned char app_ble_adv_value[], int data_len, unsigned short appearance_data, int is_scan_rsp); int ble_server_send_data(int server_num, int attr_num, unsigned char data[], int data_len); int set_ble_discoverable(int enable); int set_ble_connectable(int enable); void ble_event_callback(BLE_EVENT ble_event, void *reply, int *len); int ble_server_send_read_rsp(void *p_cb_reply, unsigned char data[], int data_len); void do_test(); int initial_disc_param(); int set_discovery_callback(void *u_custom_disc_cback); int set_discovery_bd_addr(unsigned char bt_addr[]); int set_discovery_name(char bt_name[]); int start_discovery_with_get_rssi(); int get_disc_results_with_rssi(char *disc_results, int *len); int convert_str_to_ad(unsigned char bd_ad[], char *pts); }; #endif /* __BLUETOOTH_CLIENT_H__ */
[ "given@lindeni.com" ]
given@lindeni.com
2957d7736f6ab45cde2797d77d9d59a58d3cc1df
31853223d642cbbd400432cfe97451c38fda5e71
/faceRecognition/test/test_network_shell.cpp
511410e09d986a186f81984e33fd79076361536f
[]
no_license
yuqj1991/face
02793d3f084bfbfc4e7e428038099b6d437d9e86
b0a2336aa6e7451bd8be1f2ac9774c9d604f712f
refs/heads/master
2022-04-04T06:02:42.951473
2020-02-11T02:38:06
2020-02-11T02:38:06
221,836,672
3
1
null
null
null
null
UTF-8
C++
false
false
886
cpp
#include <pthread.h> #include <unistd.h> #include <readline/readline.h> #include <string.h> #include "network_shell.hpp" #include <malloc.h> void test_cmd(int argc, char ** argv) { for(int i=0;i<argc;i++) { printf("argv[%d]=%s\n",i,argv[i]); } } void * only_for_quit(void * arg) { printf("will quit whole net shell\n"); quit_network_shell(0); return NULL; } void exit_cmd(int argc, char ** argv) { pthread_t tr; pthread_create(&tr,NULL,only_for_quit,NULL); } int test_thread_mode=0; int main(int argc, char * argv[]) { init_network_shell(); register_network_shell_cmd("test",test_cmd,"test","this is a test command"); register_network_shell_cmd("exit",exit_cmd,"test","this will exit whole net shell"); if(test_thread_mode) { create_network_shell_thread("thread>",8080); sleep(-1); } else { run_network_shell("TEST>",8080); } return 0; }
[ "tonny.yu@honeywell.com" ]
tonny.yu@honeywell.com
b6936c1facdafd9ae610e930ebd7947df2d3a600
eea72893d7360d41901705ee4237d7d2af33c492
/src/track/trafdic/src/THlxNpassExtrap.cc
c70cbd5fad9d542d903bf7e50c5675caedc5a7ca
[]
no_license
lsilvamiguel/Coral.Efficiencies.r14327
5488fca306a55a7688d11b1979be528ac39fc433
37be8cc4e3e5869680af35b45f3d9a749f01e50a
refs/heads/master
2021-01-19T07:22:59.525828
2017-04-07T11:56:42
2017-04-07T11:56:42
87,541,002
0
0
null
null
null
null
UTF-8
C++
false
false
9,932
cc
/*! Member function of class Helix to extrapolate it to position of helix Hout (at the beginning, only fixed coordinate have to be preset). Hout will be overwritten by resulting helix Numerical Helix extrapolation with numericaly calculated Jacobian, used in cov. matrix propagation. If Hcov[0] is set to 0, cov. matrix is not propagated Obsolete. */ #include <iostream> #include <iomanip> #include "TOpt.h" #include "TAlgo.h" #include "TConstants.h" #include "TDisplay.h" #include "THlx.h" #include "TMtx.h" using namespace std; bool THlx::NpassExtrap(THlx& Hout) const { double xlast = Hout.Hpar[0]; double xfirst= Hpar[0]; if(fabs(xlast-xfirst) < TConstants_RKuttaMinStep) { // very short step Hout = (*this); return(true); } int i,j,k,ier; double dx, dummy[3]; double f[5][5]; double w[5]; double vin[6],vout[6], vecin[6], vecout[6]; double xx; const int nstp = int(fabs(xlast-xfirst)/TOpt::dCut[3]); // N steps for field probing bool helix; // "false" means "use straight line extrapolation" // increments for numerical Jacobian calculation const double dvin[6]={0.0, 1.e-4, 1.e-4, 1.e-5, 1.e-5, 1.e-5}; // infinit momentum ? (q/P == 0) if(Hpar[5] == 0){ helix=false; goto do_extrap; } helix=true; goto do_extrap; ///tmp - always R.-Kutta extrap. // Probe the field assuming straight line trajectory xx = xfirst; for(int ii=0; ii <= nstp; ii++){ dummy[0]=xx; dx=dummy[0]-xfirst; dummy[1]=Hpar[1]+Hpar[3]*dx; dummy[2]=Hpar[2]+Hpar[4]*dx; if(TAlgo::Field(dummy,dummy) > TOpt::dCut[1]) { helix = true; goto do_extrap;} // there is a field on the way xx+=(xlast-xfirst)/nstp; } do_extrap: if(!helix){ // straight line case dx=Hout.Hpar[0]-Hpar[0]; Hout.Hpar[1]=Hpar[1]+Hpar[3]*dx; Hout.Hpar[2]=Hpar[2]+Hpar[4]*dx; Hout.Hpar[3]=Hpar[3]; Hout.Hpar[4]=Hpar[4]; Hout.Hpar[5]=Hpar[5]; if(Hcov[0]==0) goto end; // only track. par. extrap. // Cov matrix propagation Hout.Hcov[0] = Hcov[0] + Hcov[3]*dx + (Hcov[3] + Hcov[5]*dx)*dx; Hout.Hcov[1] = Hcov[1] + Hcov[6]*dx + (Hcov[4] + Hcov[8]*dx)*dx; Hout.Hcov[2] = Hcov[2] + Hcov[7]*dx + (Hcov[7] + Hcov[9]*dx)*dx; Hout.Hcov[3] = Hcov[3] + Hcov[5]*dx; Hout.Hcov[4] = Hcov[4] + Hcov[8]*dx; Hout.Hcov[5] = Hcov[5]; Hout.Hcov[6] = Hcov[6] + Hcov[8]*dx; Hout.Hcov[7] = Hcov[7] + Hcov[9]*dx; Hout.Hcov[8] = Hcov[8]; Hout.Hcov[9] = Hcov[9]; Hout.Hcov[10]= Hcov[10]+ Hcov[12]*dx; Hout.Hcov[11]= Hcov[11]+ Hcov[13]*dx; Hout.Hcov[12]= Hcov[12]; Hout.Hcov[13]= Hcov[13]; Hout.Hcov[14]= Hcov[14]; Hout.path = this->Dist(Hout); Hout.radLenFr = 0; } else { // helix case // cut on P < 100 MeV if(fabs(1./Hpar[5]) < 0.100) { //cout<<"THlx::Extrapolate() ==> too low momentum for Runge-Kutta propagation : " //<<fabs(1./Hpar[5]) <<" GeV"<<endl; return(false); } //Extrapolate state vector by Runge Kutta ier=TAlgo::Rkutex(this->Hpar, Hout.Hpar); if(ier != 0 ) { cout<<"THlx::Extrapolate() ==> (vec.) TAlgo::Rkutex error # "<<ier; cout<<" Momentum = "<<1./Hpar[5]<<" Gev"<<endl; return(false); } if(Hcov[0]==0) goto end; // only track. par. extrap. bool flg_sav(false); if(TDisplay::Ptr() != NULL){ // if TDisplay object exists flg_sav=TDisplay::Ref().Rkutraj(); TDisplay::Ref().SetRkutraj(false); // never draw traj. in Jacobian calculation } //Numerical calculation of Jacobian f[5][5] for helix propagation in magnetic field for(i = 1; i <= 2; i++){ for(j = 1; j <= 5; j++){ if(i==j){ f[j-1][i-1]=1.; } else { f[j-1][i-1]=0.; } } } for(k = 0; k < 6; k++) vin[k]=Hpar[k]; for(i = 3; i <= 5; i++){ vin[i]+=dvin[i]; // increment i-th component vout[0]=xlast; ier=TAlgo::Rkutex(vin,vout); // extrapolate if(ier!=0) { cout<<"THlx::Extrapolate() ==> (cov.) TAlgo::Rkutex error # "<<ier; cout<<" Momentum = "<<1./Hpar[5]<<" Gev"<<endl; return(false); } for(j = 1; j <= 5; j++){ f[j-1][i-1]=(vout[j]-Hout.Hpar[j])/dvin[i]; // jacobian element dVout(j)/dVin(i) } vin[i]=Hpar[i]; // Restore i-th component } f[4][0]=0.; f[4][1]=0.; f[4][2]=0.; f[4][3]=0.; f[4][4]=1.; if(TDisplay::Ptr() != NULL){ // if TDisplay object exists TDisplay::Ref().SetRkutraj(flg_sav); // reset prev. status of this flag } /* cout<<endl; cout<<endl; cout<<" dY1/dY0 ="<< f[0][0]<<endl; cout<<" dZ1/dY0 ="<< f[1][0]<<endl; cout<<" dYp/dY0 ="<< f[2][0]<<endl; cout<<" dZp/dY0 ="<< f[3][0]<<endl; cout<<" dPi/dY0 ="<< f[4][0]<<endl; cout<<endl; cout<<" dY1/dZ0 ="<< f[0][1]<<endl; cout<<" dZ1/dZ0 ="<< f[1][1]<<endl; cout<<" dYp/dZ0 ="<< f[2][1]<<endl; cout<<" dZp/dZ0 ="<< f[3][1]<<endl; cout<<" dPi/dZ0 ="<< f[4][1]<<endl; */ // cout<<"dY/dPinv = "<<f[0][4]<<" dZ/dPinv = "<<f[1][4]<<endl; // Propagate Cov matrix (F*Cov*F.t) w[0]=Hcov[0] * f[0][0] + Hcov[1] * f[0][1] + Hcov[3] * f[0][2] + Hcov[6] * f[0][3] + Hcov[10]*f[0][4]; w[1]=Hcov[1] * f[0][0] + Hcov[2] * f[0][1] + Hcov[4] * f[0][2] + Hcov[7] * f[0][3] + Hcov[11]*f[0][4]; w[2]=Hcov[3] * f[0][0] + Hcov[4] * f[0][1] + Hcov[5] * f[0][2] + Hcov[8] * f[0][3] + Hcov[12]*f[0][4]; w[3]=Hcov[6] * f[0][0] + Hcov[7] * f[0][1] + Hcov[8] * f[0][2] + Hcov[9] * f[0][3] + Hcov[13]*f[0][4]; w[4]=Hcov[10]* f[0][0] + Hcov[11]* f[0][1] + Hcov[12]* f[0][2] + Hcov[13]* f[0][3] + Hcov[14]*f[0][4]; Hout.Hcov[0]=w[0]*f[0][0] + w[1]*f[0][1] + w[2]*f[0][2] + w[3]*f[0][3] + w[4]*f[0][4]; w[0]=Hcov[0] * f[1][0] + Hcov[1] * f[1][1] + Hcov[3] * f[1][2] + Hcov[6] * f[1][3] + Hcov[10]*f[1][4]; w[1]=Hcov[1] * f[1][0] + Hcov[2] * f[1][1] + Hcov[4] * f[1][2] + Hcov[7] * f[1][3] + Hcov[11]*f[1][4]; w[2]=Hcov[3] * f[1][0] + Hcov[4] * f[1][1] + Hcov[5] * f[1][2] + Hcov[8] * f[1][3] + Hcov[12]*f[1][4]; w[3]=Hcov[6] * f[1][0] + Hcov[7] * f[1][1] + Hcov[8] * f[1][2] + Hcov[9] * f[1][3] + Hcov[13]*f[1][4]; w[4]=Hcov[10]* f[1][0] + Hcov[11]* f[1][1] + Hcov[12]* f[1][2] + Hcov[13]* f[1][3] + Hcov[14]*f[1][4]; Hout.Hcov[1]=w[0]*f[0][0] + w[1]*f[0][1] + w[2]*f[0][2] + w[3]*f[0][3] + w[4]*f[0][4]; Hout.Hcov[2]=w[0]*f[1][0] + w[1]*f[1][1] + w[2]*f[1][2] + w[3]*f[1][3] + w[4]*f[1][4]; w[0]=Hcov[0] * f[2][0] + Hcov[1] * f[2][1] + Hcov[3] * f[2][2] + Hcov[6] * f[2][3] + Hcov[10]*f[2][4]; w[1]=Hcov[1] * f[2][0] + Hcov[2] * f[2][1] + Hcov[4] * f[2][2] + Hcov[7] * f[2][3] + Hcov[11]*f[2][4]; w[2]=Hcov[3] * f[2][0] + Hcov[4] * f[2][1] + Hcov[5] * f[2][2] + Hcov[8] * f[2][3] + Hcov[12]*f[2][4]; w[3]=Hcov[6] * f[2][0] + Hcov[7] * f[2][1] + Hcov[8] * f[2][2] + Hcov[9] * f[2][3] + Hcov[13]*f[2][4]; w[4]=Hcov[10]* f[2][0] + Hcov[11]* f[2][1] + Hcov[12]* f[2][2] + Hcov[13]* f[2][3] + Hcov[14]*f[2][4]; Hout.Hcov[3]=w[0]*f[0][0] + w[1]*f[0][1] + w[2]*f[0][2] + w[3]*f[0][3] + w[4]*f[0][4]; Hout.Hcov[4]=w[0]*f[1][0] + w[1]*f[1][1] + w[2]*f[1][2] + w[3]*f[1][3] + w[4]*f[1][4]; Hout.Hcov[5]=w[0]*f[2][0] + w[1]*f[2][1] + w[2]*f[2][2] + w[3]*f[2][3] + w[4]*f[2][4]; w[0]=Hcov[0] * f[3][0] + Hcov[1] * f[3][1] + Hcov[3] * f[3][2] + Hcov[6] * f[3][3] + Hcov[10]*f[3][4]; w[1]=Hcov[1] * f[3][0] + Hcov[2] * f[3][1] + Hcov[4] * f[3][2] + Hcov[7] * f[3][3] + Hcov[11]*f[3][4]; w[2]=Hcov[3] * f[3][0] + Hcov[4] * f[3][1] + Hcov[5] * f[3][2] + Hcov[8] * f[3][3] + Hcov[12]*f[3][4]; w[3]=Hcov[6] * f[3][0] + Hcov[7] * f[3][1] + Hcov[8] * f[3][2] + Hcov[9] * f[3][3] + Hcov[13]*f[3][4]; w[4]=Hcov[10]* f[3][0] + Hcov[11]* f[3][1] + Hcov[12]* f[3][2] + Hcov[13]* f[3][3] + Hcov[14]*f[3][4]; Hout.Hcov[6]=w[0]*f[0][0] + w[1]*f[0][1] + w[2]*f[0][2] + w[3]*f[0][3] + w[4]*f[0][4]; Hout.Hcov[7]=w[0]*f[1][0] + w[1]*f[1][1] + w[2]*f[1][2] + w[3]*f[1][3] + w[4]*f[1][4]; Hout.Hcov[8]=w[0]*f[2][0] + w[1]*f[2][1] + w[2]*f[2][2] + w[3]*f[2][3] + w[4]*f[2][4]; Hout.Hcov[9]=w[0]*f[3][0] + w[1]*f[3][1] + w[2]*f[3][2] + w[3]*f[3][3] + w[4]*f[3][4]; // as dPinv/dx = 0 if x != Pinv Hout.Hcov[10]=Hcov[10]*f[0][0] + Hcov[11]*f[0][1] + Hcov[12]*f[0][2] + Hcov[13]*f[0][3] + Hcov[14]*f[0][4]; Hout.Hcov[11]=Hcov[10]*f[1][0] + Hcov[11]*f[1][1] + Hcov[12]*f[1][2] + Hcov[13]*f[1][3] + Hcov[14]*f[1][4]; Hout.Hcov[12]=Hcov[10]*f[2][0] + Hcov[11]*f[2][1] + Hcov[12]*f[2][2] + Hcov[13]*f[2][3] + Hcov[14]*f[2][4]; Hout.Hcov[13]=Hcov[10]*f[3][0] + Hcov[11]*f[3][1] + Hcov[12]*f[3][2] + Hcov[13]*f[3][3] + Hcov[14]*f[3][4]; Hout.Hcov[14]=Hcov[14]; /* // The same with use of TMtx class (for test only) TMtx F(5,5), C(5,5), C1(5,5), Dum(5), Par(5); double x0; this->Get(x0,Dum,C); for(i=1; i<=5; i++){ for(j=1; j<=5; j++){ F(i,j)=f[i-1][j-1]; } } C1 = F*C*F.t(); Hout.Get(x0,Par,C); // for x0, Par // cout<<"x0 = "<<x0<<endl; // Par.Print("Par"); // C.Print("C mtx"); // F.Print("Jacobian F"); // C1.Print("C1 =F*C*F.t()"); Hout.Set(x0,Par,C1); // Hout.Print("Hout"); cout<<endl; */ } // endif (straight line or helix) if(Hout.Hcov[0] < 0 || Hout.Hcov[2] < 0 || Hout.Hcov[5] < 0 || Hout.Hcov[9] < 0 || Hout.Hcov[14]< 0){ cout<<"THlx::Extrapolate() ==> output cov. matrix is wrong "<<endl; this->Print("Input helix"); Hout.Print("Output helix"); return(false); } end: /* cout<<"Jacob. old"<<endl; cout.setf(ios::showpos); cout<<setprecision(3)<<setw(10); cout.setf(ios::scientific); for(int i = 0; i < 5; i++){ for(int j = 0; j < 5; j++){ cout<<f[i][j]<<"\t "; } cout<<endl; } cout.setf(ios::fixed,ios::scientific); cout.unsetf(ios::showpos); cout<<setprecision(7); */ Hout.path = this->Dist(Hout); //just an estimation of the path length. Hout.radLenFr = 0; return(true); }
[ "lsilvamiguel@gmail.com" ]
lsilvamiguel@gmail.com
815f672cce6466e2d90b28efbec1c3faa4a99696
184c987aa3615b687cedde502ec706ad4a838124
/code/numeric/karatsuba.cpp
6ee25465443e65832648c1c739ad9e285386fe3f
[]
no_license
chinchila/ICPC
71c85664df21acc1a9eb8f67632b556ae63a058d
69cec145898ef287c25f4f927106f7a021591e0b
refs/heads/master
2021-08-10T09:31:27.577825
2021-07-07T23:49:13
2021-07-07T23:49:13
232,422,330
6
2
null
2020-12-22T18:47:52
2020-01-07T21:39:00
C++
UTF-8
C++
false
false
1,471
cpp
//O(n^1.6) All sizes MUST BE power of two #define MAX 262144 #define MOD 1000000007 unsigned long long temp[128]; int ptr = 0, buffer[MAX * 6]; // the result is stored in *a void karatsuba(int n, int *a, int *b, int *res){ int i, j, h; if (n < 17){ for (i = 0; i < (n + n); i++) temp[i] = 0; for (i = 0; i < n; i++){ if (a[i]){ for (j = 0; j < n; j++){ temp[i + j] += ((long long)a[i] * b[j]); } } } for (i = 0; i < (n + n); i++) res[i] = temp[i] % MOD; return; } h = n >> 1; karatsuba(h, a, b, res); karatsuba(h, a + h, b + h, res + n); int *x = buffer + ptr, *y = buffer + ptr + h, *z = buffer + ptr + h + h; ptr += (h + h + n); for (i = 0; i < h; i++){ x[i] = a[i] + a[i + h], y[i] = b[i] + b[i + h]; if (x[i] >= MOD) x[i] -= MOD; if (y[i] >= MOD) y[i] -= MOD; } karatsuba(h, x, y, z); for (i = 0; i < n; i++) z[i] -= (res[i] + res[i + n]); for (i = 0; i < n; i++){ res[i + h] = (res[i + h] + z[i]) % MOD; if (res[i + h] < 0) res[i + h] += MOD; } ptr -= (h + h + n); } int mul(int n, int *a, int m, int *b){ int i, r, c = (n < m ? n : m), d = (n > m ? n : m), *res = buffer + ptr; r = 1 << (32 - __builtin_clz(d) - (__builtin_popcount(d) == 1)); for (i = d; i < r; i++) a[i] = b[i] = 0; for (i = c; i < d && n < m; i++) a[i] = 0; for (i = c; i < d && m < n; i++) b[i] = 0; ptr += (r << 1), karatsuba(r, a, b, res), ptr -= (r << 1); for (i = 0; i < (r << 1); i++) a[i] = res[i]; return (n + m - 1); }
[ "pachecosobral@gmail.com" ]
pachecosobral@gmail.com
ad467f590cb47e56addb76399cbf175f9c1e043f
8fd3b655b2dce3dec782ccc9d1779176758612c0
/widget.cpp
eb7b90dd2788650cd2ab1799388b1427659173fa
[]
no_license
isliulin/HHHTL1
0f0ce52016f2c0938cef7d99cb6ab8ec04992e53
944255c99ee8f9ec6a71574b208da1f6e7d62549
refs/heads/master
2022-03-29T09:35:42.153557
2018-08-05T13:19:20
2018-08-05T13:19:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
34,333
cpp
#include "widget.h" #include "ui_widget.h" #include "mybase.h" #include "header.h" #include "qtimer.h" #include "database.h" #include "navigator.h" #include "vehiclerunstatepage.h" #include "crrcmvb.h" #include "crrcfault.h" #include "simulation.h" #include "vehiclestationbar.h" #include "vehicletrainarea.h" #include "vehiclestatusarea.h" #include "vehicleinformationarea.h" #include "vehiclepasswordpage.h" #include "vehicleairconditionerpage.h" #include "vehicleauxiliarypage.h" #include "vehiclelinecircuitbreakerpage.h" #include "vehicledoorpage.h" #include "vehiclepispage.h" #include "vehiclebrakepage.h" #include "vehicletractpage.h" #include "vehiclefirewarningpage.h" #include "vehicleaircompressorpage.h" #include "vehicletopologypage.h" #include "vehiclesetpage.h" #include "vehiclesetstationpage.h" #include "vehiclesetairconditionpage.h" #include "vehiclemaintainpage.h" #include "vehiclemthistoryfaultpage.h" #include "vehiclemttimesetpage.h" #include "maintainceallportspage.h" #include "maintainceinitsetpage.h" #include "maintainceriompage.h" #include "maintaincewheeldiametersetpage.h" #include "maintaincesoftwareversionpage.h" #include "maintaincedatamanagepage.h" #include "maintainceresetexcisionpage.h" #include "maintaincecommunicationstatepage.h" #include "vehiclesetbrakeparampage.h" #include "vehiclesetintensitycontrolpage.h" #include "vehiclesetbraketestpage.h" #include "vehiclemaintaincetractsubsystempage.h" #include "maintaincebrakesubsystempage.h" #include "maintainceauxiliarysubsystempage.h" #include "maintainceaccumulatorsubsystempage.h" #include "maintaincerunninggearsubsystempage.h" #include "faulteventpage.h" #include "bypasspage.h" Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::Widget) { ui->setupUi(this); QDesktopWidget *desktop = QApplication::desktop(); if (desktop->width() == 800 && desktop->height() == 600) { this->showFullScreen(); } else { this->move((desktop->width() - this->width()) / 2, (desktop->height() - this->height()) / 2); } this->database = new Database(); MyBase::database = this->database; this->timer = new QTimer; connect(timer, SIGNAL(timeout()), this, SLOT(updatePage())); if(CrrcFault::initCrrcFault("fault_type_SY9.db","fault_DB_SY9.db")) { crrcFault = CrrcFault::getCrrcFault(); }else { logger()->error("故障文件初始化错误"); } crrcMvb = CrrcMvb::getCrrcMvb(); this->simulation=new Simulation(); this->simulation->hide(); this->header = new Header(this); this->header->setMyBase(uTop,QString("标题栏")); this->header->show(); this->navigator = new Navigator(this); this->navigator->setMyBase(uBottom,QString("导航栏")); this->navigator->show(); this->vehicleRunStatePage = new VehicleRunStatePage(this); this->vehicleRunStatePage->setMyBase(uTrain,QString("一般信息")); this->vehicleRunStatePage->show(); this->vehicleStationBar = new VehicleStationBar(this); this->vehicleStationBar->setMyBase(uStation,QString("站点信息")); this->vehicleStationBar->show(); this->vehicleTrainArea = new VehicleTrainArea(this); this->vehicleTrainArea->setMyBase(uMainRunstatus,QString("车体")); this->vehicleTrainArea->show(); this->vehicleStatusArea = new VehicleStatusArea(this); this->vehicleStatusArea->setMyBase(uStatus,QString("过程信息")); this->vehicleStatusArea->show(); this->vehicleInformationArea = new VehicleInformationArea(this); this->vehicleInformationArea->setMyBase(uInformation,QString("提示信息")); this->vehicleInformationArea->show(); this->vehiclePasswordPage = new VehiclePasswordPage(this); this->vehiclePasswordPage->setMyBase(uMiddle,QString("密码页面")); this->vehiclePasswordPage->hide(); this->vehicleAirConditionerPage=new VehicleAirConditionerPage(this); this->vehicleAirConditionerPage->setMyBase(uTrain,QString("空调界面")); this->vehicleAirConditionerPage->hide(); this->vehicleAuxiliaryPage=new VehicleAuxiliaryPage(this); this->vehicleAuxiliaryPage->setMyBase(uTrain,QString("辅助界面")); this->vehicleAuxiliaryPage->hide(); this->vehicleLineCircuitBreakerPage=new VehicleLineCircuitBreakerPage(this); this->vehicleLineCircuitBreakerPage->setMyBase(uTrain,QString("主回路界面")); this->vehicleLineCircuitBreakerPage->hide(); this->vehicleDoorPage=new VehicleDoorPage(this); this->vehicleDoorPage->setMyBase(uTrain,QString("车门界面")); this->vehicleDoorPage->hide(); this->vehiclePISPage=new VehiclePISPage(this); this->vehiclePISPage->setMyBase(uTrain,QString("PIS界面")); this->vehiclePISPage->hide(); this->vehicleBrakePage=new VehicleBrakePage(this); this->vehicleBrakePage->setMyBase(uTrain,QString("制动界面")); this->vehicleBrakePage->hide(); this->vehicleTractPage=new VehicleTractPage(this); this->vehicleTractPage->setMyBase(uTrain,QString("牵引界面")); this->vehicleTractPage->hide(); this->vehicleFireWarningPage=new VehicleFireWarningPage(this); this->vehicleFireWarningPage->setMyBase(uTrain,QString("火灾报警")); this->vehicleFireWarningPage->hide(); this->vehicleAirCompressorPage=new VehicleAirCompressorPage(this); this->vehicleAirCompressorPage->setMyBase(uTrain,QString("空压机界面")); this->vehicleAirCompressorPage->hide(); this->vehicleTopologyPage=new VehicleTopologyPage(this); this->vehicleTopologyPage->setMyBase(uTolopogy,QString("拓扑界面")); this->vehicleTopologyPage->hide(); this->vehicleSetPage=new VehicleSetPage(this); this->vehicleSetPage->setMyBase(uMiddle,QString("设置界面")); this->vehicleSetPage->hide(); this->vehicleSetStationPage=new VehicleSetStationPage(this); this->vehicleSetStationPage->setMyBase(uMiddle,QString("站点设置界面")); this->vehicleSetStationPage->hide(); this->vehicleSetAirConditionPage=new VehicleSetAirConditionPage(this); this->vehicleSetAirConditionPage->setMyBase(uMiddle,QString("空调设置界面")); this->vehicleSetAirConditionPage->hide(); this->vehicleSetBrakeParamPage=new VehicleSetBrakeParamPage(this); this->vehicleSetBrakeParamPage->setMyBase(uMiddle,QString("制动参数界面")); this->vehicleSetBrakeParamPage->hide(); this->vehicleSetIntensityControlPage=new VehicleSetIntensityControlPage(this); this->vehicleSetIntensityControlPage->setMyBase(uMiddle,QString("亮度调节")); this->vehicleSetIntensityControlPage->hide(); this->vehicleSetBrakeTestPage=new VehicleSetBrakeTestPage(this); this->vehicleSetBrakeTestPage->setMyBase(uMiddle,"制动自检"); this->vehicleSetBrakeTestPage->hide(); this->vehicleMaintainPage=new VehicleMaintainPage(this); this->vehicleMaintainPage->setMyBase(uMiddle,QString("维护界面")); this->vehicleMaintainPage->hide(); this->vehicleMTTimeSetPage=new VehicleMTTimeSetPage(this); this->vehicleMTTimeSetPage->setMyBase(uMiddle,QString("时间设定界面")); this->vehicleMTTimeSetPage->hide(); this->vehicleMTHistoryFaultPage=new VehicleMTHistoryFaultPage(this); this->vehicleMTHistoryFaultPage->setMyBase(uMiddle,QString("故障履历界面")); this->vehicleMTHistoryFaultPage->hide(); this->vehicleMaintainceAllPortsPage=new MaintainceAllPortsPage(this); this->vehicleMaintainceAllPortsPage->setMyBase(uHuge,QString("数据监控界面")); this->vehicleMaintainceAllPortsPage->hide(); this->vehicleMaintainceAllPortsPage->installMvb(this->crrcMvb); this->vehicleMaintainceInitSetPage=new MaintainceInitSetPage(this); this->vehicleMaintainceInitSetPage->setMyBase(uMiddle,QString("显示屏设置界面")); this->vehicleMaintainceInitSetPage->hide(); this->vehicleMaintainceRIOMPage=new MaintainceRIOMPage(this); this->vehicleMaintainceRIOMPage->setMyBase(uMiddle,QString("RIOM界面")); this->vehicleMaintainceRIOMPage->hide(); this->vehicleMaintainceWheelDiameterSetPage=new MaintainceWheelDiameterSetPage(this); this->vehicleMaintainceWheelDiameterSetPage->setMyBase(uMiddle,QString("轮径设置界面")); this->vehicleMaintainceWheelDiameterSetPage->hide(); this->vehicleMaintainceSoftwareVersionPage=new MaintainceSoftwareVersionPage(this); this->vehicleMaintainceSoftwareVersionPage->setMyBase(uMiddle,QString("版本信息界面")); this->vehicleMaintainceSoftwareVersionPage->hide(); this->vehicleMaintainceDataManagePage=new MaintainceDataManagePage(this); this->vehicleMaintainceDataManagePage->setMyBase(uMiddle,QString("数据管理界面")); this->vehicleMaintainceDataManagePage->hide(); this->vehicleMaintainceResetExcisionPage=new MaintainceResetExcisionPage(this); this->vehicleMaintainceResetExcisionPage->setMyBase(uMiddle,QString("复位切除")); this->vehicleMaintainceResetExcisionPage->hide(); this->vehicleMaintainceCommunicationStatePage=new MaintainceCommunicationStatePage(this); this->vehicleMaintainceCommunicationStatePage->setMyBase(uMiddle,QString("通信状态界面")); this->vehicleMaintainceCommunicationStatePage->hide(); this->vehicleMaintainceTractSubsystemPage=new VehicleMaintainceTractSubsystemPage(this); this->vehicleMaintainceTractSubsystemPage->setMyBase(uMiddle,QString("牵引子系统界面")); this->vehicleMaintainceTractSubsystemPage->hide(); this->vehicleMaintainceBrakeSubsystemPage=new MaintainceBrakeSubsystemPage(this); this->vehicleMaintainceBrakeSubsystemPage->setMyBase(uMiddle,QString("制动子系统界面")); this->vehicleMaintainceBrakeSubsystemPage->hide(); this->vehicleMaintainceAuxiliarySubsystemPage=new MaintainceAuxiliarySubsystemPage(this); this->vehicleMaintainceAuxiliarySubsystemPage->setMyBase(uMiddle,QString("辅助子系统界面")); this->vehicleMaintainceAuxiliarySubsystemPage->hide(); this->vehicleMaintainceAccumulatorSubsystemPage=new MaintainceAccumulatorSubsystemPage(this); this->vehicleMaintainceAccumulatorSubsystemPage->setMyBase(uMiddle,QString("蓄电池子系统界面")); this->vehicleMaintainceAccumulatorSubsystemPage->hide(); this->vehicleMaintainceRunningGearSubsystemPage=new MaintainceRunningGearSubsystemPage(this); this->vehicleMaintainceRunningGearSubsystemPage->setMyBase(uMiddle,QString("走形部子系统界面")); this->vehicleMaintainceRunningGearSubsystemPage->hide(); this->vehicleFaultEventPage=new FaultEventPage(this); this->vehicleFaultEventPage->setMyBase(uMiddle,QString("当前故障页面")); this->vehicleFaultEventPage->hide(); this->vehicleByPassPage=new ByPassPage(this); this->vehicleByPassPage->setMyBase(uMiddle,QString("旁路界面")); this->vehicleByPassPage->hide(); this->widgets.insert(uVehicleRunStatePage,this->vehicleRunStatePage); this->widgets.insert(uVehicleStationBar,this->vehicleStationBar); this->widgets.insert(uVehicleTrainArea,this->vehicleTrainArea); this->widgets.insert(uVehicleStatusArea,this->vehicleStatusArea); this->widgets.insert(uVehicleInformationArea,this->vehicleInformationArea); this->widgets.insert(uVehiclePasswordPage,this->vehiclePasswordPage); this->widgets.insert(uVehicleAirConditionerPage,this->vehicleAirConditionerPage); this->widgets.insert(uVehicleAuxiliaryPage,this->vehicleAuxiliaryPage); this->widgets.insert(uVehicleLineCircuitBreakerPage,this->vehicleLineCircuitBreakerPage); this->widgets.insert(uVehicleDoorPage,this->vehicleDoorPage); this->widgets.insert(uVehiclePISPage,this->vehiclePISPage); this->widgets.insert(uVehicleBrakePage,this->vehicleBrakePage); this->widgets.insert(uVehicleTractPage,this->vehicleTractPage); this->widgets.insert(uVehicleFireWarningPage,this->vehicleFireWarningPage); this->widgets.insert(uVehicleAirCompressorPage,this->vehicleAirCompressorPage); this->widgets.insert(uVehicleTopologyPage,this->vehicleTopologyPage); this->widgets.insert(uVehicleSetPage,this->vehicleSetPage); this->widgets.insert(uVehicleSetStationPage,this->vehicleSetStationPage); this->widgets.insert(uVehicleSetAirConditionPage,this->vehicleSetAirConditionPage); this->widgets.insert(uVehicleMaintainPage,this->vehicleMaintainPage); this->widgets.insert(uVehicleMTHistoryFaultPage,this->vehicleMTHistoryFaultPage); this->widgets.insert(uVehicleMTTimeSetPage,this->vehicleMTTimeSetPage); this->widgets.insert(uVehicleMaintainceAllPortsPage,this->vehicleMaintainceAllPortsPage); this->widgets.insert(uVehicleMaintainceInitSetPage,this->vehicleMaintainceInitSetPage); this->widgets.insert(uVehicleMaintainceRIOMPage,this->vehicleMaintainceRIOMPage); this->widgets.insert(uVehicleMaintainceWheelDiameterSetPage,this->vehicleMaintainceWheelDiameterSetPage); this->widgets.insert(uVehicleMaintainceSoftwareVersionPage,this->vehicleMaintainceSoftwareVersionPage); this->widgets.insert(uVehicleMaintainceDataManagePage,this->vehicleMaintainceDataManagePage); this->widgets.insert(uVehicleMaintainceResetExcisionPage,this->vehicleMaintainceResetExcisionPage); this->widgets.insert(uVehicleMaintainceCommunicationStatePage,this->vehicleMaintainceCommunicationStatePage); this->widgets.insert(uVehicleSetBrakeParamPage,this->vehicleSetBrakeParamPage); this->widgets.insert(uVehicleSetIntensityControlPage,this->vehicleSetIntensityControlPage); this->widgets.insert(uVehicleSetBrakeTestPage,this->vehicleSetBrakeTestPage); this->widgets.insert(uVehicleMaintainceTractSubsystemPage,this->vehicleMaintainceTractSubsystemPage); this->widgets.insert(uVehicleMaintainceBrakeSubsystemPage,this->vehicleMaintainceBrakeSubsystemPage); this->widgets.insert(uVehicleMaintainceAuxiliarySubsystemPage,this->vehicleMaintainceAuxiliarySubsystemPage); this->widgets.insert(uVehicleMaintainceAccumulatorSubsystemPage,this->vehicleMaintainceAccumulatorSubsystemPage); this->widgets.insert(uVehicleMaintainceRunningGearSubsystemPage,this->vehicleMaintainceRunningGearSubsystemPage); this->widgets.insert(uVehicleFaultEventPage,this->vehicleFaultEventPage); this->widgets.insert(uVehicleByPassPage,this->vehicleByPassPage); } Widget::~Widget() { delete ui; } void Widget::updatePage() { static QTime timeStart(QTime::currentTime()); static int counter = 1; this->header->updatePage(); this->widgets[MyBase::currentPage]->updatePage(); // update comm data,some base logic if(counter%2 == 0) { crrcMvb->synchronizeMvbData(); this->simulation->installMvb(crrcMvb); } // start fault scanning thread static int faultdelaycnt = 0; if ((faultdelaycnt++ > 45) ) { crrcFault->start(); faultdelaycnt = 60; } counter >= 100 ? (counter = 1) : (counter ++); if (timeStart.msecsTo(QTime::currentTime()) > 500) { _LOG << "update page time out fault" << timeStart.msecsTo(QTime::currentTime()) << ", please check it"; } timeStart = QTime::currentTime(); } void Widget::changePage(int page) { foreach (int key, this->widgets.keys()) { if (key == page) { MyBase::currentPage = page; this->widgets[page]->show(); this->header->setPageName(this->widgets[page]->name); if(this->widgets[page]->Position == uHuge) { this->header->hide(); this->navigator->hide(); this->vehicleStationBar->hide(); this->vehicleStatusArea->hide(); this->vehicleInformationArea->hide(); this->vehicleTrainArea->hide(); this->vehicleStatusArea->refreshAllButton(); }else if(this->widgets[key]->Position == uMiddle) { this->header->show(); this->navigator->hide(); this->vehicleStationBar->hide(); this->vehicleStatusArea->hide(); this->vehicleInformationArea->hide(); this->vehicleTrainArea->hide(); this->vehicleStatusArea->refreshAllButton(); }else if(this->widgets[key]->Position == uTrain) { this->header->show(); this->navigator->show(); this->vehicleStationBar->show(); this->vehicleStatusArea->show(); this->vehicleInformationArea->show(); //this->vehicleTrainArea->hide(); } else if(this->widgets[key]->Position==uTolopogy) { //拓扑界面单独设置了一种模式 this->header->show(); this->navigator->show(); this->vehicleStationBar->show(); this->vehicleTopologyPage->show(); this->vehicleInformationArea->show(); } else if(this->widgets[key]->Position==uMainRunstatus) { this->header->show(); this->navigator->show(); this->vehicleStationBar->show(); this->vehicleStatusArea->show(); this->vehicleStatusArea->refreshAllButton();//点击HOME按键的时候刷新按键的状态 this->vehicleInformationArea->show(); } _LOG << "change page to" << this->widgets[page]->name; } else { this->widgets[key]->hide(); } } } void Widget::showEvent(QShowEvent *) { this->header->setPageName(this->widgets[uVehicleRunStatePage]->name); if(MainGetDefaultPara::configureValid()) { #ifndef WINDOWS_MODE if(database->HMIPosition == 1)//config sourcePORT and IP { system("ifconfig eth0 192.168.2.3"); if(!crrcMvb->initializeMvb(0x31)) { logger()->error("MVB板卡初始化失败"); } //HMI-CCU system("ifconfig eth0 192.168.2.3"); if(!crrcMvb->initializeMvb(0x31)) { logger()->error("MVB板卡初始化失败"); } //HMI-CCU crrcMvb->addSourcePort(0x210,uFCode4,256); crrcMvb->addSourcePort(0x211,uFCode4,256); crrcMvb->addSourcePort(0x212,uFCode4,256); crrcMvb->addSourcePort(0x213,uFCode4,256); crrcMvb->addSinkPort(0x220,uFCode4,256); crrcMvb->addSinkPort(0x221,uFCode4,256); crrcMvb->addSinkPort(0x222,uFCode4,256); crrcMvb->addSinkPort(0x223,uFCode4,256); }else if(database->HMIPosition == 2) { system("ifconfig eth0 192.168.2.4"); if(!crrcMvb->initializeMvb(0x32)) { logger()->error("MVB板卡初始化失败"); } //HMI-CCU crrcMvb->addSinkPort(0x210,uFCode4,256); crrcMvb->addSinkPort(0x211,uFCode4,256); crrcMvb->addSinkPort(0x212,uFCode4,256); crrcMvb->addSinkPort(0x213,uFCode4,256); crrcMvb->addSourcePort(0x220,uFCode4,256); crrcMvb->addSourcePort(0x221,uFCode4,256); crrcMvb->addSourcePort(0x222,uFCode4,256); crrcMvb->addSourcePort(0x223,uFCode4,256); } //add ports { //CCU-HMI crrcMvb->addSinkPort(0x208,uFCode4,128); crrcMvb->addSinkPort(0x209,uFCode4,128); crrcMvb->addSinkPort(0x20A,uFCode4,128); //RIOM-CCU crrcMvb->addSinkPort(0x110,uFCode4,64); crrcMvb->addSinkPort(0x111,uFCode4,64); crrcMvb->addSinkPort(0x120,uFCode4,64); crrcMvb->addSinkPort(0x121,uFCode4,64); crrcMvb->addSinkPort(0x130,uFCode4,64); crrcMvb->addSinkPort(0x131,uFCode4,64); crrcMvb->addSinkPort(0x140,uFCode4,64); crrcMvb->addSinkPort(0x141,uFCode4,64); crrcMvb->addSinkPort(0x150,uFCode4,64); crrcMvb->addSinkPort(0x151,uFCode4,64); crrcMvb->addSinkPort(0x160,uFCode4,64); crrcMvb->addSinkPort(0x161,uFCode4,64); crrcMvb->addSinkPort(0x170,uFCode4,64); crrcMvb->addSinkPort(0x171,uFCode4,64); crrcMvb->addSinkPort(0x180,uFCode4,64); crrcMvb->addSinkPort(0x181,uFCode4,64); //ERM-CCU crrcMvb->addSinkPort(0x310,uFCode4,256); crrcMvb->addSinkPort(0x311,uFCode4,256); crrcMvb->addSinkPort(0x312,uFCode4,256); crrcMvb->addSinkPort(0x313,uFCode4,256); crrcMvb->addSinkPort(0x320,uFCode4,256); crrcMvb->addSinkPort(0x321,uFCode4,256); crrcMvb->addSinkPort(0x322,uFCode4,256); crrcMvb->addSinkPort(0x323,uFCode4,256); //DCU-CCU crrcMvb->addSinkPort(0x480,uFCode3,32); crrcMvb->addSinkPort(0x481,uFCode4,64); crrcMvb->addSinkPort(0x482,uFCode4,512); crrcMvb->addSinkPort(0x483,uFCode4,512); crrcMvb->addSinkPort(0x484,uFCode3,512); crrcMvb->addSinkPort(0x490,uFCode3,32); crrcMvb->addSinkPort(0x491,uFCode4,64); crrcMvb->addSinkPort(0x492,uFCode4,512); crrcMvb->addSinkPort(0x493,uFCode4,512); crrcMvb->addSinkPort(0x494,uFCode3,512); crrcMvb->addSinkPort(0x4C0,uFCode3,32); crrcMvb->addSinkPort(0x4C1,uFCode4,64); crrcMvb->addSinkPort(0x4C2,uFCode4,512); crrcMvb->addSinkPort(0x4C3,uFCode4,512); crrcMvb->addSinkPort(0x4C4,uFCode3,512); crrcMvb->addSinkPort(0x4D0,uFCode3,32); crrcMvb->addSinkPort(0x4D1,uFCode4,64); crrcMvb->addSinkPort(0x4D2,uFCode4,512); crrcMvb->addSinkPort(0x4D3,uFCode4,512); crrcMvb->addSinkPort(0x4D4,uFCode3,512); //SIV-CCU crrcMvb->addSinkPort(0x501,uFCode4,64); crrcMvb->addSinkPort(0x502,uFCode4,512); crrcMvb->addSinkPort(0x503,uFCode4,512); crrcMvb->addSinkPort(0x504,uFCode3,512); crrcMvb->addSinkPort(0x511,uFCode4,64); crrcMvb->addSinkPort(0x512,uFCode4,512); crrcMvb->addSinkPort(0x513,uFCode4,512); crrcMvb->addSinkPort(0x514,uFCode3,512); crrcMvb->addSinkPort(0x521,uFCode4,64); crrcMvb->addSinkPort(0x522,uFCode4,512); crrcMvb->addSinkPort(0x523,uFCode4,512); crrcMvb->addSinkPort(0x524,uFCode3,512); crrcMvb->addSinkPort(0x531,uFCode4,64); crrcMvb->addSinkPort(0x532,uFCode4,512); crrcMvb->addSinkPort(0x533,uFCode4,512); crrcMvb->addSinkPort(0x534,uFCode3,512); //BCU-CCU crrcMvb->addSinkPort(0x610,uFCode4,128); crrcMvb->addSinkPort(0x611,uFCode4,64); crrcMvb->addSinkPort(0x612,uFCode4,64); crrcMvb->addSinkPort(0x613,uFCode4,128); crrcMvb->addSinkPort(0x614,uFCode4,512); crrcMvb->addSinkPort(0x620,uFCode4,128); crrcMvb->addSinkPort(0x621,uFCode4,64); crrcMvb->addSinkPort(0x622,uFCode4,64); crrcMvb->addSinkPort(0x623,uFCode4,128); crrcMvb->addSinkPort(0x624,uFCode4,512); crrcMvb->addSinkPort(0x630,uFCode4,128); crrcMvb->addSinkPort(0x631,uFCode4,64); crrcMvb->addSinkPort(0x632,uFCode4,64); crrcMvb->addSinkPort(0x633,uFCode4,128); crrcMvb->addSinkPort(0x634,uFCode4,512); crrcMvb->addSinkPort(0x640,uFCode4,128); crrcMvb->addSinkPort(0x641,uFCode4,64); crrcMvb->addSinkPort(0x642,uFCode4,64); crrcMvb->addSinkPort(0x643,uFCode4,128); crrcMvb->addSinkPort(0x644,uFCode4,512); //EDCU-CCU crrcMvb->addSinkPort(0x710,uFCode4,512); crrcMvb->addSinkPort(0x711,uFCode4,1024); crrcMvb->addSinkPort(0x712,uFCode4,1024); crrcMvb->addSinkPort(0x720,uFCode4,512); crrcMvb->addSinkPort(0x721,uFCode4,1024); crrcMvb->addSinkPort(0x722,uFCode4,1024); crrcMvb->addSinkPort(0x730,uFCode4,512); crrcMvb->addSinkPort(0x731,uFCode4,1024); crrcMvb->addSinkPort(0x732,uFCode4,1024); crrcMvb->addSinkPort(0x740,uFCode4,512); crrcMvb->addSinkPort(0x741,uFCode4,1024); crrcMvb->addSinkPort(0x742,uFCode4,1024); crrcMvb->addSinkPort(0x750,uFCode4,512); crrcMvb->addSinkPort(0x751,uFCode4,1024); crrcMvb->addSinkPort(0x752,uFCode4,1024); crrcMvb->addSinkPort(0x760,uFCode4,512); crrcMvb->addSinkPort(0x761,uFCode4,1024); crrcMvb->addSinkPort(0x762,uFCode4,1024); crrcMvb->addSinkPort(0x770,uFCode4,512); crrcMvb->addSinkPort(0x771,uFCode4,1024); crrcMvb->addSinkPort(0x772,uFCode4,1024); crrcMvb->addSinkPort(0x780,uFCode4,512); crrcMvb->addSinkPort(0x781,uFCode4,1024); crrcMvb->addSinkPort(0x782,uFCode4,1024); crrcMvb->addSinkPort(0x790,uFCode4,512); crrcMvb->addSinkPort(0x791,uFCode4,1024); crrcMvb->addSinkPort(0x792,uFCode4,1024); crrcMvb->addSinkPort(0x7A0,uFCode4,512); crrcMvb->addSinkPort(0x7A1,uFCode4,1024); crrcMvb->addSinkPort(0x7A2,uFCode4,1024); crrcMvb->addSinkPort(0x7B0,uFCode4,512); crrcMvb->addSinkPort(0x7B1,uFCode4,1024); crrcMvb->addSinkPort(0x7B2,uFCode4,1024); crrcMvb->addSinkPort(0x7C0,uFCode4,512); crrcMvb->addSinkPort(0x7C1,uFCode4,1024); crrcMvb->addSinkPort(0x7C2,uFCode4,1024); //CCU-D crrcMvb->addSinkPort(0x818,uFCode3,512); crrcMvb->addSinkPort(0x828,uFCode3,512); //HVAC-CCU crrcMvb->addSinkPort(0x910,uFCode4,256); crrcMvb->addSinkPort(0x920,uFCode4,256); crrcMvb->addSinkPort(0x930,uFCode4,256); crrcMvb->addSinkPort(0x940,uFCode4,256); crrcMvb->addSinkPort(0x950,uFCode4,256); crrcMvb->addSinkPort(0x960,uFCode4,256); //ATC-CCU crrcMvb->addSinkPort(0xA10,uFCode3,64); crrcMvb->addSinkPort(0xA11,uFCode4,128); crrcMvb->addSinkPort(0xA20,uFCode3,64); crrcMvb->addSinkPort(0xA21,uFCode4,128); //PIS-CCU crrcMvb->addSinkPort(0xB10,uFCode4,256); crrcMvb->addSinkPort(0xB20,uFCode4,256); //TDS-CCU crrcMvb->addSinkPort(0xc10,uFCode4,1024); crrcMvb->addSinkPort(0xc11,uFCode4,1024); crrcMvb->addSinkPort(0xc12,uFCode4,1024); crrcMvb->addSinkPort(0xc13,uFCode4,1024); crrcMvb->addSinkPort(0xc20,uFCode4,1024); crrcMvb->addSinkPort(0xc21,uFCode4,1024); crrcMvb->addSinkPort(0xc22,uFCode4,1024); crrcMvb->addSinkPort(0xc23,uFCode4,1024); //LCU-CCU crrcMvb->addSinkPort(0xD10,uFCode4,512); crrcMvb->addSinkPort(0xD11,uFCode4,512); crrcMvb->addSinkPort(0xD12,uFCode4,512); crrcMvb->addSinkPort(0xD13,uFCode4,512); crrcMvb->addSinkPort(0xD20,uFCode4,512); crrcMvb->addSinkPort(0xD21,uFCode4,512); crrcMvb->addSinkPort(0xD22,uFCode4,512); crrcMvb->addSinkPort(0xD23,uFCode4,512); crrcMvb->addSinkPort(0xD30,uFCode4,512); crrcMvb->addSinkPort(0xD31,uFCode4,512); crrcMvb->addSinkPort(0xD32,uFCode4,512); crrcMvb->addSinkPort(0xD33,uFCode4,512); crrcMvb->addSinkPort(0xD40,uFCode4,512); crrcMvb->addSinkPort(0xD41,uFCode4,512); crrcMvb->addSinkPort(0xD42,uFCode4,512); crrcMvb->addSinkPort(0xD43,uFCode4,512); crrcMvb->addSinkPort(0xD50,uFCode4,512); crrcMvb->addSinkPort(0xD51,uFCode4,512); crrcMvb->addSinkPort(0xD52,uFCode4,512); crrcMvb->addSinkPort(0xD53,uFCode4,512); crrcMvb->addSinkPort(0xD60,uFCode4,512); crrcMvb->addSinkPort(0xD61,uFCode4,512); crrcMvb->addSinkPort(0xD62,uFCode4,512); crrcMvb->addSinkPort(0xD63,uFCode4,512); crrcMvb->addSinkPort(0xD70,uFCode4,512); crrcMvb->addSinkPort(0xD71,uFCode4,512); crrcMvb->addSinkPort(0xD72,uFCode4,512); crrcMvb->addSinkPort(0xD73,uFCode4,512); crrcMvb->addSinkPort(0xD80,uFCode4,512); crrcMvb->addSinkPort(0xD81,uFCode4,512); crrcMvb->addSinkPort(0xD82,uFCode4,512); crrcMvb->addSinkPort(0xD83,uFCode4,512); //BMS-CCU crrcMvb->addSinkPort(0xE10,uFCode4,1024); crrcMvb->addSinkPort(0xE20,uFCode4,1024); //FAS-CCU crrcMvb->addSinkPort(0xE50,uFCode4,256); crrcMvb->addSinkPort(0xE60,uFCode4,256); //PCU-CCU crrcMvb->addSinkPort(0xF10,uFCode3,256); crrcMvb->addSinkPort(0xF20,uFCode3,256); //CCU-ALL crrcMvb->addSinkPort(0x00F,uFCode3,64); //CCU-RIOM crrcMvb->addSinkPort(0x118,uFCode3,64); crrcMvb->addSinkPort(0x128,uFCode3,64); crrcMvb->addSinkPort(0x138,uFCode3,64); crrcMvb->addSinkPort(0x148,uFCode3,64); crrcMvb->addSinkPort(0x158,uFCode3,64); crrcMvb->addSinkPort(0x168,uFCode3,64); crrcMvb->addSinkPort(0x178,uFCode3,64); crrcMvb->addSinkPort(0x188,uFCode3,64); //CCU-ERM crrcMvb->addSinkPort(0x308,uFCode4,128); crrcMvb->addSinkPort(0x309,uFCode4,128); //CCU-TCU crrcMvb->addSinkPort(0x488,uFCode3,32); crrcMvb->addSinkPort(0x489,uFCode4,64); crrcMvb->addSinkPort(0x48A,uFCode4,512); crrcMvb->addSinkPort(0x498,uFCode3,32); crrcMvb->addSinkPort(0x499,uFCode4,64); crrcMvb->addSinkPort(0x49A,uFCode4,512); crrcMvb->addSinkPort(0x4C8,uFCode3,32); crrcMvb->addSinkPort(0x4C9,uFCode4,64); crrcMvb->addSinkPort(0x4CA,uFCode4,512); crrcMvb->addSinkPort(0x4D8,uFCode3,32); crrcMvb->addSinkPort(0x4D9,uFCode4,64); crrcMvb->addSinkPort(0x4DA,uFCode4,512); //CCU-ACU crrcMvb->addSinkPort(0x508,uFCode2,32); crrcMvb->addSinkPort(0x509,uFCode3,64); crrcMvb->addSinkPort(0x50A,uFCode3,512); crrcMvb->addSinkPort(0x518,uFCode2,32); crrcMvb->addSinkPort(0x519,uFCode3,64); crrcMvb->addSinkPort(0x51A,uFCode3,512); crrcMvb->addSinkPort(0x528,uFCode2,32); crrcMvb->addSinkPort(0x529,uFCode3,64); crrcMvb->addSinkPort(0x52A,uFCode3,512); crrcMvb->addSinkPort(0x538,uFCode2,32); crrcMvb->addSinkPort(0x539,uFCode3,64); crrcMvb->addSinkPort(0x53A,uFCode3,512); //CCU-BCU crrcMvb->addSinkPort(0x608,uFCode4,32); //CCU-EDCU crrcMvb->addSinkPort(0x708,uFCode3,256); //CCU-TCU-public crrcMvb->addSinkPort(0x800,uFCode2,512); //CCU-CCU-D crrcMvb->addSinkPort(0x810,uFCode2,512); //CCU-HVAC crrcMvb->addSinkPort(0x918,uFCode3,128); crrcMvb->addSinkPort(0x928,uFCode3,128); crrcMvb->addSinkPort(0x938,uFCode3,128); crrcMvb->addSinkPort(0x948,uFCode3,128); crrcMvb->addSinkPort(0x958,uFCode3,128); crrcMvb->addSinkPort(0x968,uFCode3,128); //CCU-ATC crrcMvb->addSinkPort(0xA08,uFCode4,128); crrcMvb->addSinkPort(0xA09,uFCode4,128); //CCU-PIS crrcMvb->addSinkPort(0xB08,uFCode4,256); crrcMvb->addSinkPort(0xB09,uFCode3,512); //CCU-TDS crrcMvb->addSinkPort(0xC08,uFCode4,1024); crrcMvb->addSinkPort(0xC09,uFCode4,1024); //CCU-LCU crrcMvb->addSinkPort(0xD08,uFCode3,256); //CCU-LCU1 crrcMvb->addSinkPort(0xD18,uFCode4,32); crrcMvb->addSinkPort(0xD19,uFCode4,32); //CCU-LCU2 crrcMvb->addSinkPort(0xD28,uFCode4,32); crrcMvb->addSinkPort(0xD29,uFCode4,32); //CCU-LCU3 crrcMvb->addSinkPort(0xD38,uFCode4,32); crrcMvb->addSinkPort(0xD39,uFCode4,32); //CCU-LCU4 crrcMvb->addSinkPort(0xD48,uFCode4,32); crrcMvb->addSinkPort(0xD49,uFCode4,32); //CCU-LCU5 crrcMvb->addSinkPort(0xD58,uFCode4,32); crrcMvb->addSinkPort(0xD59,uFCode4,32); //CCU-LCU6 crrcMvb->addSinkPort(0xD68,uFCode4,32); crrcMvb->addSinkPort(0xD69,uFCode4,32); //CCU-LCU7 crrcMvb->addSinkPort(0xD78,uFCode4,32); //CCU-LCU8 crrcMvb->addSinkPort(0xD88,uFCode4,32); //CCU-FAS crrcMvb->addSinkPort(0xE58,uFCode4,128); crrcMvb->addSinkPort(0xE68,uFCode4,128); //CCU-PCU crrcMvb->addSinkPort(0xF08,uFCode3,256); } #endif if(crrcMvb->setMvbOperation()) { logger()->error("MVB板卡设置操作模式失败"); } timer->start(333); }else { logger()->error("configure.ini文件错误"); _LOG << "fail to read configure file."; } } void Widget::keyPressEvent(QKeyEvent *event) { if (event->key() == Qt::Key_Escape) { this->close(); } else if (event->key() == Qt::Key_S) { QDesktopWidget *desktop = QApplication::desktop(); // show a window uesd to manipulate the mvb ports and change page simulation->raise(); simulation->move((desktop->width() - simulation->width()) / 2, (desktop->height() - simulation->height()) / 2); simulation->show(); } }
[ "dxm666@mail.dlut.edu.cn" ]
dxm666@mail.dlut.edu.cn
cda5fff70a4fdef2091348212a1f76c5c7c7ba76
65a511c8bdf76d5ff66ea79c0e4013281b060ff4
/svm_option.cpp
cac5fe5c7a284be7a2c0b6e5219742f4a0765676
[]
no_license
B1ztn/svm_simplified
5ef61e08ae13ed20378fb52194979030d1fccca9
42cf3af648e70e04207607966a9fd3089769c426
refs/heads/master
2021-05-09T09:01:59.715967
2018-01-30T16:56:29
2018-01-30T16:56:29
119,416,409
0
0
null
null
null
null
UTF-8
C++
false
false
2,877
cpp
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: svm_option.cpp * Author: b1 * * Created on January 27, 2018, 2:26 PM */ /* * control the input and output data!!!!!! */ #include <cstdlib> #include "svm_option.h" #include "svm_common.h" using namespace std; /* * */ SVMOption :: SVMOption(){ _C = SVM_OPTION_C; _eps = SVM_OPTION_EPSILON; _sig = SVM_OPTION_SIGMA; _is_linear_kernel = false; _fname_train[0] = '\0'; _fname_valid[0] = '\0'; _fname_model[0] = '\0'; _flags = 0; } SVMOption::~SVMOption(){} void SVMOption::print(){ cerr<< "# [c = " << _C << "]\n" "# [epsilon = " << _eps << "]\n" "# [sigma = " << _sig << "]\n" "# [is_linear_kernel = " << _is_linear_kernel << "]\n" "# [fname_train = " << _fname_train << "]\n" "# [fname_model = " << _fname_model << "]\n" "# [fname_valid = " << _fname_valid << "]\n" "#--------------END----------------------------------\n" <<endl; } int SVMOption::parse_command_line(int argc, char * argv[]){ int option; const char *opt_string =""; struct option long_opts[]={ {"train", 1,NULL,0}, {"model", 1,NULL,1}, {"validate",1, NULL, 2}, {"linear_kernel", 0, NULL, 3}, {"c", 0,NULL,4}, {"epsilon", 1,NULL,5}, {"sigma", 1,NULL,6}, {"help", 0,NULL,7}, {0,0,0,0} }; while((option = getopt_long_only(argc, argv, opt_string,long_opts,NULL))!=-1){ switch(option){ case 0: _flags |= FLAG_TRAIN; memcpy(_fname_train, optarg, strlen(optarg)); _fname_train[strlen(optarg)] = '\0'; break; case 1: _flags |= FLAG_MODEL; memcpy(_fname_model, optarg, strlen(optarg)); _fname_model[strlen(optarg)] = '\0'; break; case 2: _flags |= FLAG_VALID; memcpy(_fname_valid, optarg, strlen(optarg)); _fname_valid[strlen(optarg)] = '\0'; break; case 3: _flags |= FLAG_LINEAR_KERNEL; _is_linear_kernel = true; break; case 4: _flags |= FLAG_C; _C = atof(optarg); break; case 5: _flags |= FLAG_EPSILON; _eps = atof(optarg); break; case 6: _flags |= FLAG_SIGMA; _sig = atof(optarg); break; case 7: _flags |= FLAG_HELP; break; } } }
[ "zhangtn0227@hotmail.com" ]
zhangtn0227@hotmail.com
7d92d169b376d7b814aa13316f188d610b28b4bc
72d03ec10b4955bcc7daac5f820f63f3e5ed7e75
/cvs/objects/reporting/source/sgm_gen_table.cpp
27aa7ee9418a4b7ad5d0fcf0ae256cedf0fedfcb
[ "ECL-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
bgmishra/gcam-core
54daddc3d037571bf745c4cf0d54c0d7a77f493f
bbfb78aeb0cde4d75f307fc3967526d70157c2f8
refs/heads/master
2022-04-17T11:18:25.911460
2020-03-17T18:03:21
2020-03-17T18:03:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
25,302
cpp
/* * LEGAL NOTICE * This computer software was prepared by Battelle Memorial Institute, * hereinafter the Contractor, under Contract No. DE-AC05-76RL0 1830 * with the Department of Energy (DOE). NEITHER THE GOVERNMENT NOR THE * CONTRACTOR MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR ASSUMES ANY * LIABILITY FOR THE USE OF THIS SOFTWARE. This notice including this * sentence must appear on any copies of this computer software. * * EXPORT CONTROL * User agrees that the Software will not be shipped, transferred or * exported into any country or used in any manner prohibited by the * United States Export Administration Act or any other applicable * export laws, restrictions or regulations (collectively the "Export Laws"). * Export of the Software may require some form of license or other * authority from the U.S. Government, and failure to obtain such * export control license may result in criminal liability under * U.S. laws. In addition, if the Software is identified as export controlled * items under the Export Laws, User represents and warrants that User * is not a citizen, or otherwise located within, an embargoed nation * (including without limitation Iran, Syria, Sudan, Cuba, and North Korea) * and that User is not otherwise prohibited * under the Export Laws from receiving the Software. * * Copyright 2011 Battelle Memorial Institute. All Rights Reserved. * Distributed as open-source under the terms of the Educational Community * License version 2.0 (ECL 2.0). http://www.opensource.org/licenses/ecl2.php * * For further details, see: http://www.globalchange.umd.edu/models/gcam/ * */ /*! * \file sgm_gen_table.cpp * \ingroup Objects * \brief The SGMGenTable class source file. * * \author Sonny Kim */ #include "util/base/include/definitions.h" #include <iostream> #include <string> #include <map> #include "reporting/include/sgm_gen_table.h" #include "containers/include/scenario.h" #include "marketplace/include/marketplace.h" #include "containers/include/region.h" #include "containers/include/region_cge.h" #include "demographics/include/demographic.h" #include "sectors/include/sector.h" #include "sectors/include/production_sector.h" #include "sectors/include/subsector.h" #include "emissions/include/aghg.h" #include "containers/include/national_account.h" #include "technologies/include/expenditure.h" #include "technologies/include/base_technology.h" #include "consumers/include/consumer.h" #include "consumers/include/household_consumer.h" #include "consumers/include/govt_consumer.h" #include "consumers/include/trade_consumer.h" #include "consumers/include/invest_consumer.h" #include "technologies/include/production_technology.h" #include "functions/include/iinput.h" #include "sectors/include/factor_supply.h" #include "util/base/include/model_time.h" #include "functions/include/function_utils.h" #include "technologies/include/ioutput.h" #include "containers/include/iinfo.h" using namespace std; extern Scenario* scenario; //! Default Constructor SGMGenTable::SGMGenTable( const string& aName, const string& aHeader, const Modeltime* aModeltime ): mName( aName ), mHeader( aHeader ), mModeltime( aModeltime ), mFile( 0 ) { } /*! \brief Set the file the table will print to. * \todo Remove this. * \param aOutputFile File to which to output. */ void SGMGenTable::setOutputFile( ostream& aOutputFile ){ mFile = &aOutputFile; } //! Add to the value for the DCT specified by the account type key. void SGMGenTable::addToType( const int aTypeRow, const string aTypeCol, const double value ){ // add to column and row totals here // Do not add to totals anywhere else mTable[ aTypeRow ][ aTypeCol ] += value; // add to total for this type of table only mTable[ aTypeRow ][ "zTotal" ] += value; } //! set the value for the DCT specified by the account type key. void SGMGenTable::setType( const int aTypeRow, const string aTypeCol, const double value ){ mTable[ aTypeRow ][ aTypeCol ] = value; } //! Get the value for the DCT specified by the account type key. double SGMGenTable::getValue( const int aTypeRow, const string aTypeCol ) const { return util::searchForValue( util::searchForValue( mTable, aTypeRow ), aTypeCol ); } /*! \brief For outputting SGM data to a flat csv File * */ void SGMGenTable::finish() const { /*! \pre The output file has been set. */ assert( mFile ); if ( !mTable.empty() ){ // don't print if empty *mFile << mHeader << endl; // Note: This is structurally different from SAM. This goes through the rows and prints // out each of the category values. // write column labels *mFile << "Year" << ','; for( map< string, double>::const_iterator strIter = (*mTable.begin()).second.begin(); strIter != (*mTable.begin()).second.end(); ++strIter ) { *mFile << (*strIter).first << ','; } *mFile << endl; for ( map<int, map<string, double> >::const_iterator mapIter = mTable.begin(); mapIter != mTable.end(); ++mapIter ) { *mFile << (*mapIter).first; for( map< string, double >::const_iterator strIter = ((*mapIter).second).begin(); strIter != ((*mapIter).second).end(); strIter++ ) { *mFile << ',' << (*strIter).second; } *mFile << endl; } *mFile << endl; } } void SGMGenTable::startVisitRegionCGE( const RegionCGE* regionCGE, const int aPeriod ) { // Store the current region name. mCurrentRegionName = regionCGE->getName(); // if table output is by sector, then add sector names to map if( mName == "PECbySector" ) { for( std::vector<Sector*>::const_iterator secNameIter = regionCGE->mSupplySector.begin(); secNameIter != regionCGE->mSupplySector.end(); ++secNameIter ) { for ( int per = 0; per < mModeltime->getmaxper(); per++ ) { int year = mModeltime->getper_to_yr( per ); addToType( year, (*secNameIter)->getName(), 0 ); } } } } void SGMGenTable::endVisitRegionCGE( const RegionCGE* aRegionCGE, const int aPeriod ){ // Clear the stored region name. mCurrentRegionName.clear(); } void SGMGenTable::startVisitSector( const Sector* aSector, const int aPeriod ){ // Store the current sector name. mCurrentSectorName = aSector->getName(); } void SGMGenTable::endVisitSector( const Sector* aSector, const int aPeriod ){ // Clear the stored sector name. mCurrentSectorName.clear(); } // Write sector market prices to the SGM gen file void SGMGenTable::startVisitProductionSector( const ProductionSector* aProductionSector, const int aPeriod ) { if( mName == "PRICE" ) { addToType( mModeltime->getper_to_yr( aPeriod ), aProductionSector->getName(), scenario->getMarketplace()->getPrice( aProductionSector->getName(), aProductionSector->mRegionName, aPeriod ) ); } } // Write factor supply market prices to the SGM gen file void SGMGenTable::startVisitFactorSupply( const FactorSupply* aFactorSupply, const int aPeriod ) { if( mName == "PRICE" ) { addToType( mModeltime->getper_to_yr( aPeriod ), aFactorSupply->getName(), scenario->getMarketplace()->getPrice( aFactorSupply->getName(), aFactorSupply->marketName, aPeriod ) ); } } // Write National Account information to the SGM gen file void SGMGenTable::startVisitNationalAccount( const NationalAccount* aNationalAccount, const int aPeriod ) { if( mName == "GNPREAL" ) { addToType( mModeltime->getper_to_yr( aPeriod ), "Consumption", aNationalAccount->getAccountValue( NationalAccount::CONSUMPTION_REAL ) ); addToType( mModeltime->getper_to_yr( aPeriod ), "Investment", aNationalAccount->getAccountValue( NationalAccount::INVESTMENT_REAL ) ); addToType( mModeltime->getper_to_yr( aPeriod ), "Government", aNationalAccount->getAccountValue( NationalAccount::GOVERNMENT_REAL ) ); addToType( mModeltime->getper_to_yr( aPeriod ), "Trade Balance", aNationalAccount->getAccountValue( NationalAccount::NET_EXPORT_REAL ) ); addToType( mModeltime->getper_to_yr( aPeriod ), "GNP", aNationalAccount->getAccountValue( NationalAccount::GNP_REAL ) ); } else if( mName == "GNPNOM" ) { addToType( mModeltime->getper_to_yr( aPeriod ), "Consumption", aNationalAccount->getAccountValue( NationalAccount::CONSUMPTION_NOMINAL ) ); addToType( mModeltime->getper_to_yr( aPeriod ), "Investment", aNationalAccount->getAccountValue( NationalAccount::INVESTMENT_NOMINAL ) ); addToType( mModeltime->getper_to_yr( aPeriod ), "Government", aNationalAccount->getAccountValue( NationalAccount::GOVERNMENT_NOMINAL ) ); addToType( mModeltime->getper_to_yr( aPeriod ), "Trade Balance", aNationalAccount->getAccountValue( NationalAccount::NET_EXPORT_NOMINAL ) ); addToType( mModeltime->getper_to_yr( aPeriod ), "GNP", aNationalAccount->getAccountValue( NationalAccount::GNP_NOMINAL ) ); } } // Write demographics results to the SGM gen file void SGMGenTable::startVisitDemographic( const Demographic* aDemographic, const int aPeriod ) { if( mName == "DEM" ) { addToType( mModeltime->getper_to_yr( aPeriod ), "Tot Pop", aDemographic->getTotal( aPeriod ) ); addToType( mModeltime->getper_to_yr( aPeriod ), "Working Age Male", aDemographic->getWorkingAgePopulationMales( aPeriod ) ); addToType( mModeltime->getper_to_yr( aPeriod ), "Working Age Female", aDemographic->getWorkingAgePopulationFemales( aPeriod ) ); addToType( mModeltime->getper_to_yr( aPeriod ), "Working Age Tot", aDemographic->getWorkingAgePopulation( aPeriod ) ); } } // Write to SGM general table. // This routine assumes that only and all operating technology vintages are passed in as // an argument. void SGMGenTable::startVisitConsumer( const Consumer* aConsumer, const int aPeriod ) { // Only update the current consumer. if( aConsumer->getYear() != mModeltime->getper_to_yr( aPeriod ) ){ return; } // add output of each technology for each period if( ( mName == "CO2" ) || ( mName == "CO2bySec" ) || ( mName == "CO2byTech" ) ){ unsigned int CO2index = util::searchForValue( aConsumer->mGhgNameMap, string( "CO2" ) ); double CO2Emiss = aConsumer->mGhgs[ CO2index ]->getEmission( aPeriod ); if( mName == "CO2" ) { addToType( mModeltime->getper_to_yr( aPeriod ), "CO2", CO2Emiss ); } else if( mName == "CO2bySec" ) { addToType( mModeltime->getper_to_yr( aPeriod ), aConsumer->getXMLName(), CO2Emiss ); } else if( mName == "CO2byTech" ) { addToType( mModeltime->getper_to_yr( aPeriod ), aConsumer->getName(), CO2Emiss ); } } } void SGMGenTable::startVisitHouseholdConsumer( const HouseholdConsumer* householdConsumer, const int aPeriod ) { if( mName == "CAP" ) { // add only current year consumer if( householdConsumer->year == mModeltime->getper_to_yr( aPeriod ) ) { addToType( mModeltime->getper_to_yr( aPeriod ), "Savings", householdConsumer->expenditures[ aPeriod ].getValue( Expenditure::SAVINGS ) ); } } else if( mName == "DEM" ) { if( householdConsumer->year == mModeltime->getper_to_yr( aPeriod ) ) { addToType( mModeltime->getper_to_yr( aPeriod ), "Labor Supply", householdConsumer->getLaborSupply() ); } } } void SGMGenTable::startVisitGovtConsumer( const GovtConsumer* govtConsumer, const int aPeriod ) { if( mName == "CAP" ) { // add only current year consumer if( govtConsumer->year == mModeltime->getper_to_yr( aPeriod ) ) { // note the negative sign to get addToType( mModeltime->getper_to_yr( aPeriod ), "Govt Deficit", govtConsumer->expenditures[ aPeriod ].getValue( Expenditure::SAVINGS ) ); } } } void SGMGenTable::startVisitTradeConsumer( const TradeConsumer* tradeConsumer, const int aPeriod ) { // net energy trade if( mName == "ETRADE" ) { // add only current year consumer if( tradeConsumer->getYear() == mModeltime->getper_to_yr( aPeriod ) ) { // get energy inputs only for( unsigned int i=0; i<tradeConsumer->mLeafInputs.size(); i++ ){ if( tradeConsumer->mLeafInputs[ i ]->hasTypeFlag( IInput::ENERGY ) ){ addToType( mModeltime->getper_to_yr( aPeriod ), tradeConsumer->mLeafInputs[ i ]->getName(), tradeConsumer->mLeafInputs[ i ]->getPhysicalDemand( aPeriod ) ); } } } } else if( mName == "EmissBySource" ){ // add or remove emissions only for the current consumer. if( tradeConsumer->getYear() != mModeltime->getper_to_yr( aPeriod ) ){ return; } // Loop through the inputs and find primary goods. for( unsigned int i = 0; i < tradeConsumer->mLeafInputs.size(); ++i ){ // Skip non-primary inputs if( !tradeConsumer->mLeafInputs[ i ]->hasTypeFlag( IInput::PRIMARY ) ){ continue; } // Calculate the amount of emissions that are being traded. const double tradedEmissions = tradeConsumer->mLeafInputs[ i ]->getPhysicalDemand( aPeriod ) * tradeConsumer->mLeafInputs[ i ]->getCO2EmissionsCoefficient( "CO2", aPeriod ); // Add or remove the emissions to the column for the sector and year. Check that the sign is right. addToType( mModeltime->getper_to_yr( aPeriod ), tradeConsumer->mLeafInputs[ i ]->getName(), -1 * tradedEmissions ); } } } void SGMGenTable::startVisitInvestConsumer( const InvestConsumer* investConsumer, const int aPeriod ) { // add only current year consumer if( investConsumer->year == mModeltime->getper_to_yr( aPeriod ) ) { } } // Write to SGM general table. // This routine assumes that only and all operating technology vintages are passed in as // an argument. void SGMGenTable::startVisitProductionTechnology( const ProductionTechnology* prodTech, const int aPeriod ) { if( aPeriod == -1 || ( prodTech->isAvailable( aPeriod ) && !prodTech->isRetired( aPeriod ) ) ) { // add output of each technology for each period if( ( mName == "CO2" ) || ( mName == "CO2bySec" ) || ( mName == "CO2byTech" ) ){ unsigned int CO2index = util::searchForValue( prodTech->mGhgNameMap, string( "CO2" ) ); double CO2Emiss = prodTech->mGhgs[CO2index]->getEmission( aPeriod ); if( mName == "CO2" ) { addToType( mModeltime->getper_to_yr( aPeriod ), "CO2", CO2Emiss ); } else if( mName == "CO2bySec" ) { addToType( mModeltime->getper_to_yr( aPeriod ), mCurrentSectorName, CO2Emiss ); } else if( mName == "CO2byTech" ) { addToType( mModeltime->getper_to_yr( aPeriod ), prodTech->getName(), CO2Emiss ); } } else if( mName == "PEC" ) { for( unsigned int i=0; i<prodTech->mLeafInputs.size(); i++ ){ // get primary energy input only if( prodTech->mLeafInputs[ i ]->hasTypeFlag( IInput::PRIMARY ) ){ // isn't this the same as getting physical demand? addToType( mModeltime->getper_to_yr( aPeriod ), prodTech->mLeafInputs[ i ]->getName(), prodTech->mLeafInputs[ i ]->getPhysicalDemand( aPeriod ) ); } } // special code to add renewable, nuclear and hydro electricity to primary energy consumption if( mCurrentSectorName == "ElectricityGeneration" ) { // TODO: use average fossil efficiency instead of hard-coded 0.3 double fossilEfficiency = 0.3; if( prodTech->categoryName == "Renewable"){ addToType( mModeltime->getper_to_yr( aPeriod ), prodTech->name, prodTech->getOutput( aPeriod ) / fossilEfficiency ); } } } // primary energy production else if( mName == "PEP" ) { // get primary energy input only if( isPrimaryEnergyGood( mCurrentRegionName, mCurrentSectorName ) ){ addToType( mModeltime->getper_to_yr( aPeriod ), mCurrentSectorName, prodTech->getOutput( aPeriod ) ); } // special code to add renewable, nuclear and hydro electricity to primary energy production if( mCurrentSectorName == "ElectricityGeneration" ) { // TODO: use average fossil efficiency instead of hard-coded 0.3 double fossilEfficiency = 0.3; if( prodTech->categoryName == "Renewable"){ addToType( mModeltime->getper_to_yr( aPeriod ), prodTech->name, prodTech->getOutput( aPeriod ) / fossilEfficiency ); } } } // secondary energy production else if( mName == "SEP" ) { // get secondary energy goods only if( isSecondaryEnergyGood( mCurrentRegionName, mCurrentSectorName ) ){ addToType( mModeltime->getper_to_yr( aPeriod ), mCurrentSectorName, prodTech->getOutput( aPeriod ) ); } } // non-energy sector output else if( mName == "NEP" ) { // get non-energy goods only if( !isEnergyGood( mCurrentRegionName, mCurrentSectorName ) ){ addToType( mModeltime->getper_to_yr( aPeriod ), mCurrentSectorName, prodTech->getOutput( aPeriod ) ); } } // electricity generation by technology else if( mName == "ELEC" ) { if( mCurrentSectorName == "ElectricityGeneration" ) { addToType( mModeltime->getper_to_yr( aPeriod ), prodTech->getName(), prodTech->getOutput(aPeriod) ); } } // fuel consumption for electricity generation else if( mName == "ElecFuel" ) { if( mCurrentSectorName == "ElectricityGeneration" ) { for( unsigned int i=0; i<prodTech->mLeafInputs.size(); i++ ){ // get energy input only if( prodTech->mLeafInputs[ i ]->hasTypeFlag( IInput::ENERGY ) ){ addToType( mModeltime->getper_to_yr( aPeriod ), prodTech->mLeafInputs[ i ]->getName(), prodTech->mLeafInputs[ i ]->getPhysicalDemand( aPeriod ) ); } } } } // capital stock and other related output else if( mName == "CAP" ) { addToType( mModeltime->getper_to_yr( aPeriod ), "CapitalStock", prodTech->getCapitalStock() ); /* addToType( mModeltime->getper_to_yr( aPeriod ), "CapitalStock/1000 Worker", prodTech->getCapitalStock() / scenario->getMarketplace()->getSupply( "Labor", mCurrentRegionName, aPeriod ) ); */ addToType( mModeltime->getper_to_yr( aPeriod ), "Profits", prodTech->mProfits[ aPeriod ] ); addToType( mModeltime->getper_to_yr( aPeriod ), "Retained Earnings", prodTech->expenditures[ aPeriod ].getValue( Expenditure::RETAINED_EARNINGS ) ); } // energy investments annual else if( mName == "EINV" ) { // get energy technologies only if( isEnergyGood( mCurrentRegionName, mCurrentSectorName ) ){ addToType( mModeltime->getper_to_yr( aPeriod ), mCurrentSectorName, prodTech->getAnnualInvestment( aPeriod ) ); } } // non-energy investments annual else if( mName == "NEINV" ) { // get non-energy technologies only if( !isEnergyGood( mCurrentRegionName, mCurrentSectorName ) ){ addToType( mModeltime->getper_to_yr( aPeriod ), mCurrentSectorName, prodTech->getAnnualInvestment( aPeriod ) ); } } // write out all passenger transportation sector results else if( (mName == "PASSTRAN") || (mName == "PASSTRANFC") || (mName == "PASSTRANFCM") || (mName == "PASSTRANFCT") || (mName == "PASSTRANMPG") || (mName == "PASSTRANCOST") ) { // get passenger transport technologies only that have non zero production if( (prodTech->categoryName == "PassTransport") && (prodTech->mOutputs[ 0 ]->getCurrencyOutput( aPeriod ) != 0) ){ double conversionFactor = FunctionUtils::getMarketConversionFactor( mCurrentRegionName, mCurrentSectorName ); if( mName == "PASSTRAN" ) { addToType( mModeltime->getper_to_yr( aPeriod ), mCurrentSectorName, prodTech->mOutputs[ 0 ]->getPhysicalOutput( aPeriod ) ); } else if ( mName == "PASSTRANCOST" ) { addToType( mModeltime->getper_to_yr( aPeriod ), mCurrentSectorName, scenario->getMarketplace()->getPrice(mCurrentSectorName, mCurrentRegionName, aPeriod) * conversionFactor ); } // for all other tables that require inputs else { for( unsigned int i=0; i<prodTech->mLeafInputs.size(); i++ ){ // get secondary energy input only string inputName = prodTech->mLeafInputs[ i ]->getName(); // *** skip if not refined oil input *** // this is problematic for other vehicles that do not use refined oil if( inputName != "RefinedOil" ) { continue; } double fuelConsumption = prodTech->mLeafInputs[ i ]->getPhysicalDemand( aPeriod ); // passenger transportation technology fuel consumption by fuel if( mName == "PASSTRANFC" ) { addToType( mModeltime->getper_to_yr( aPeriod ), inputName, fuelConsumption ); } // passenger transportation technology fuel consumption by mode else if( mName == "PASSTRANFCM" ) { addToType( mModeltime->getper_to_yr( aPeriod ), mCurrentSectorName, fuelConsumption ); } // passenger transportation technology fuel consumption by technology else if( mName == "PASSTRANFCT" ) { addToType( mModeltime->getper_to_yr( aPeriod ), prodTech->name, fuelConsumption ); } // passenger transportation technology fuel economy else if( mName == "PASSTRANMPG" ) { double mpg = prodTech->mOutputs[ 0 ]->getPhysicalOutput( aPeriod ) / fuelConsumption; addToType( mModeltime->getper_to_yr( aPeriod ), prodTech->name, mpg ); } } } } } } } /*! \brief Return whether a good is an energy good. * \param aGoodName Good name. * \return Whether the good is an energy price good. */ bool SGMGenTable::isEnergyGood( const string& aRegionName, const string& aGoodName ){ const IInfo* marketInfo = scenario->getMarketplace()->getMarketInfo( aGoodName, aRegionName, 0, false ); return marketInfo && marketInfo->getBoolean( "IsEnergyGood", false ); } /*! \brief Return whether a good is a primary energy good. * \param aRegionName Region name. * \param aGoodName Good name. * \return Whether the good is a primary energy price good. */ bool SGMGenTable::isPrimaryEnergyGood( const string& aRegionName, const string& aGoodName ){ const IInfo* marketInfo = scenario->getMarketplace()->getMarketInfo( aGoodName, aRegionName, 0, false ); return marketInfo && marketInfo->getBoolean( "IsPrimaryEnergyGood", false ); } /*! \brief Return whether a good is a secondary energy good. * \param aRegionName Region name. * \return Whether the good is a secondary energy price good. */ bool SGMGenTable::isSecondaryEnergyGood( const string& aRegionName, const string& aGoodName ){ const IInfo* marketInfo = scenario->getMarketplace()->getMarketInfo( aGoodName, aRegionName, 0, false ); return marketInfo && marketInfo->getBoolean( "IsSecondaryEnergyGood", false ); }
[ "chrisrvernon@gmail.com" ]
chrisrvernon@gmail.com
e34c582877b0e71e6f9e5ebdc72e570861af5108
e44615ca2ca2896f4bb47269754f21134c14a29a
/commondatatype.cpp
d5e0a902c669e4570698c7ac469dd4aaae487a2f
[]
no_license
lihanxing/Potted_Plant
411c0ce24cd81a309c1820001b99368ce36caf7f
f1d8272638fd4d48ceea2a61cd9e7a6f515ba8a9
refs/heads/main
2023-07-17T09:54:57.823659
2021-09-03T12:15:34
2021-09-03T12:15:34
397,539,263
0
0
null
null
null
null
UTF-8
C++
false
false
4,067
cpp
#include "commondatatype.h" //-----------------PetalStroke------------------------- PetalStroke::PetalStroke(const Stroke &s) { //remove first point and last point,then add their average point stroke.insert(stroke.end(), s.begin() + 1, s.end() - 1); rootPoint.setX((s.front().x() + s.back().x()) / 2); rootPoint.setY((s.front().y() + s.back().y()) / 2); stroke.push_back(rootPoint);//add average point contour = stroke; //now find farPoint int maxDis = -1; int tempDis; for (auto &p : s) { tempDis = euclidDistance(rootPoint, p); if (tempDis >= maxDis) { maxDis = tempDis; farPoint = p; } } } void PetalStroke::generateUVCoord() { glm::vec2 axis(farPoint.x() - rootPoint.x(), farPoint.y() - rootPoint.y()); glm::vec2 axisNormalized = glm::normalize(axis); auto cross2 = [](const glm::vec2& v1, const glm::vec2& v2)->float {return v1.x*v2.y - v1.y*v2.x; }; float axisDis = glm::dot(axis, axisNormalized); uvs.clear(); float Umax, Umin, Vmax, Vmin; Umax = Vmax = -10086; Umin = Vmin = 10086; for (auto& p : stroke) { glm::vec2 vec(p.x() - rootPoint.x(), p.y() - rootPoint.y()); float V = glm::dot(vec, axisNormalized); float U = std::sqrt(std::abs(glm::dot(vec, vec) - glm::dot(vec, axisNormalized)*glm::dot(vec, axisNormalized))); if (cross2(axisNormalized, vec) < 0)U = -U; if (U > Umax)Umax = U; if (U < Umin)Umin = U; if (V > Vmax)Vmax = V; if (V < Vmin)Vmin = V; uvs.push_back(glm::vec2(U, V)); } float Ugap = Umax - Umin; float Vgap = Vmax - Vmin; for (auto& c : uvs) { c.x = (c.x - Umin) / Ugap; c.y = 1 - (c.y - Vmin) / Vgap; } } void PetalStroke::translate(QPoint newOrigin) { for (auto& s : stroke) { s.setX(s.x() - newOrigin.x()); s.setY(newOrigin.y() - s.y()); } for (auto& s : contour) { s.setX(s.x() - newOrigin.x()); s.setY(newOrigin.y() - s.y()); } rootPoint.setX(rootPoint.x() - newOrigin.x()); rootPoint.setY(newOrigin.y() - rootPoint.y()); farPoint.setX(farPoint.x() - newOrigin.x()); farPoint.setY(newOrigin.y() - farPoint.y()); } //-----------------------PetalStroke3D------------------- PetalStroke3D::PetalStroke3D(const Stroke3D &s) { stroke = s; } //-----------------------Triangle----------------------- Triangle::Triangle(int i1, int i2, int i3) { pointIndices.push_back(i1); pointIndices.push_back(i2); pointIndices.push_back(i3); } void strokeFilter(Stroke& stroke) { if (stroke.size() < 5)return; Stroke origin = stroke; const int size = stroke.size(); for (int i = 2; i < size - 2; ++i) { stroke[i].setX((origin[i - 2].x() + origin[i - 1].x() + origin[i].x() + origin[i + 1].x() + origin[i + 2].x()) / 5.0); stroke[i].setY((origin[i - 2].y() + origin[i - 1].y() + origin[i].y() + origin[i + 1].y() + origin[i + 2].y()) / 5.0); } stroke[1].setX((stroke[0].x() + stroke[1].x() + stroke[2].x()) / 3); stroke[1].setY((stroke[0].y() + stroke[1].y() + stroke[2].y()) / 3); stroke[size - 2].setX((stroke[size - 3].x() + stroke[size - 2].x() + stroke[size - 1].x()) / 3.0); stroke[size - 2].setY((stroke[size - 3].y() + stroke[size - 2].y() + stroke[size - 1].y()) / 3.0); } void strokeFilter(Stroke3D& stroke) { if (stroke.size() < 5)return; Stroke3D origin = stroke; const int size = stroke.size(); for (int i = 2; i < size - 2; ++i) { stroke[i].x = ((origin[i - 2].x + origin[i - 1].x + origin[i].x + origin[i + 1].x + origin[i + 2].x) / 5.0); stroke[i].y = ((origin[i - 2].y + origin[i - 1].y + origin[i].y + origin[i + 1].y + origin[i + 2].y) / 5.0); stroke[i].z = ((origin[i - 2].z + origin[i - 1].z + origin[i].z + origin[i + 1].z + origin[i + 2].z) / 5.0); } stroke[1].x = ((stroke[0].x + stroke[1].x + stroke[2].x) / 3); stroke[1].y = ((stroke[0].y + stroke[1].y + stroke[2].y) / 3); stroke[1].z = ((stroke[0].z + stroke[1].z + stroke[2].z) / 3); stroke[size - 2].x = ((stroke[size - 3].x + stroke[size - 2].x + stroke[size - 1].x) / 3); stroke[size - 2].y = ((stroke[size - 3].y + stroke[size - 2].y + stroke[size - 1].y) / 3); stroke[size - 2].z = ((stroke[size - 3].z + stroke[size - 2].z + stroke[size - 1].z) / 3); }
[ "2645376975@qq.com" ]
2645376975@qq.com
ab4a3c5bbcfc8edf705287111f4afd2c485c63f9
0c420e8b97af7a1dacb668b1b8ef1180a8d47588
/Backup2306/EvCoreHeaders/EvImaging/MathAlgo.h
24b6fc33a68b5ae7cf0e763932306d141d28f6c1
[]
no_license
Spritutu/Halcon_develop
9da18019b3fefac60f81ed94d9ce0f6b04ce7bbe
f2ea3292e7a13d65cab5cb5a4d507978ca593b66
refs/heads/master
2022-11-04T22:17:35.137845
2020-06-22T17:30:19
2020-06-22T17:30:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
31,259
h
#pragma once #include "stdafx.h" #include "afxtempl.h" #include <math.h> #ifndef PI #define PI 3.1415926535 #endif class CPoint2D { public: double x,y; CPoint2D(); CPoint2D(CPoint); CPoint2D(int x0, int y0); CPoint2D(double x0, double y0); CPoint2D(int x0, double y0); CPoint2D(double x0, int y0); CPoint2D(const CPoint2D &); double GetDistance(CPoint2D); double GetDistance(CPoint2D* ppt2D); CPoint2D GetInterpol(CPoint2D* ppt2DStart, CPoint2D* ppt2DEnd, double dRatio); void SetPoint(const CPoint2D &pt2D); void RotateAbout(CPoint2D pt2D, double Angle); CPoint2D & operator =(CPoint2D pt2d); BOOL operator ==(CPoint2D); CPoint2D & operator += (const CPoint2D &v); CPoint2D & operator -= (const CPoint2D &v); CPoint2D & operator /= (const double d); CPoint2D & operator / (const double d); CPoint2D operator -(CPoint2D pt2dSub); CPoint2D operator +(CPoint2D pt2dAdd); }; class CSize2D { public: double cx,cy; CSize2D(); CSize2D(CSize); CSize2D(int x0, int y0); CSize2D(double x0, double y0); CSize2D(const CSize2D &); CSize2D & operator =(CSize2D cs2d); CSize2D & operator =(CSize cs); BOOL operator ==(CSize2D); }; class CPoint2DArray : public CArray<CPoint2D,CPoint2D &> { public: CPoint2DArray(); ~CPoint2DArray(); CPoint2DArray(CPoint* ppt, int nptNo); CPoint2DArray(CPoint2D* ppt2D, int npt2DNo); CPoint2DArray(CPoint2DArray &); CPoint2DArray & operator = (CPoint2DArray &); int GetGravityCenter(CPoint2D* ppt2DGravityCenter); void Zoom(CPoint2D* ppt2DCenter, double dRatio); }; class CVector2D : public CPoint2D{ public: CVector2D(); CVector2D(CPoint ptDst,CPoint ptSrc); CVector2D(CPoint2D pt2DDst,CPoint2D ptSrc=CPoint2D(0,0)); CVector2D(int nX0,int nY0); CVector2D(double dX0,double dY0); CVector2D(const CVector2D &); double GetSize(); int Normalize(); CVector2D & operator =(CVector2D); int GetUnit(CVector2D* pvctDst); // Pointer to A 2-D Vector double operator ^ (CVector2D); // A 2-D Vector BOOL IsValid(); int GetAngleRad(CVector2D vt2D, // A 2D Vector double& dAngleRad); // Angle in Radians }; class CLine2D { public: CLine2D(); CLine2D(CPoint2D pt2D, // A Point on the Line CVector2D vt2D); // Line Vector CLine2D(CPoint2D pt2D, // A Point on Line double dAngle); // Angle of the Line CLine2D(CPoint2D pt2D0, // A Point on the Line CPoint2D pt2D1); // Another Point on the Line CLine2D(CPoint pt0, // A Point on the Line CPoint pt1); // Another Point on the Line ~CLine2D(); CLine2D & operator =(CLine2D ln2D); BOOL IsInValid(); void Reset(); void SetPosition(double dPosX, double dPosY); void SetPosition(CPoint2D pt2D); int SetDirection(double dVt2DX, double dVt2DY); int SetDirection(double dAngle); int SetDirection(CVector2D vt2D); CPoint2D GetPosition(); CVector2D GetDirection(); int GetParallelPoints(CPoint2D* ppt2DSrc, double dAbsDis, CPoint2D* ppt2DDst0, CPoint2D* ppt2DDst1); int GetParallelPoint(CPoint2D* ppt2DSrc, double dAbsDis, int nXCheckFlag, int nYCheckFlag, CPoint2D* ppt2DDst); int GetPerpendicularPoints(CPoint2D* ppt2DSrc, double dAbsDis, CPoint2D* ppt2DDst0, CPoint2D* ppt2DDst1); int GetPerpendicularPoint(CPoint2D* ppt2DSrc, double dAbsDis, int nXCheckFlag, int nYCheckFlag, CPoint2D* ppt2DDst); int GetDiagonalPoints(CPoint2D* ppt2DSrc, double dAbsParallelDis, double dAbsPerpendicularDis, CPoint2D* ppt2DParallelPair0Pt0, CPoint2D* ppt2DParallelPair0Pt1, CPoint2D* ppt2DParallelPair1Pt0, CPoint2D* ppt2DParallelPair1Pt1); int IsOnLine(CPoint2D* ppt2DSrc, // Pointer to A Point BOOL* pbOnLine); // Status whether the point is on the line: 1:On Line; 0: Not On Line int GetDistance(CPoint2D* ppt2DSrc, // Pointer to A Point double* pdDis); // Pointer to Absolute Distance int GetDistance(CPoint* pptSrc, double* pdDis); int GetSignedDistance(CPoint2D* ppt2DSrc, // Pointer to A Point double* pdDis); // Pointer to Signed Distance int GetSignedDistance(CPoint* pptSrc, // Pointer to A Point double* pdDis); // Pointer to Signed Distance int GetDistanceX(CPoint2D* ppt2DSrc, // Pointer to A Point double* pdDis); // Pointer to Horizontal Distance int GetDistanceY(CPoint2D* ppt2DSrc, // Pointer to A Point double* pdDis); // Pointer to Vertical Distance int GetProjectionX(CPoint2D* pptSrc, // Pointer to A Point CPoint2D* pptProj); // Pointer to Projection Point int GetProjectionY(CPoint2D* pptSrc, // Pointer to A Point CPoint2D* pptProj); // Pointer to Projection Point int GetProjection(CPoint2D* ppt2dSrc, // Pointer to A Point CPoint2D* ppt2DProj); // Pointer to Projection Point int IsOnSameSide(CPoint2D* pptSrc1, // Pointer to A Point CPoint2D* pptSrc2, // Pointer to Another Point BOOL* pbOnSameSide); // Status whether two points are on the same side of the line int GetBiSectLine(CLine2D *pln2DLine1, CLine2D *pln2DLine2); int GetAverageLine(CLine2D *pln2D, int nln2D); int GetBestFittingLine(CPoint2D* ppt2D, // Pointer to a series of Points int nCount); // Number of Points int GetBestFittingLine(CPoint* ppt, int nCount); int GetIntercept(CLine2D* pln2D, // Pointer to A Line CPoint2D* ppt2DIntercept); // Pointer to Intersection Point int GetAngleDeg(double& pdAngle); // Angle of This Line in Degree int GetAngleRad(double& pdAngle); // Angle of This Line in Radians int GetX(double dY, // Y Coordinate of a Point double* dX); // Pointer to X Coordinate of a Point (that is on this line) int GetY(double dX, // X Coordinate of a Point double* dY); // Pointer to Y Coordinate of a Point (that is on this line) int GetPerpendicularLine(CPoint2D* ppt2D, // Pointer to A Point on Perpendicular Line CLine2D* pln2DLine); // Perpendicular Line int GetParallelLine(CPoint2D* ppt2D, // Pointer to A Point on Parallel Line CLine2D* pln2DLine); // Parallel Line protected: CPoint2D Position; //The line passes through the point Position CVector2D Direction; //The direction vector of the line BOOL m_bInValid; // Status of This Line : 1: Invalid; 0: Valid private: }; class PROJ_1D_X { public: PROJ_1D_X(); ~PROJ_1D_X(); int nProjX; int* pnY; int nYSize; }; class PROJ_1D_Y { public: PROJ_1D_Y(); ~PROJ_1D_Y(); int nProjY; int* pnX; int nXSize; }; class PROJ_2D_X { public: PROJ_2D_X(); ~PROJ_2D_X(); void MemLocate(int nInspNo); void Clean(); int* pnSortX; int* pnY; int* pnSortXIndex; int nptSize; PROJ_1D_X* pPROJX; int* pnHistPosSort; int* pnHistConvSort; int* pnHistConvSortIndex; int nHistConvNo; int nHistSize; int nHistConv; int nMaxCovHist; int nMaxCovHistPos; private: int nMemLoc; }; class PROJ_2D_Y{ public: PROJ_2D_Y(); ~PROJ_2D_Y(); void MemLocate(int nInspNo); void Clean(); int* pnSortY; int* pnX; int* pnSortYIndex; int nptSize; PROJ_1D_Y* pPROJY; int* pnHistPosSort; int* pnHistConvSort; int* pnHistConvSortIndex; int nHistSize; int nHistConv; int nMaxCovHist; int nMaxCovHistPos; private: int nMemLoc; }; class PROJ_2D_Search{ public: PROJ_2D_Search(); ~PROJ_2D_Search(); void MemLocate(int nInspNo); void Clean(); int* pnData; int nptSize; int* pnHistPosSort; int* pnHistConvSort; int* pnHistConvSortIndex; int nHistSize; int nHistConv; int nMaxCovHist; int nMaxCovHistPos; }; class ADV_HIST_1D_RSLT { public: ADV_HIST_1D_RSLT(); ~ADV_HIST_1D_RSLT(); void Clean(); void MemLocate(int nNo); int* pnHist; long* plPos; int nHistNo; }; class ADV_CONV_HIST_1D_RSLT { public: ADV_CONV_HIST_1D_RSLT(); ~ADV_CONV_HIST_1D_RSLT(); void Clean(); void MemLocate(int nNo); int* pnHist; long* plPosStart; long* plPosEnd; int nHistNo; }; class CAdvHistogram{ protected: typedef struct { int nFoundMaxPt; int nStartProjIndex; int nEndProjIndex; CRect rcFound; bool bFoundByProjX; } PROJ_2D_Result; PROJ_2D_X ProjX; PROJ_2D_Y ProjY; PROJ_2D_Result ProjResult; ADV_CONV_HIST_1D_RSLT AdvConvHist1DXRslt; ADV_CONV_HIST_1D_RSLT AdvConvHist1DYRslt; public: int GetHist(int *pnData, int nDataNo, ADV_HIST_1D_RSLT* pAdvHist1DRslt); int GetAccHist(int *pnData, int nDataNo, ADV_HIST_1D_RSLT* pAdvHist1DRslt); int GetAccHist(long *plData, int nDataNo, ADV_HIST_1D_RSLT* pAdvHist1DRslt); int GetConvHist(int *pnData, int nDataNo, int nHistConv, ADV_CONV_HIST_1D_RSLT* pAdvConvHist1DRslt); int GetConvHist(long *plData, int nDataNo, int nHistConv, ADV_CONV_HIST_1D_RSLT* pAdvConvHist1DRslt); int GetConvHist(ADV_HIST_1D_RSLT* pAdvHist1DRslt, int nHistConv, ADV_CONV_HIST_1D_RSLT* pAdvConvHist1DRslt); int GetMaxConvHist1D(int *pnData, int nDataNo, int nHistConv, int &nMaxHist, int &nMaxHistPos); int GetFastMaxConvHist1D(int *pnData, int nDataNo, int nHistConv, int nHistMinTol, int &nMaxHist, int &nMaxHistPos); int GetMaxConvHist1D(long *plData, int nDataNo, int nHistConv, int &nMaxHist, long &lMaxHistPos); int GetMaxConvHist2D(CPoint2D *ppt2DInsp, int nInspNo, CSize2D* pcs2DHistConv, CPoint2D *ppt2DSelected, int &nSelectedSize, CPoint2D *ppt2DNOTSelected, int &nNOTSelectedSize); int GetMaxConvHist1D(int *pnData, int nDataNo, int nHistConv, int &nMaxHist, int &nMaxHistPos, double &dAvgPos); int GetMaxConvHist1D(double *pdData, int nDataNo, double dHistConv, int &nMaxHist, double &dAvgPos); protected: int Proj2DX(long* plX, long* plY, int nInspNo, int nHistConv); int Proj2DY(long* plX, long* plY, int nInspNo, int nHistConv); int FindMaxProj2DX(int nProjIndex); int FindMaxProj2DY(int nProjIndex); int GetFastConvHist1D(ADV_HIST_1D_RSLT* pAdvHist1DRslt, int nHistConv, ADV_CONV_HIST_1D_RSLT* pAdvConvHist1DRslt); int GetMaxConvHist1DCmpFoundMax(int *pnData, int nDataNo, int nHistConv, int nFndMaxHist, int &nMaxHist, int &nMaxHistPos); PROJ_2D_Search ProjSearch; }; class CPointPatternCorrelation { public: CPointPatternCorrelation(); int GetLUTSize(int nTeachPatternNo, // Number of the Points of the 2D Teach Pattern int nSearchAngle, // Search Angle double dAngleStep, // Step of Search Angle long& lLUTSize); // Size of LUT int InitLUT(CPoint *pptTeachPattern, // 2D Point Array of A Teach Pattern int nTeachPatternNo, // Number of the Points of the 2D Teach Pattern int nSearchAngle, // Search Angle double dAngleStep, // Step of Search Angle int *pnLUTX, // LookUpTable of X Coordinates int *pnLUTY); // LookUpTable of Y Coordinates int FindPattern1D(double *pdTeachPos, int nTeachPosNo, double *pdInspPos, int nInspPosNo, double dTeachNInspOffsetNominal, double dTeachNInspOffsetTol, double dPosVarTol, int *pnMatchingPosIndex, int &nMatchingPosNo, int *pnNotMatchingPosIndex, int &nNotMatchingPosNo, double *pdCorrPos, BOOL *pbCorrStatus, bool bAccurate); int FindPeriodicPattern1D(double *pdTeachPos, int nTeachPosNo, double dTeachPitch, double *pdInspPos, int nInspPosNo, double dPosVarTol, int *pnMatchingTeachPosIndex, int *pnMatchingInspPosIndex, int &nMatchingPosNo, int *pnNotMatchingInspPosIndex, int &nNotMatchingInspPosNo, double *pdMissingInspPos, int &nMissingPosInspNo, bool bAccurate); int FindPatternPos(CPoint *pptTeachPattern, // 2D Point Array of A Teach Pattern int m_nTeachPatternNo, // Number of the Points of the 2D Teach Pattern CPoint *pptInspectPattern, // 2D Point Array of A Inspection Pattern int nInspectPatternNo, // Number of the Points of the 2D Inspection Pattern int nSearchAngle, // Search Angle double dAngleStep, // Step of Search Angle int nXShift, // X Shift int nYShift, // Y Shift int nCenterUncertainty, // Tolerance of Point Matching int *pnLUTX, // LookUpTable of X Coordinates int *pnLUTY, // LookUpTable of Y Coordinates double &dFndAngle, // Found Rotation Angle double &dFndXShift, // Found X Shift double &dFndYShift); // Found Y Shift void PointSorting(CPoint *pptTeachPattern, // 2D Point Array of A Teach Pattern int nTeachPatternNo, // Number of the Points of the 2D Teach Pattern CPoint *pptInspectPattern, // 2D Point Array of A Inspection Pattern BOOL *pbInspectPattern, // Status of Matching: 1: Matching; 0: Not Matching int nInspectPatternNo, // Number of the Points of the 2D Inspection Pattern int nCenterUncertainty, // Tolerance of Point Matching double &dFndAngle, // Found Rotation Angle double &dFndXShift, // Found X Shift double &dFndYShift); // Found Y Shift }; class CHoughTransform { public: CHoughTransform(); int GetLineLUTStatus(CRect* prcROI, // Pointer to ROI double dNominalAngleRad, // Nominal Angle double dTolAngleRad, // Angle Tolerance double dAngleStep, // Step of Angle bool& bLUTChangeStatus, // Status of Change of LUT: 1: Change LUT. 0: Not Change LUT bool& bLUTStatus); // Status of LUT: 1: LUT Generated. 0: LUT Not Generated int GetLineLUTSize(CRect* prcROI, // Pointer to ROI double dTolAngleRad, // Angle Tolerance double dAngleStep, // Step of Angle long& lLUTSize); // Size of LUT int InitLineLUT(CRect* prcROI, // Pointer to ROI double dNominalAngleRad, // Nominal Angle double dTolAngleRad, // Angle Tolerance double dAngleStep, // Step of Angle short int* pnLUT); // Pointer to LUT int LineLUTHoughTransform(CPoint2D *ppt2DInsp, // Pointer to Inspected Points int nInspNo, // Number of Inspected points short int* pnLUT, // Pointer to LUT long lLUTSize, // Size of LUT int nOnLineTol, // Tolerance of Distance between A Point and Hough Transform Line CPoint2D *ppt2DOnLine, // Pointer to the Points On Hough Transform Line int &nOnLineSize, // Number of Points On Hough Transform Line CPoint2D *ppt2DNOTOnLine, // Pointer to the Points NOT On Hough Transform Line int &nNOTOnLineSize); // Number of Points NOT On Hough Transform Line ////////////////////////////////////// //This function has a bug and will be removed. //Please use the function "HoughTransformLine" int LineHoughTransform(CPoint2D *ppt2DInsp, // Pointer to Inspected Points int nInspNo, // Number of Inspected points double dNominalAngleRad, // Nominal Angle double dTolAngleRad, // Angle Tolerance double dAngleStep, // Step of Angle double dOnLineTol, // Tolerance of Distance between A Point and Hough Transform Line CPoint2D *ppt2DOnLine, // Pointer to the Points On Hough Transform Line int &nOnLineSize, // Number of Points On Hough Transform Line CPoint2D *ppt2DNOTOnLine, // Pointer to the Points NOT On Hough Transform Line int &nNOTOnLineSize); // Number of Points NOT On Hough Transform Line /////////////////////////////////////////////////// int HoughTransformLine(CPoint2D *ppt2DInsp, // Pointer to Inspected Points int nInspNo, // Number of Inspected points double dNominalAngleRad, // Nominal Angle double dTolAngleRad, // Angle Tolerance double dAngleStep, // Step of Angle double dOnLineTol, // Tolerance of Distance between A Point and Hough Transform Line CPoint2D *ppt2DOnLine, // Pointer to the Points On Hough Transform Line int &nOnLineSize, // Number of Points On Hough Transform Line CPoint2D *ppt2DNOTOnLine, // Pointer to the Points NOT On Hough Transform Line int &nNOTOnLineSize, // Number of Points NOT On Hough Transform Line int nMinOnLinePercentageForFastSearch = 60); private: CAdvHistogram AdvHistogram; int m_nAngleFound; bool m_bLUTStatus; bool m_bLUTChangeStatus; int m_nLUTWidth; int m_nLUTHeight; double m_dTableNominalAngle; double m_dTableAngleTol; double m_dTableAngleStep; int m_nTableAngleSize; long m_lROISize; long m_lLUTSize; long m_lHoughSize; CRect m_rcBounding; double m_dAngleMin; double m_dAngleMax; void GetBoundingRect(CPoint *pptInsp, int nInspNo, CRect* prcBounding); void GetOffsetPoints(CPoint* pptSrc, int nSrc, CPoint* pptDst, CPoint* pptOffset); }; class CPoint3D { public: double x,y,z; CPoint3D(); CPoint3D(CPoint,double dZ0=0); CPoint3D(double dX0,double dY0,double dZ0=0); CPoint3D(const CPoint3D &); CPoint3D & operator =(CPoint3D); CPoint3D operator +(CPoint3D); CPoint3D operator -(CPoint3D); CPoint3D operator *(double); CPoint3D operator /(double); CPoint3D &operator +=(CPoint3D); CPoint3D &operator -=(CPoint3D); CPoint3D &operator *=(double); CPoint3D &operator /=(double); BOOL operator == (CPoint3D); double GetDistance(CPoint3D); // A 3-D Point }; class CVector3D : public CPoint3D{ public: CVector3D(); CVector3D(CPoint3D pt3DDst,CPoint3D pt3DSrc=CPoint3D(0,0,0)); CVector3D(double dX0,double dY0,double dZ0=0); CVector3D(const CVector3D &); //CVector3D(const CVector2D &); double GetSize(); int Normalize(); CVector3D & operator =(CVector3D) ; CVector3D operator *(CVector3D); CVector3D operator *(double d); int GetUnit(CVector3D* pvct3D); double operator ^ (CVector3D); BOOL IsValid(); int GetAngleRad(CVector3D vt3D, // A 3-D Vector double& dAngleRad); // Angle between the Vector and This Vector }; class CLine3D { public: CPoint3D Position; //The line passes through the point Position CVector3D Direction; //The direction vector of the line public: CLine3D(); CLine3D(CPoint3D pt3D,CVector3D vt3D); CLine3D(CPoint3D pt3D0,CPoint3D pt3D1); BOOL IsValid(); int IsOnLine(CPoint3D, // A 3-D Point BOOL* pbOnLine); // Status of Point-On This Line : 1: Point On This Line; 0: Point Not On This Line int GetDistance(CPoint3D, // A 3-D Point double& dDis); // Distance between The Point and This Line private: BOOL m_bValid; // Status of This Line }; class CSize3D { public: // Member Variables double cx,cy,cz; // Methods CSize3D(); CSize3D(CSize); CSize3D(int x0, int y0, int z0); CSize3D(double x0, double y0, double z0); CSize3D(const CSize3D &); CSize3D & operator =(CSize3D cs3d); }; class CPlane { public: CVector3D Normal; //A 3D vector normal to the plane CPoint3D Position; // A point which lies on the plane public: CPlane(); CPlane(CPoint3D p,CVector3D n); CPlane(CLine3D l0,CLine3D l1); CPlane(CPoint3D p,CLine3D l); CPlane(CPoint3D p0,CPoint3D p1,CPoint3D p2); BOOL IsValid(); int GetDistance(CPoint3D p1, // A 3-D Point double& dDis); // Distance between the Point and This Plane int GetAngleRad(CVector3D v, // A 3-D Vector double &dAngleRad); // Angle between the Vector and This Plane int GetAngleRad(CLine3D l, // A 3-D Line double &dAngleRad); // Angle between the Line and This Plane int GetAngleRad(CPlane p, // A Plane double &dAngleRad); // Angle between the Plane and This Plane int GetIntersection(CLine3D, // A 3-D Line CPoint3D *); // A Pointer to A 3-D Point int GetProjection(CPoint3D pt3DSrc, // A Source Point CPoint3D& pt3DProj); // The Projection Point }; class CRectangle2D { CPoint2D m_pointCenter; // Center of The Rectangle double m_Width; // Width of The Rectangle double m_Height; // Height of The Rectangle double m_Angle; // Angle of The Rectangle public: CRectangle2D(); CRectangle2D(CRectangle2D &); CRectangle2D(CRect &); CRectangle2D(CPoint2D* ppt2D0, CPoint2D* ppt2D1, CPoint2D* ppt2D2, CPoint2D* ppt2D3); CRectangle2D(CPoint2D* ppt2D0, CPoint2D* ppt2D1, CPoint2D* ppt2D2, CPoint2D* ppt2D3, CRect* prcROI, BOOL* pbPass); CRectangle2D(CRectangle2D* prc2D, CRect* prcROI, BOOL* pbPass); CRectangle2D & operator =(CRectangle2D& rc2D); double GetWidth(); double GetHeight(); void SetSize(CSize cs); void SetSize(CSize2D cs2D); CPoint2D GetDevTopLeft(); CPoint2D GetDevTopRight(); CPoint2D GetDevBottomLeft(); CPoint2D GetDevBottomRight(); CPoint2D GetDevLftMost(); // Get the Device Left Most Point CPoint2D GetDevTopMost(); // Get the Device Top Most Point CPoint2D GetDevRhtMost(); // Get the Device Right Most Point CPoint2D GetDevBotMost(); // Get the Device Bottom Most Point CPoint2D GetGeoTopMost(); CPoint2D GetGeoBottomMost(); CPoint2D GetGeoLeftMost(); CPoint2D GetGeoRightMost(); int DeflateRect2D(double dl, double dt, double dr, double db); int InflateRect2D(double dl, double dt, double dr, double db); double GetAngle(); CPoint2D GetCenterPoint(); void Shift(CPoint2D); // Offset void ShiftTo(CPoint2D pt2D); // Center of The Rectangle void RotateAbout(CPoint2D p, // Center of The Rectangle double Angle); // Angle of Rotation void RotateBy(double Angle); // Angle of Rotation void RotateTo(double Angle); // Angle of The Rectangle int Rotate(CPoint2D* ppt2DRotCtr, double dAngle); CRect GetBoundingRect(); CRect GetBoundingRectWithoutInflate(); private: int GetRect2DByFixOnePt(CPoint2D* ppt2DOrg, CPoint2D* ppt2DOthers, CRect* prcROI, CRectangle2D* prc2DMaxROI); int GetExpandRect2D(CPoint2D* ppt2DOrg, CPoint2D* ppt2DSide, CPoint2D* ppt2DCornerOrg, CRect* prcROI, CRectangle2D* prc2D); int GetLinePtsInROI(CPoint2D* ppt2DOrg, CPoint2D* ppt2D, CPoint2D* ppt2DInROI, CRect* prcROI); }; class CRECTANGLE2D_FIND_PARM { public: CRECTANGLE2D_FIND_PARM(); ~CRECTANGLE2D_FIND_PARM(); CSize2D cs2DRect; CSize2D csRectVarTol; CSize2D csEdgePtVarTol; int nTopSampleStep; int nTopPercentage; int nBotSampleStep; int nBotPercentage; int nLftSampleStep; int nLftPercentage; int nRhtSampleStep; int nRhtPercentage; double dNominalAngle; double dMaxTiltAngle; double dAngleStep; }; class CRECTANGLE2D_FOUND_INFO { public: CRECTANGLE2D_FOUND_INFO(); ~CRECTANGLE2D_FOUND_INFO(); CRectangle2D rc2DRect; int nTopPercentage; int nBotPercentage; int nLftPercentage; int nRhtPercentage; }; class CRECTANGLE2D_FOUND_RSLT { public: CRECTANGLE2D_FOUND_RSLT(); ~CRECTANGLE2D_FOUND_RSLT(); CRECTANGLE2D_FOUND_INFO* pRect2DFndInfo; int nRect2DFndNo; }; class CPackageEdgeSelectedPoints { public: CPackageEdgeSelectedPoints(); ~CPackageEdgeSelectedPoints(); void Clean(); CPackageEdgeSelectedPoints & operator =(CPackageEdgeSelectedPoints PackageEdgeSelectedPoints); bool* pbLftIndex; bool* pbRhtIndex; bool* pbTopIndex; bool* pbBotIndex; int nLft; int nRht; int nTop; int nBot; int nLftScore; int nTopScore; int nRhtScore; int nBotScore; int nSumScore; double dAngle; }; class CRectangle2DFind { public: CRectangle2DFind(); ~CRectangle2DFind(); CRectangle2D rc2DFound; CPackageEdgeSelectedPoints *pPackageEdgeSelectedPoints; int GetRectangle2D(CPoint2D* ppt2DInspTop, int nInspTopNo, CPoint2D* ppt2DInspBot, int nInspBotNo, CPoint2D* ppt2DInspLft, int nInspLftNo, CPoint2D* ppt2DInspRht, int nInspRhtNo, CRECTANGLE2D_FIND_PARM* pRect2DFindParm); int DistanceMatching(long* plFirstEdgePos, int nFirstEdgePosNo, long* plLastEdgePos, int nLastEdgePosNo, int nDistVar, int nDist, int nEdgePtVar, int nFirstEdgeHistThreshold, int nLastEdgeHistThreshold, int* pnFirstEdgeStartPos, int* pnFirstEdgeEndPos, int* pnLastEdgeStartPos, int* pnLastEdgeEndPos, int* pnEdgePair); CRECTANGLE2D_FOUND_RSLT Rect2DFndRslt; private: typedef struct { int nSide0Percentage; int nSide0HistIndex; int nSide1Percentage; int nSide1HistIndex; int nCrossPercentage; } RECT_PROJ; int GetRectProj(); int nTopPercentage; int nBotPercentage; int nLftPercentage; int nRhtPercentage; CSize csRect; CSize csRectVarTol; CSize csEdgePtVarTol; double dPkgAngle; CPoint ptPkgCtr; int nTimesX; int nTimesY; int GetVerticalEdgeHist(long* plSrcX, long* plSrcY, int nInspNo, int nEdgeVar, CRect* prcEdge); int GetHorizontalEdgeHist(long* plSrcX, long* plSrcY, int nInspNo, int nEdgeVar, CRect* prcEdge); void GetVerticalEdgeIndex(long* plSrcX, long* plSrcY, int nInspNo, CRect* prcEdge, int nEdgeVar, bool* pbSelected); void GetHorizontalEdgeIndex(long* plSrcX, long* plSrcY, int nInspNo, CRect* prcEdge, int nEdgeVar, bool* pbSelected); int FindOverlap(int nLftEdgeStartPos, int nLftEdgeEndPos, int nRhtEdgeStartPos, int nRhtEdgeEndPos, int nWidth, int nWidthVar, int* pnLftEdgeStartPosDst, int* pnLftEdgeEndPosDst, int* pnRhtEdgeStartPosDst, int* pnRhtEdgeEndPosDst); int RangeMerge(int* pnStartPos, int* pnEndPos, int* pnNo); }; class CRectInfo { public: CRectInfo(); ~CRectInfo(); void Clean(); int SetLabel(CRect* prcSrc, CSize* pcsFOV, int nLabel); CRect rc; int m_nLabel; int* pnLabelX; int nLabelXSize; int* pnConnectedLabelHistX; int nConnectedLabelHistX; int* pnLabelY; int nLabelYSize; int* pnConnectedLabelHistY; int nConnectedLabelHistY; int* pnConnectedLabelHist; int nConnectedLabelHist; bool bMerged; }; class CMergedRect { public: CMergedRect(); ~CMergedRect(); void Clean(); CRect rcMerged; int* pnMergedHist; int nMergedLabel; int* pnMergedLabel; }; class CRectMerge { public: CRectMerge(); ~CRectMerge(); void Clean(); CMergedRect* pMergedRect; CRect* prcFoundMerged; int nFoundMerged; int nLabelStart; int Merge(CRect* prcRect, int nRectNo, CSize* pcsFOV); private: long* plAccX; long* plAccY; CRect* prcMerge; CRectInfo* pRectInfo; int npMergedRect; int nRectInfoNo; int nMergedRect; int nRectMergeNo; void FndConnectLocalLabelX(int nRectIndex); void FndConnectLocalLabelY(int nRectIndex); void FndCommonLocalLabel(int nRectIndex); }; CPoint2D RotatePoint2D(CPoint2D ptOrg, // Point to Be Rotated CPoint2D ptRef, // Point of Rotation Center double dAngle); // Angle of Rotation CPoint2D RotatePoint2DOfRigidObject(CPoint2D ptOrg_PC, // center point of package window in teaching process CPoint2D ptOrg_OC, //the CRect of template window in teaching process CPoint2D ptRef_PC,// center point of package window in inspection process double dAngle) ; // the angle rotated around the the center of package in inspection process CRect RotateRecWindow2D(CPoint2D ptOrg_PC, // center point of package window in teaching process CRect rcOrg_OC, //the CRect of template window in teaching process CPoint2D ptRef_PC, // center point of package window in inspection process double dAngle); // the angle rotated around the the center of package in inspection process //BOOL IsCollinear(double ptsX[], double ptsY[], double dDelta); int IsCollinear(CPoint2D* ppt2d, // Pointer to Points int nSize, // Number of Points double dDelta, // Tolerance of Collinear BOOL* pbCollinear); // Result of Collinear int GetCircleCenter(CPoint2D* ppt2DSrc1, CPoint2D* ppt2DSrc2, CPoint2D* ppt2DSrc3, CPoint2D* ppt2DCenter); void Sorting(int *nData, int nDataNo, int *index, BOOL bAscend); void Sorting(int *pnData, int nDataNo, BOOL bAscend); void Sorting(long *nData, int nDataNo, int *index, BOOL bAscend); void Sorting(long *pnData, int nDataNo, BOOL bAscend); void Sorting(double *nData, int nDataNo, BOOL bAscend); void Sorting(double *nData, int nDataNo, int *index, BOOL bAscend); int Round(double d); int GetCombination(int nBase, int *pnOrder, int& nValid); double InterpolX(CPoint2D ptBefore,CPoint2D ptAfter, double dThres); int InterpolCPoint(CPoint* pptSrc1, BYTE byteVal1, CPoint* pptSrc2, BYTE byteVal2, BYTE byteThreshold, CPoint2D* ppt2DInterpol, bool bThresholdCheck); int GetRoughBallCenter(CPoint2D* ppt2DBallEdge, int nBallEdge, CPoint2D* ppt2DEstimatedCenter, double dBallRadiusTol, double dCenterStep, CSize2D* pcs2DShiftTol, CPoint2D* ppt2DBallCenter, double* pdRadiusInsp, int* pnPercentage); int GetPointsBoundingRect(CPoint2D* ppt2D, int nptNo, CRect* prcBounding); int GetPointsBoundingRect(CPoint* ppt, int nptNo, CRect* prcBounding); int GetPointsBoundingRect(CArray<CPoint2D, CPoint2D>* pArypt2D, CRect* prcBounding); int GetPointsBoundingRect(CArray<CPoint, CPoint>* pArypt, CRect* prcBounding); int GetRoughBallCenter(CPoint* pptBallEdge, int nBallEdge, CPoint2D* ppt2DEstimatedCenter, double dBallRadiusTol, double dCenterStep, CSize2D* pcs2DShiftTol, CPoint2D* ppt2DBallCenter, double* pdRadiusInsp, int* pnPercentage); class CInterpolationBy2Pts { public: CInterpolationBy2Pts(); ~CInterpolationBy2Pts(); void Clean(); int SetPoint2DAry(CPoint2D* pPt2D, int nPt2DNo); int SetPointAry(CPoint* pPt, int nPtNo); int GetY(double dx, double* pdInterpolationy); int GetYByMinDisPts(double dx, double* pdInterpolationy); public: int nNo; CPoint2D* ppt2DSorting; private: int* pnMappingIndex; int nMappingNo; double* pdx; double* pdy; int GetIndex(double dx, int* pnIndex); }; class CInterpolationBy3Pts { public: CInterpolationBy3Pts(); ~CInterpolationBy3Pts(); void Clean(); int SetPoint2DAry(CPoint2D* pPt2D, int nPt2DNo); int GetY(double dx, double* pdInterpolationy); int ModifyPoint(double* pdDifY, BOOL* pbMatch, int nInterpolationNo, int nStartX, int nEndX, int nSegmentMatchingPercentageTol, double dDifYTol); public: int nNo; CPoint2D* ppt2DSorting; private: int CalculateGradVal(); int* pnMappingIndex; int nMappingNo; double* pdx; double* pdy; double* pdGrad; double* pParmA; double* pParmB; int GetIndex(double dx, int* pnIndex); };
[ "huynhbuutu@gmail.com" ]
huynhbuutu@gmail.com
d26dc66907b1d33807ccb9382fa9a8ff816f61f0
c6fc5b57b58c44745f6b9264950fb1409ab83057
/head_wo_len/app.cpp
2178260dff3265850cd2687fe2c306798b79b024
[]
no_license
mintj/jpverb_classification
71965b93ae164f950d94a4989c73d08bf0bd948c
d1414b4288c4712f2ab829050f3cbce2d0c0386d
refs/heads/master
2023-02-15T09:31:47.601848
2021-01-15T04:46:28
2021-01-15T04:46:28
327,861,274
0
0
null
null
null
null
UTF-8
C++
false
false
6,053
cpp
/// \file /// \ingroup tutorial_tmva /// \notebook -nodraw /// This macro provides a simple example on how to use the trained classifiers /// within an analysis module /// - Project : TMVA - a Root-integrated toolkit for multivariate data analysis /// - Package : TMVA /// - Exectuable: TMVAClassificationApplication /// /// \macro_output /// \macro_code /// \author Andreas Hoecker #include <cstdlib> #include <vector> #include <iostream> #include <map> #include <string> #include "TFile.h" #include "TTree.h" #include "TString.h" #include "TSystem.h" #include "TROOT.h" #include "TStopwatch.h" #include "TMVA/Tools.h" #include "TMVA/Reader.h" #include "TMVA/MethodCuts.h" using namespace TMVA; void copy_vals(float * fx, float & flen, int * x, int len) { for (int i = 0; i < 6; ++i) { fx[i] = x[i]; } flen = len; } void get_numbers(int * cnt, TTree * t, int * n, float * r) { n[0] = cnt[0]; n[1] = cnt[1]; n[2] = cnt[2]; n[3] = t->GetEntries(); r[0] = 100.*n[0]/n[3]; r[1] = 100.*n[1]/n[3]; r[2] = 100.*n[2]/n[3]; } void app( TString myMethodList = "" ) { //--------------------------------------------------------------- // This loads the library TMVA::Tools::Instance(); std::cout << std::endl; std::cout << "==> Start TMVAClassificationApplication" << std::endl; // Create the Reader object TMVA::Reader *reader = new TMVA::Reader( "!Color:!Silent" ); // Create a set of variables and declare them to the reader // - the variable names MUST corresponds in name and type to those given in the weight file(s) used float fx[6]; float flen; reader->AddVariable("x[0]", fx); reader->AddVariable("x[1]", fx+1); reader->AddVariable("x[2]", fx+2); reader->AddVariable("x[3]", fx+3); reader->AddVariable("x[4]", fx+4); reader->AddVariable("x[5]", fx+5); //reader->AddVariable("len", &flen); TFile * f1 = TFile::Open("../prepare_data/fake_data_test/jpverb.root"); TFile * f2 = TFile::Open("../prepare_data/real_data/jpverb.root"); TTree * t1a = (TTree *)f1->Get("type1_alt"); TTree * t1b = (TTree *)f1->Get("type2_alt"); TTree * t2a = (TTree *)f2->Get("type1_alt"); TTree * t2b = (TTree *)f2->Get("type2_alt"); int x[6], len; t1a->SetBranchAddress("x", x); t1a->SetBranchAddress("len", &len); t1b->SetBranchAddress("x", x); t1b->SetBranchAddress("len", &len); t2a->SetBranchAddress("x", x); t2a->SetBranchAddress("len", &len); t2b->SetBranchAddress("x", x); t2b->SetBranchAddress("len", &len); TString dir = "dataset/weights/"; TString prefix = "TMVAClassification"; // Book method(s) vector<TString> methods {"Likelihood", "KNN", "MLP", "MLP_L2Reg", "DNN_ReLU", "DNN_ReLU_mlp", "BDT", "BDTG"}; for (auto method: methods) { TString weightfile = Form("dataset/weights/jpvc_%s.weights.xml", method.Data()); reader->BookMVA(method, weightfile); } map<TString, double> cut_sig; map<TString, double> cut_tot; map<TString, double> cut_sqr; ifstream ifs("cuts.dat"); TString method; double c; while (ifs >> method) { ifs >> c; cut_sig[method] = c; ifs >> c; cut_tot[method] = c; ifs >> c; cut_sqr[method] = c; } map<TString, float> score_test, score_real, score_diff; for (auto method: methods) { int count1a[3] = {0, 0, 0}; int count1b[3] = {0, 0, 0}; int count2a[3] = {0, 0, 0}; int count2b[3] = {0, 0, 0}; for (int i = 0; i < t1a->GetEntries(); ++i) { t1a->GetEntry(i); copy_vals(fx, flen, x, len); double response = reader->EvaluateMVA(method); if (response > cut_sig[method]) ++count1a[0]; if (response > cut_tot[method]) ++count1a[1]; if (response > cut_sqr[method]) ++count1a[2]; } for (int i = 0; i < t1b->GetEntries(); ++i) { t1b->GetEntry(i); copy_vals(fx, flen, x, len); double response = reader->EvaluateMVA(method); if (response < cut_sig[method]) ++count1b[0]; if (response < cut_tot[method]) ++count1b[1]; if (response < cut_sqr[method]) ++count1b[2]; } for (int i = 0; i < t2a->GetEntries(); ++i) { t2a->GetEntry(i); copy_vals(fx, flen, x, len); double response = reader->EvaluateMVA(method); if (response > cut_sig[method]) ++count2a[0]; if (response > cut_tot[method]) ++count2a[1]; if (response > cut_sqr[method]) ++count2a[2]; } for (int i = 0; i < t2b->GetEntries(); ++i) { t2b->GetEntry(i); copy_vals(fx, flen, x, len); double response = reader->EvaluateMVA(method); if (response < cut_sig[method]) ++count2b[0]; if (response < cut_tot[method]) ++count2b[1]; if (response < cut_sqr[method]) ++count2b[2]; } const char * format_a = " type1@fake sample: %12d(%5.1f)%12d(%5.1f)%12d(%5.1f) (%8lld in total)"; const char * format_b = " type2@fake sample: %12d(%5.1f)%12d(%5.1f)%12d(%5.1f) (%8lld in total)"; cout << Form("%9s cut at %12f%12f%12f", method.Data(), cut_sig[method], cut_tot[method], cut_sqr[method]) << endl; int n[4]; float r[3]; int nc1, nt1; float ws1; int nc2, nt2; float ws2; get_numbers(count1a, t1a, n, r); cout << Form(format_a, n[0], r[0], n[1], r[1], n[2], r[2], n[3]) << endl; nc1 = n[1]; nt1 = n[3]; get_numbers(count1b, t1b, n, r); cout << Form(format_b, n[0], r[0], n[1], r[1], n[2], r[2], n[3]) << endl; nc1 += n[1]; nt1 += n[3]; ws1 = 1.0*nc1/nt1; cout << " average score: " << 100*ws1 << endl; get_numbers(count2a, t2a, n, r); cout << Form(format_a, n[0], r[0], n[1], r[1], n[2], r[2], n[3]) << endl; nc2 = n[1]; nt2 = n[3]; get_numbers(count2b, t2b, n, r); cout << Form(format_b, n[0], r[0], n[1], r[1], n[2], r[2], n[3]) << endl; nc2 += n[1]; nt2 += n[3]; ws2 = 1.0*nc2/nt2; cout << " average score: " << 100*ws2 << endl; cout << " score down by: " << 100*(ws1-ws2) << endl; score_test[method] = ws1; score_real[method] = ws2; score_diff[method] = ws1 - ws2; cout << endl; } ofstream ofs("score.dat"); for (auto method: methods) { ofs << method << " " << score_test[method] << " " << score_real[method] << " " << score_diff[method] << endl; } } //int main( int argc, char** argv ) //{ //}
[ "mintianjue@gmail.com" ]
mintianjue@gmail.com
c520443f6cb1044ce9ccd95a60fc0bcbe09f8551
fa04923b39bcf3db63e82b37aa6d35fd742d8975
/Core/src/channel/write_pipe.cpp
8f2c67a1c5f87d3d01bea7ab57eb0d5ad43a8563
[]
no_license
nonametr/mls
47da669d523f379a13ad48c5f10d5815ad65ee10
f8ff04a55d49d9ce553d19f12f760402023b22a9
refs/heads/master
2021-01-19T00:16:34.640453
2013-11-01T13:42:53
2013-11-01T13:42:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,827
cpp
#include "write_pipe.h" #include "runtime.h" void WritePipe::setup_pipe() { // Create a pipe to send data _pipe = CreateNamedPipeA( _pipe_name.c_str(), // name of the pipe PIPE_ACCESS_OUTBOUND, // 1-way pipe -- send only PIPE_TYPE_BYTE | PIPE_WAIT, // send data as a byte stream 1, // only allow 1 instance of this pipe 0, // no outbound buffer 0, // no inbound buffer 10, // use default wait time NULL // use default security attributes ); if (_pipe == NULL || _pipe == INVALID_HANDLE_VALUE) { traceerr("Failed to create outbound pipe instance."); return; } bool result = ConnectNamedPipe(_pipe, NULL); if (!result) { traceerr( "Failed to make connection on named pipe."); CloseHandle(_pipe); // close the pipe return; } running = true; } void WritePipe::stop() { running = false; QThread::terminate(); } void WritePipe::run() { DWORD numBytesWritten = 0; setup_pipe(); while(running) { if(data_ptr == NULL) { continue; } // This call blocks until a client process reads all the data //rdtscll(r_start); bool result = WriteFile( _pipe, // handle to our outbound pipe data_ptr, // data to send data_len, // length of data to send (bytes) &numBytesWritten, // will store actual amount of data sent NULL // not using overlapped IO ); //rdtscll(r_end); Sleep(39); //data_ptr = NULL; if (!result) { CloseHandle(_pipe); if(running) { traceerr("Error! FFMPEG connection lost!"); running = false; setup_pipe(); } } } } bool WritePipe::send(char *p_data, unsigned int len) { data_ptr = p_data; data_len = len; return running; } WritePipe::WritePipe(string name) : running(false), data_ptr(NULL), data_len(0), _pipe(NULL) { _pipe_name = "\\\\.\\pipe\\" + name; } WritePipe::~WritePipe() { CloseHandle(_pipe); }
[ "ikuruch@gmail.com" ]
ikuruch@gmail.com
d060d4e69a1fe410149ef89229b95dac59014043
764f7c7a30ce9006a7aa3d0071ffd602c7ecaeda
/lsdtt_xtensor/include/liblas/error.hpp
0e3ef0c32a1fe76132d254e4953e89f5eb5fe582
[ "GPL-3.0-only", "MIT" ]
permissive
LSDtopotools/lsdtopytools
be40906a5bc757b86a54fc479cd3f784e9c6b91b
b2854003c7da1507cff80e45fe096b13c96c324c
refs/heads/master
2023-01-14T16:45:13.007778
2022-12-26T21:12:00
2022-12-26T21:12:00
235,968,220
4
1
MIT
2022-12-26T21:12:01
2020-01-24T08:50:59
C++
UTF-8
C++
false
false
3,467
hpp
/****************************************************************************** * $Id$ * * Project: libLAS - http://liblas.org - A BSD library for LAS format data. * Purpose: An error encapsulation class * Author: Mateusz Loskot, mateusz@loskot.net * ****************************************************************************** * Copyright (c) 2008, Mateusz Loskot * Copyright (c) 2008, Howard Butler * Copyright (c) 2008, Phil Vachon * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following * conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided * with the distribution. * * Neither the name of the Martin Isenburg or Iowa Department * of Natural Resources nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. ****************************************************************************/ #ifndef LIBLAS_LASERROR_HPP_INCLUDED #define LIBLAS_LASERROR_HPP_INCLUDED #include <liblas/export.hpp> //std #include <iosfwd> #include <string> namespace liblas { /// Definition of error notification used on the level of C API. /// This class describes details of error condition occured in /// libLAS core. All errors are stacked by C API layer, so it's /// possible to track problem down to its source. class LAS_DLL Error { public: /// Custom constructor. /// This is the main and the only tool to initialize error instance. Error(int code, std::string const& message, std::string const& method); /// Copy constructor. /// Error objects are copyable. Error(Error const& other); /// Assignment operator. /// Error objects are assignable. Error& operator=(Error const& rhs); // TODO - mloskot: What about replacing string return by copy with const char* ? // char const* GetMethod() const { return m_method.c_str(); }, etc. int GetCode() const { return m_code; } std::string GetMessage() const { return m_message; } std::string GetMethod() const { return m_method; } private: int m_code; std::string m_message; std::string m_method; }; } // namespace liblas #endif // LIBLAS_LASERROR_HPP_INCLUDED
[ "boris.gailleton@gfz-potsdam.de" ]
boris.gailleton@gfz-potsdam.de
04f9302b01f34b44ad37ae946ebd0046c2356c40
187073f42b26007f72076cba8a312cb4694b5438
/C_C++/season4/p019/play.cpp
9f27915a67b2e46acbf0be5ed24bf0a41fb4a8de
[]
no_license
GandT/learning
bccd3d322873f89e8ca9b0c0c2d188f88ea2e3fa
acf9c9ac20fe9b74553053042289ffc835eb3201
refs/heads/master
2023-01-22T17:43:26.737643
2022-09-12T09:18:50
2022-09-12T09:18:50
59,556,177
0
1
null
2023-01-19T04:48:22
2016-05-24T08:45:18
Ruby
UTF-8
C++
false
false
1,822
cpp
#include "play.h" //必要ライブラリ #include <opencv2/opencv.hpp> #include <GL/glut.h> //必要処理 #include "system.h" #include "camera.h" #include "picture.h" using namespace cv; //ゲーム画面キー入力処理 void GamePlayKey(unsigned char k, int x, int y) { switch(k){ //タイトルに戻る case '\033': //ESC gamestate = GAME_TITLE; break; } } //ゲーム画面マウスクリック処理 void GamePlayMouseClick(int b, int s, int x, int y) { } //ゲーム画面マウス移動処理 void GamePlayMouseMove(int x, int y) { } //ゲーム画面フレーム処理 void GamePlayFrame() { //フレームカウント ++frame; //ディスプレイの変化を通達 glutPostRedisplay(); } //ゲーム画面ディスプレイ処理 void GamePlayDisplay() { /*【注意】※※※各種変換はスタックに積まれるため実際の処理順序は記述の逆順※※※【注意】*/ /***ビューポート変換***/ //なし /***投影変換***/ glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(30, //カメラの画角 0.75, //アスペクト比 0.1, //最近奥行き 500); //最遠奥行き /***モデルビュー変換***/ glMatrixMode(GL_MODELVIEW); glLoadIdentity(); //カメラ視点移動 //gluLookAt(); //バッファの初期化 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //2D描画 //デプスバッファ機能の有効化 glEnable(GL_DEPTH_TEST); //3D描画 //デプスバッファ無効化 glDisable(GL_DEPTH_TEST); //2D描画 //画面反映 glFlush(); //裏画面を表画面に描画 glutSwapBuffers(); }
[ "GandT@users.noreplygithub.com" ]
GandT@users.noreplygithub.com
61e53c8dbd6d3fdd7b19e3754a67235f38f1f15b
89b233f71ef27d935749a0992025eb3a795b26fa
/C++/2021/2ndOct_SiddharthJadhav99.cpp
705505d56292ef11ffef734fb81c133cf72a7ff0
[]
no_license
Priyanshuparihar/make-pull-request
1dd780fcabedee2bced1f90661c91c7b3bfa637d
d7096a63558268020ffa0ea8e04015e4496ad3a1
refs/heads/master
2023-09-01T02:32:17.541752
2021-10-11T03:42:13
2021-10-11T03:42:13
415,766,845
1
0
null
null
null
null
UTF-8
C++
false
false
1,228
cpp
#include <iostream> int main() { int r, c, i, j, k, digits; std::cout << "Enter the number of rows followed by the number of columns" << std::endl; std::cin >> r >> c; int pos[c]; // array to store which row is supposed to print the column number for each column for (i = 0; i < c; i++) { if (i / (r - 1) % 2 == 0) // processes the position for the downward slope { pos[i] = i % (r - 1); } else // processes the position for the upward slope { pos[i] = r - 1 - (i % (r - 1)); } } std::cout << "\n-------ZIGZAG PATTERN-------\n\n"; for (i = 0; i < r; i++) { for (j = 0; j < c; j++) { if (pos[j] == i) // if ith row is supposed to print out the column number for jth column, we print it { std::cout << (j + 1); } else { for (k = j + 1; k != 0; k /= 10) // if we're not printing out the column number, we print out the appropriate amount of spaces { std::cout << " "; } } std::cout << " "; } std::cout << "\n"; } }
[ "jadhavsid99@gmail.com" ]
jadhavsid99@gmail.com
4e63db8db04345be93d494ddfd02d32a47a8abee
0187dcbbb838b5c614953a969b9a51eab2142496
/GLEngine/src/GLEngine.h
1b6cf92259d3127eb74d347122e6c9929284b199
[ "MIT" ]
permissive
Cobralion/GLEngine
51e27065809b6a8c3774dbc6be6b9e8a2afebcb1
c265f6d372c05d1a903365ce42082b99b98f8c86
refs/heads/main
2023-04-09T08:42:22.717077
2021-04-05T16:16:22
2021-04-05T16:16:22
352,317,127
0
0
null
null
null
null
UTF-8
C++
false
false
942
h
#pragma once #include "Core.h" #include "Rendering/Renderer.h" #include "Rendering/Window.h" #include "Rendering/WindowManager.h" #include "Tools/Timer.h" namespace gle { namespace Rendering { class WindowManager; } class GLENGINE_API GLEngine { private: bool m_closeWindow = false; Rendering::Window* m_window; Rendering::Renderer* m_renderer; Rendering::WindowManager* m_windowManager; Tools::Timer m_timer; protected: GLEngine(); virtual ~GLEngine(); virtual void Update(float deltaTime) = 0; virtual void Draw(const Rendering::Renderer* renderer) = 0; virtual void WindowUpdate(const Rendering::WindowManager* manager) = 0; GLEngine(const GLEngine& other) = delete; GLEngine(GLEngine&& other) noexcept = delete; GLEngine& operator=(const GLEngine& other) = delete; GLEngine& operator=(GLEngine&& other) noexcept = delete; public: void Run(); }; }
[ "lindner.maurice@freenet.de" ]
lindner.maurice@freenet.de
15efc1684dcbb1a8bba5db1bd1996ccdf8fa4cdd
091dc0ac8cd98d704ff40654051c8e0c146e3b0b
/1113_119구급대.cpp
d72882398324e176751b112fbc40ba85831ee30f
[]
no_license
jangsohee/Algorithm
e2ff80fe49c8acd566c221e857b264df8948dffd
e57eebafc9169e7c0493b666a16b94da3e1f788e
refs/heads/master
2020-06-28T20:37:25.264200
2016-11-22T13:21:46
2016-11-22T13:21:46
74,246,997
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
1,693
cpp
#include <iostream> #include <cstring> #include <queue> using namespace std; int row, col; int map[200][200]; int res[200][200]; int direct[200][200]; int dir[4][2] = { { -1, 0 }, { 0, -1 }, { 1, 0 }, { 0, 1 }}; //»ó ÁÂ ÇÏ ¿ì int gRow, gCol; queue<pair<int, int> > que; void bfs(int r, int c) { res[r][c] = 0; for (int i = 2; i < 4; i++) { int tR = r + dir[i][0]; int tC = c + dir[i][1]; if (tR < 0 || tC < 0 || tR >= row || tC >= col) continue; if (map[tR][tC] == 0) continue; res[tR][tC] = 0; direct[tR][tC] = i; que.push(make_pair(tR, tC)); } while (!que.empty()) { int nowR = que.front().first; int nowC = que.front().second; int nowStep = res[nowR][nowC]; int nowD = direct[nowR][nowC]; que.pop(); if (nowR == gRow && nowC == gCol) { cout << res[nowR][nowC] << endl; return; } for (int i = 0; i < 4; i++) { int nextR = nowR + dir[i][0]; int nextC = nowC + dir[i][1]; int nextStep = nowStep + 1; if (nextR < 0 || nextC < 0 || nextR >= row || nextC >= col) continue; if (map[nextR][nextC] == 0) continue; if (i != nowD) { if (res[nextR][nextC] != -1 && res[nextR][nextC] <= nextStep) continue; que.push(make_pair(nextR, nextC)); res[nextR][nextC] = nextStep; } else { if (res[nextR][nextC] != -1 && res[nextR][nextC] <= nowStep) continue; que.push(make_pair(nextR, nextC)); res[nextR][nextC] = nowStep; } direct[nextR][nextC] = i; } } } int main() { cin >> col >> row; cin >> gRow >> gCol; for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { scanf("%d", &map[i][j]); } } memset(res, -1, sizeof(res)); bfs(0, 0); return 0; }
[ "jsh41817@naver.com" ]
jsh41817@naver.com
a70f74f63f7106ce32271ae7ede2e55e7ca68c09
8fd605662fd2daa65ccbdeb0c7614b541ea2ee6f
/Data Structures/Stack/Stack (using LinkedList)/Stack-using-LinkedList/LLStack.cpp
ad0774e094b10358369a42419037cefc193a622f
[ "MIT" ]
permissive
benymaxparsa/Algorithms-and-Data-Structures
bfee5558b9922bc86499b28141c0584e005c0e31
87324a071c22ac9cbc9d205baca85d64e2e4a514
refs/heads/master
2021-02-13T12:46:55.885711
2020-11-16T09:28:21
2020-11-16T09:28:21
244,697,691
2
0
null
null
null
null
UTF-8
C++
false
false
831
cpp
#include "LLStack.h" LLStack::LLStack() { size = 0; root = NULL; } LLStack::~LLStack() { } StackNode* LLStack::lastData() { StackNode* p = root; while (p->next) { p = p->next; } return p; } void LLStack::push(int data) { StackNode* node = new StackNode(data); size++; if (!root) { root = node; return; } else { lastData()->next = node; return; } } int LLStack::pop() { if (!root) return 0; else { StackNode* p = lastData(); int data =p->data; size--; p = NULL; if (size == 0) root = NULL; return data; } } int LLStack::top() { if (!root) return 0; else { StackNode* p = root; while (p->next) { p = p->next; } return p->data; } } bool LLStack::isEmpty() { if (!root && size == 0) return true; else return false; } int LLStack::Size() { return size; }
[ "parsakamalipour@gmail.com" ]
parsakamalipour@gmail.com
0fa55f35c029e694544c4cb535fae83c1f12b572
600df3590cce1fe49b9a96e9ca5b5242884a2a70
/media/base/android/media_codec_util.h
09e5ac84d1de63908e321f4a74bd4191aac6deed
[ "BSD-3-Clause" ]
permissive
metux/chromium-suckless
efd087ba4f4070a6caac5bfbfb0f7a4e2f3c438a
72a05af97787001756bae2511b7985e61498c965
refs/heads/orig
2022-12-04T23:53:58.681218
2017-04-30T10:59:06
2017-04-30T23:35:58
89,884,931
5
3
BSD-3-Clause
2022-11-23T20:52:53
2017-05-01T00:09:08
null
UTF-8
C++
false
false
3,634
h
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef MEDIA_BASE_ANDROID_MEDIA_CODEC_UTIL_H_ #define MEDIA_BASE_ANDROID_MEDIA_CODEC_UTIL_H_ #include <jni.h> #include <set> #include <string> #include <vector> #include "base/compiler_specific.h" #include "base/macros.h" #include "media/base/android/media_codec_direction.h" #include "media/base/media_export.h" class GURL; namespace media { class MediaCodecBridge; // Helper macro to skip the test if MediaCodecBridge isn't available. #define SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE() \ do { \ if (!MediaCodecUtil::IsMediaCodecAvailable()) { \ VLOG(0) << "Could not run test - not supported on device."; \ return; \ } \ } while (0) // Helper macro to skip the test if VP8 decoding isn't supported. #define SKIP_TEST_IF_VP8_DECODER_IS_NOT_SUPPORTED() \ do { \ if (!MediaCodecUtil::IsVp8DecoderAvailable()) { \ VLOG(0) << "Could not run test - not supported on device."; \ return; \ } \ } while (0) class MEDIA_EXPORT MediaCodecUtil { public: // Returns true if MediaCodec is available on the device. // All other static methods check IsAvailable() internally. There's no need // to check IsAvailable() explicitly before calling them. static bool IsMediaCodecAvailable(); // Returns true if MediaCodec.setParameters() is available on the device. static bool SupportsSetParameters(); // Returns whether MediaCodecBridge has a decoder that |is_secure| and can // decode |codec| type. static bool CanDecode(const std::string& codec, bool is_secure); // Get a list of encoder supported color formats for |mime_type|. // The mapping of color format name and its value refers to // MediaCodecInfo.CodecCapabilities. static std::set<int> GetEncoderColorFormats(const std::string& mime_type); // Returns true if |mime_type| is known to be unaccelerated (i.e. backed by a // software codec instead of a hardware one). static bool IsKnownUnaccelerated(const std::string& mime_type, MediaCodecDirection direction); // Test whether a URL contains "m3u8". (Using exactly the same logic as // NuPlayer does to determine if a stream is HLS.) static bool IsHLSURL(const GURL& url); // Test whether the path of a URL ends with ".m3u8". static bool IsHLSPath(const GURL& url); // Indicates if the vp8 decoder or encoder is available on this device. static bool IsVp8DecoderAvailable(); static bool IsVp8EncoderAvailable(); // Indicates if the vp9 decoder is available on this device. static bool IsVp9DecoderAvailable(); // Indicates if SurfaceView and MediaCodec work well together on this device. static bool IsSurfaceViewOutputSupported(); // Indicates if the decoder is known to fail when flushed. (b/8125974, // b/8347958) // When true, the client should work around the issue by releasing the // decoder and instantiating a new one rather than flushing the current one. static bool CodecNeedsFlushWorkaround(MediaCodecBridge* codec); }; } // namespace media #endif // MEDIA_BASE_ANDROID_MEDIA_CODEC_UTIL_H_
[ "enrico.weigelt@gr13.net" ]
enrico.weigelt@gr13.net
4d5ac9e2aa971f02593301fcee430dac0994689b
691c2349b43b782747b65d98c00a1d7be4a751e3
/Implement_strStrII.cpp
f9bcf3352a816b2559cfc7e4ac160d68e3dc91c9
[]
no_license
LiliMeng/Leetcode
a37bd7117dc6d772419c0a3091c81235b844c47a
6023fa43e448423b93fd257f90fe70bba13c70fb
refs/heads/master
2021-06-08T08:55:40.206452
2020-05-25T06:06:36
2020-05-25T06:06:36
34,866,993
2
2
null
null
null
null
UTF-8
C++
false
false
739
cpp
//这个是普通的算法, leetcode通不过. 学神说kmp算法很快,对于网页上的aaabbbb这种很快. 但对于实际问题并不快 #include<string> #include<vector> #include<iostream> using namespace std; class Solution { public: int strStr(string haystack, string needle) { for(int i=0; i<haystack.size(); i++) { int j=0; int k=i; for( ; j<needle.size()&&k<haystack.size(); j++,k++) { if(haystack[k]!=needle[j]) { break; } } if(j==needle.size()) { return i; } } return -1; } }; int main() { Solution s; cout<<s.strStr("Summer","mer")<<endl; }
[ "lilimeng1103@gmail.com" ]
lilimeng1103@gmail.com
873dc0233f07aebd7f4576c2e04fb96de86e18ff
d2add169afaff80fd1f2fcd79179d3cd63ad597b
/public_html/asset/submission_files/bb2e496ee53cb97a93d9a7ee3597d9e4.cpp
aae7b06af2cd08dedc89329a70e2a65fe4632b2b
[ "MIT" ]
permissive
zyxave/baba
60e3063cdb2fcf37943ad4e20c718f460ef965d5
7287a1b421a3503657986e0a13c9c4a02615dea5
refs/heads/master
2020-03-20T05:52:01.062398
2018-06-13T14:47:15
2018-06-13T14:47:15
136,165,542
0
0
null
null
null
null
UTF-8
C++
false
false
739
cpp
#include<bits/stdc++.h> #define ll long long #define pb push_back #define mp make_pair #define fi first #define se second using namespace std; ll t,d[2020202],b[2020202],u,tee,n; queue<ll> q; string s; ll st(string aa) { stringstream ss; ll ee; ss<<aa; ss>>ee; return ee; } string ts(ll aa) { stringstream ss; string ee; ss<<aa; ss>>ee; return ee; } int main() { cin>>t; q.push(0); d[0]=0; b[0]=1; while(!q.empty()) { u=q.front(); q.pop(); s=ts(u); reverse(s.begin(),s.end()); tee=st(s); if(u+1<=2000000&&b[u+1]==0) { b[u+1]=1; d[u+1]=d[u]+1; q.push(u+1); } if(tee<=2000000&&b[tee]==0) { b[tee]=1; d[tee]=d[u]+1; q.push(tee); } } while(t--) { cin>>n; cout<<d[n]<<"\n"; } }
[ "puncomakr@gmail.com" ]
puncomakr@gmail.com
d3aa29305d0bed6758314362bdc5c4e18bd7c8bf
b146b54363a20726b3e1dc0ef0fadc82051234f9
/tests/blocks/MinMaxIdxBlock_test.cpp
8edbbf7bc295237f5699397698b00704e5d41101
[ "BSD-3-Clause" ]
permissive
helkebir/Lodestar
90a795bbbd7e496313c54e34f68f3527134b88ce
465eef7fe3994339f29d8976a321715441e28c84
refs/heads/master
2022-03-12T23:16:03.981989
2022-03-03T05:08:42
2022-03-03T05:08:42
361,901,401
4
1
null
null
null
null
UTF-8
C++
false
false
865
cpp
// // Created by Hamza El-Kebir on 2/19/22. // #include "catchOnce.hpp" #include <Lodestar/blocks/std/MinMaxIdxBlock.hpp> #include <Eigen/Dense> TEST_CASE("MinMaxIdxBlock", "[blocks][std]") { Eigen::Matrix3d M; M << 1, 2, -3, 4, 15, -6, 5, 4, -5; ls::blocks::std::MinMaxIdxBlock<decltype(M), ls::blocks::std::MinMaxIdxBlockOperator::Min> minBlock; ls::blocks::std::MinMaxIdxBlock<decltype(M), ls::blocks::std::MinMaxIdxBlockOperator::Max> maxBlock; minBlock.i<0>() = M; maxBlock.i<0>() = M; minBlock.trigger(); maxBlock.trigger(); REQUIRE(minBlock.o<0>().object == 1); REQUIRE(minBlock.o<1>().object == 2); REQUIRE(minBlock.o<2>().object == Approx(-6)); REQUIRE(maxBlock.o<0>().object == 1); REQUIRE(maxBlock.o<1>().object == 1); REQUIRE(maxBlock.o<2>().object == Approx(15)); }
[ "ha.elkebir@gmail.com" ]
ha.elkebir@gmail.com
4dbe924826762c42f5dcf8e4dac6aa5fd1fbcd5f
4ae0d8be44a7e4bf774b6eb08acca79de3d9937e
/homework_19_20/╫ў╥╡20-ICP╙ж╙├╩╡╝∙-┤·┬ы┐Є╝▄/icp.cpp
4478d20d6682c2863109647cf0bec9567a4c2aad
[]
no_license
Hustwireless/SLAM-Learning
65b0ee1e6057cffd52a4a0dd1b9ee266f265e2ed
ab534ab513ce3d6b0d6cabf0ccbd8f657fbaa2d1
refs/heads/master
2020-12-11T00:15:28.089709
2019-08-30T12:10:23
2019-08-30T12:10:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,570
cpp
/**************************** * 题目:给定一个轨迹1,数据格式:timestamp tx ty tz qx qy qz qw * 自定义一个任意的旋转矩阵和平移向量(可以尝试不同的值看看结果有什么变化),对轨迹1进行变换,得到一个新的轨迹2 * 使用ICP算法(提示:取平移作为三维空间点)估计轨迹1,2之间的位姿,然后将该位姿作用在轨迹2 * 验证:ICP算法估计的旋转矩阵和平移向量是否准确;轨迹1,2是否重合 * * 本程序学习目标: * 熟悉ICP算法的原理及应用。 * * 公众号:计算机视觉life。发布于公众号旗下知识星球:从零开始学习SLAM,参考答案请到星球内查看。 * 时间:2019.05 * 作者:小六 ****************************/ #include <iostream> #include "sophus/se3.h" #include <fstream> #include <pangolin/pangolin.h> #include <opencv2/core/core.hpp> #include <opencv2/calib3d/calib3d.hpp> #include <Eigen/Core> #include <Eigen/Geometry> #include <Eigen/SVD> using namespace std; using namespace cv; void DrawTrajectory(vector<Sophus::SE3, Eigen::aligned_allocator<Sophus::SE3>> pose1, vector<Sophus::SE3, Eigen::aligned_allocator<Sophus::SE3>> pose2); int main() { // path to trajectory file string trajectory_file = "./trajectory.txt"; //string trajectory_file = "./new.txt"; vector<Sophus::SE3, Eigen::aligned_allocator<Sophus::SE3>> pose_groundtruth; vector<Sophus::SE3, Eigen::aligned_allocator<Sophus::SE3>> pose_new; vector<Sophus::SE3, Eigen::aligned_allocator<Sophus::SE3>> pose_estimate; vector<Point3f> pts_new, pts_groundtruth; //Eigen::Quaterniond q; // Eigen::Vector3d t; //Sophus::SE3 T; //string timestamp; ifstream textFile; // 自定义一个变换矩阵 /********************** 开始你的代码,参考星球里作业5代码 ****************************/ // 旋转向量(轴角):沿Z轴旋转45° Eigen::AngleAxisd rotation_vector(M_PI/4,Eigen::Vector3d(0,0,1)); Eigen::Matrix3d rotate=Eigen::Matrix3d::Identity(); rotate=rotation_vector.toRotationMatrix(); Eigen::Vector3d tranlation=Eigen::Vector3d(3,-1,0.8); //Eigen::Isometry3d T=Eigen::Isometry3d::Identity();//虽然是3d,实际上是4×4 //T.rotate(rotation_vector); //T.Pretranslate(Eigen::Vector3d(3,-1,0.8)); // 平移向量,可以自己自定义,我这里是 x=3, y=-1, z=0.8,可以多尝试其他值 /********************** 结束你的代码 ****************************/ Sophus::SE3 myTransform(rotate,tranlation); //Sophus::SE3 myTransform(rotate,tranlation); cout<<"rotation matrix =\n"<<rotation_vector.matrix() <<endl; cout<<"translation vector =\n"<<tranlation <<endl; cout<<"myTransform =\n"<<myTransform.matrix() <<endl; textFile.open(trajectory_file.c_str()); // 读取轨迹数据 /********************** 开始你的代码,参考星球里作业8代码 ****************************/ // 提示:取平移作为三维空间点 if (!textFile.is_open()){ cout << "file is empty!" <<endl; return -1; } string line; double timestamp,tx, ty, tz, qx, qy, qz, qw; while( getline(textFile,line) ){ stringstream lineStream(line); lineStream>>timestamp>>tx>>ty>>tz>>qx>>qy>>qz>>qw; //if (timestamp == "#"){ // cout << "WARN: INF ERROR" << endl; // continue; //} Eigen::Vector3d t(tx,ty,tz); Eigen::Quaterniond q = Eigen::Quaterniond(qw,qx,qy,qz).normalized();//一定要归一化 Sophus::SE3 T(q,t); //pts_new[0]=tx; // pts_new[1]=ty; // pts_new[2]=tz;//错误 // pts_new[0]=Point3f(tx,ty,tz);//错误 //pts_groundtruth=t;//取平移作为三维空间点 // pts_groundtruth[0]=Point3f(tx,ty,tz); pose_groundtruth.push_back(T); pts_groundtruth.push_back(cv::Point3f(tx,ty,tz)); //pose_new.push_back(T); // pts_new.push_back(cv::Point3f(tx,ty,tz)); // T = Sophus::SE3(q, t); //pose_groundtruth.push_back(T); //pose // pts_groundtruth.push_back(Point3f(t[0], t[1], t[2])); // points //////////////////////// Sophus::SE3 Tmp(myTransform * T); pose_new.push_back(Tmp); //new pose pts_new.push_back(Point3f(Tmp.translation()[0], Tmp.translation()[1], Tmp.translation()[2])); // new points } /********************** 结束你的代码 ****************************/ textFile.close(); // 使用ICP算法估计轨迹1,2之间的位姿,然后将该位姿作用在轨迹2 /********************** 开始你的代码,参考十四讲中第7章ICP代码 ****************************/ Point3f p1,p2;//质心 int N=pts_new.size(); for(int i=0;i<N;i++) { p1+=pts_new[i]; p2+= pts_groundtruth[i]; } p1/=N; p2/=N; vector<Point3f> q1(N),q2(N);//去质心 for(int i=0;i<N;i++) { q1[i]=pts_new[i]-p1; q2[i]=pts_groundtruth[i]-p2; } //计算 q1*q2^T Eigen::Matrix3d W=Eigen::Matrix3d::Zero(); for(int i=0;i<N;i++) { W+=Eigen::Vector3d(q1[i].x,q1[i].y,q1[i].z)*Eigen::Vector3d(q2[i].x,q2[i].y,q2[i].z).transpose(); } cout<<"W= "<<W<<endl; //SVD Eigen::JacobiSVD<Eigen::Matrix3d> svd(W,Eigen::ComputeFullU|Eigen::ComputeFullV); Eigen::Matrix3d U=svd.matrixU(); Eigen::Matrix3d V=svd.matrixV(); cout<<"U= "<<U<<endl; cout<<"V= "<<V<<endl; Eigen::Matrix3d R_=U*(V.transpose()); Eigen::Vector3d t_=Eigen::Vector3d(p1.x,p1.y,p1.z)-R_*Eigen::Vector3d(p2.x,p2.y,p2.z); // Sophus::SE3 T0(R_,t_); // pose_estimate.push_back(T0); ///////////////// //取逆 Eigen::Matrix3d Rot = R_.inverse(); Eigen::Vector3d tran = -Rot*t_; Sophus::SE3 T_estimate(Rot, tran); // pose_groundtruth = T_estimate* pose_new for(int i = 0; i< pose_new.size();i++) { pose_estimate.push_back(T_estimate * pose_new[i]); } /********************** 结束你的代码 ****************************/ // DrawTrajectory(pose_groundtruth, pose_new); // 变换前的两个轨迹 DrawTrajectory(pose_groundtruth, pose_estimate); // 轨迹应该是重合的 return 0; } void DrawTrajectory(vector<Sophus::SE3, Eigen::aligned_allocator<Sophus::SE3>> pose1, vector<Sophus::SE3, Eigen::aligned_allocator<Sophus::SE3>> pose2) { if (pose1.empty()||pose2.empty()) { cerr << "Trajectory is empty!" << endl; return; } // create pangolin window and plot the trajectory pangolin::CreateWindowAndBind("Trajectory Viewer", 1080, 720); glEnable(GL_DEPTH_TEST); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); pangolin::OpenGlRenderState s_cam( pangolin::ProjectionMatrix(1024, 768, 500, 500, 512, 389, 0.1, 1000), pangolin::ModelViewLookAt(0, -0.1, -1.8, 0, 0, 0, 0.0, -1.0, 0.0) ); pangolin::View &d_cam = pangolin::CreateDisplay() .SetBounds(0.0, 1.0, pangolin::Attach::Pix(175), 1.0, -1024.0f / 768.0f) .SetHandler(new pangolin::Handler3D(s_cam)); while (pangolin::ShouldQuit() == false) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); d_cam.Activate(s_cam); glClearColor(1.0f, 1.0f, 1.0f, 1.0f); glLineWidth(2); for (size_t i = 0; i < pose1.size() - 1; i++) { //glColor3f(1 - (float) i / pose1.size(), 1.0f, (float) i / pose1.size()); glColor3f(1.0, 0.0, 0.0); glBegin(GL_LINES); auto p1 = pose1[i], p2 = pose1[i + 1]; glVertex3d(p1.translation()[0], p1.translation()[1], p1.translation()[2]); glVertex3d(p2.translation()[0], p2.translation()[1], p2.translation()[2]); glEnd(); } for (size_t i = 0; i < pose2.size() - 1; i++) { //glColor3f(1 - (float) i / pose2.size(), 1.0f, (float) i / pose2.size()); glColor3f(0,0,1); glBegin(GL_LINES); auto p1 = pose2[i], p2 = pose2[i + 1]; glVertex3d(p1.translation()[0], p1.translation()[1], p1.translation()[2]); glVertex3d(p2.translation()[0], p2.translation()[1], p2.translation()[2]); glEnd(); } pangolin::FinishFrame(); usleep(5000); // sleep 5 ms } }
[ "lyy3690@126.com" ]
lyy3690@126.com
f5bd124dd828ff0578d778c74912d2e71875d1cf
ebedf37f3545e6af6b22cb0aa1f7c7ee1ef2f090
/orilocal/cmd_status.cc
d96479876e1993f5cba16ae7e868df49baef23b6
[ "ISC" ]
permissive
orifs/ori
dc1b0fe5e9f166ab64b647a11d51be9c589c20db
a6545618ba5f12bc7367f7744269197eb3124503
refs/heads/master
2021-01-16T18:00:51.687684
2019-11-08T23:42:59
2019-11-15T22:54:25
15,926,756
23
8
NOASSERTION
2019-10-08T23:39:42
2014-01-15T06:20:48
C++
UTF-8
C++
false
false
1,387
cc
/* * Copyright (c) 2012 Stanford University * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <stdint.h> #include <string> #include <iostream> #include <iomanip> #include <ori/localrepo.h> using namespace std; extern LocalRepo repository; int cmd_status(int argc, char * const argv[]) { Commit c; ObjectHash tip = repository.getHead(); if (tip != EMPTY_COMMIT) { c = repository.getCommit(tip); } TreeDiff td; td.diffToDir(c, repository.getRootPath(), &repository); for (size_t i = 0; i < td.entries.size(); i++) { printf("%c %s\n", td.entries[i].type, td.entries[i].filepath.c_str()); } return 0; }
[ "mashti@cs.stanford.edu" ]
mashti@cs.stanford.edu
7315c728bc6bae3d2ae729619b1e62ec4629cfaf
ef8df20641b85ed70d07602e13db5720499e2795
/棚外雨量版_WS100/STM32_LORA_WS100_V1.1.0_alpha/Private_Timer.cpp
d3329a1dadaf60e0f82c4a2a9f89603d36750559
[]
no_license
Arrogantyunya/LoRa_SensorV2.0
0a1538b96823176def1217f68530daf4cd8e5470
c6bf18a3919dd13dae26ac945f4eb5559e2b7a36
refs/heads/master
2020-09-20T22:44:37.708282
2020-07-21T10:27:08
2020-07-21T10:27:08
224,607,027
1
0
null
null
null
null
UTF-8
C++
false
false
1,907
cpp
#include "Private_Timer.h" // #include "fun_periph.h" #include "Security.h" #include <Arduino.h> /*Timer timing time*/ #define TIMER_NUM 1000000L * 1 //1S #define CHECK_TIMER_NUM 1000000L volatile static unsigned int gSelfCheckNum; /* @brief : 使用定时器2初始化卷膜行程计时参数 @param : 无 @return : 无 */ // void Roll_Timer_Init(void) // { // Timer2.setPeriod(TIMER_NUM); // in microseconds,1S // Timer2.attachCompare1Interrupt(Timer2_Interrupt); // Timer2.setCount(0); // Timer2.pause(); // } /* @brief : 使用定时器3初始化自检参数功能自检周期 @param : 无 @return : 无 */ void Self_Check_Parameter_Timer_Init(void) { Timer3.setPeriod(TIMER_NUM); // in microseconds,1S Timer3.attachCompare1Interrupt(Timer3_Interrupt); Timer3.setCount(0); } /* @brief : 开始卷膜计时 @param : 无 @return : 无 */ // void Start_Roll_Timing(void) // { // gRollingTime = 0; // gRollingTimeVarFlag = false; // Timer2.setCount(0); // Timer2.resume(); // } /* @brief : 开始自检周期计时 @param : 无 @return : 无 */ void Start_Self_Check_Timing(void) { Timer3.resume(); Timer3.setCount(0); } /* @brief : 停止卷膜计时 @param : 无 @return : 无 */ // void Stop_Roll_Timing(void) // { // Timer2.pause(); // } /* @brief : 停止自检周期计时 @param : 无 @return : 无 */ void Stop_Self_Check_Timing(void) { Timer3.pause(); } /* @brief : 卷膜计时定时器2计时中断处理函数 @param : 无 @return : 无 */ // void Timer2_Interrupt(void) // { // gRollingTime++; // gRollingTimeVarFlag = true; // } /* @brief : 自检计时定时器3计时中断处理函数 @param : 无 @return : 无 */ void Timer3_Interrupt(void) { gSelfCheckNum++; if (gSelfCheckNum >= 14400) //4 hours 14400 { gSelfCheckNum = 0; gCheckStoreParamFlag = true; } }
[ "liujiahiu@qq.com" ]
liujiahiu@qq.com
c33f0c4a6f7477ae23c5952b22774f3b85d2b8cf
04d62a4efee438eb08e3ac2e39e5e1e8db2bcea1
/Lab 10/Commercial.h
ce8c24098ebc22e3df4760f50ebe751d9b7aa287
[]
no_license
Sweetville/Property-Example
744a6570c2fb1a37aa7844a91e8fd3d40efba533
e80b208a22ee3411bbfa3798272cbd263cfc8ed8
refs/heads/master
2020-03-30T14:37:20.585800
2018-10-02T23:24:10
2018-10-02T23:24:10
151,327,150
0
0
null
null
null
null
UTF-8
C++
false
false
606
h
#include <iostream> #include <sstream> #include <vector> #include <string> #include <fstream> #include "Property.h" using namespace std; //--------------------------------------------------------------------------------------------------- //create the commercial class, inheriting from the property class class Commercial : public Property{ protected: bool discounted; double discount_rate; const double commercial_rental_rate = 0.012; const double commercial_norental_rate = 0.01; public: string toString(); Commercial(string, int, string, bool, double, bool, double); double calculate_taxes(); };
[ "mswainj@gmail.com" ]
mswainj@gmail.com
69f6de1e1a15638a364d26bbdef88d24c362054c
770731ee3e60f3119139b577951687daf62abe50
/main.cpp
5f1633297c05178bc9ec8103b880c268e6298047
[]
no_license
Daya-Jin/textrank
1c817430bb55bae851e02b810f03e458d1e07ae2
eb24fbe120421efeb7f6c89e304270392a6efb1a
refs/heads/main
2023-02-03T15:30:21.339571
2020-12-20T10:46:41
2020-12-20T10:46:41
323,045,080
0
0
null
null
null
null
UTF-8
C++
false
false
2,698
cpp
// 分词,仅留下需要的词 #include <iostream> #include <cstdlib> #include "src/text_utils.h" #include "Jieba.hpp" using namespace std; const char *const DICT_PATH = "../lib/cppjieba/dict/jieba.dict.utf8"; const char *const HMM_PATH = "../lib/cppjieba/dict/hmm_model.utf8"; const char *const USER_DICT_PATH = "../lib/cppjieba/dict/user.dict.utf8"; const char *const IDF_PATH = "../lib/cppjieba/dict/idf.utf8"; const char *const STOP_WORD_PATH = "../lib/cppjieba/dict/stop_words.utf8"; int main() { string input_file = "../data/news.u8"; int text_field = 1; string out_file = "../data/news.seg"; cppjieba::Jieba jieba(DICT_PATH, HMM_PATH, USER_DICT_PATH, IDF_PATH, STOP_WORD_PATH); ifstream fin(input_file.c_str()); if (!fin.is_open()) { cout << "Fail to open file: " << input_file << endl; return -1; } ofstream fout(out_file.c_str()); if (!fout.is_open()) { cout << "Fail to open file: " << out_file << endl; return -1; } string line; vector<pair<string, string> > res; vector<string> fields; const size_t char_len = 3; // utf-8 char const size_t least_word_len = char_len * 2; // two chars while (getline(fin, line)) { TextUtils::Split(line, "\t", fields); const string &text = fields[text_field]; // 正文 res.clear(); jieba.Tag(text, res); fout << line << '\t'; // 原文写回 bool start = true; for (size_t i = 0; i < res.size(); ++i) { const string &word = res[i].first; // word const string &pos = res[i].second; // 词性 if (!TextUtils::IsAscii(word) && word.size() < least_word_len) continue; if (TextUtils::IsAlphaNum(word) && word.size() < 3) continue; if (pos[0] == 'n' || //名词 pos == "t" || //时间词 pos == "s" || //处所词 pos == "f" || //方位词 pos == "v" || //动词 pos == "a" || //形容词 pos == "vn" || //名动词 pos == "an" || //名形词 pos == "eng" || //英文词 pos == "x") //未登录词 { if (start) { fout << res[i].first; start = false; } else fout << ' ' << res[i].first; } } fout << endl; } fin.close(); fout.close(); return 0; }
[ "goldenteeth.cn@gmail.com" ]
goldenteeth.cn@gmail.com
1a42c85213cf230091910d11f0e37c10fb2205e6
ef4d82ee297aaa73e4ccff1a9f53400a38851dab
/RectChange/RectChange/stdafx.cpp
d26abcceb9c6136343325b4c8489bf51258f873c
[]
no_license
yue-sheng/-
86f5d670e5e2e7c19272978a2d7b1e714c521871
a548bec9622825930a52b23415c854f45f5505e4
refs/heads/master
2021-04-16T09:57:01.392058
2020-07-06T13:08:57
2020-07-06T13:08:57
249,346,890
0
0
null
null
null
null
GB18030
C++
false
false
165
cpp
// stdafx.cpp : 只包括标准包含文件的源文件 // RectChange.pch 将作为预编译头 // stdafx.obj 将包含预编译类型信息 #include "stdafx.h"
[ "1487289990@qq.com" ]
1487289990@qq.com
0c46a6735c4a05623766a436dd61deb91a535e82
4f4a635342747f5d2489e0ff74bd7f2832e42a7d
/zadanie.cpp
9ab8130971ad0b50859844cffa14276803e43a0f
[]
no_license
ldkavanagh010/Container-Exercise
213caa07309537c391e870b3aad2a6f99bdd347d
3b2b0b4206c2b76c6b9f9fdb632267a5bf7be95a
refs/heads/master
2022-10-20T03:06:29.310401
2018-08-21T13:08:03
2018-08-21T13:08:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,542
cpp
#include <string> #include <vector> #include <map> #include <algorithm> #include <iostream> class Synchronizer { public: Synchronizer(int i); ~Synchronizer(); /* member functions */ void init_data(); void delete_data(); void sync_data(); void print_data(); /* Данные */ private: int size; std::vector<int> vec; std::map<int, int> map; std::vector<int>::iterator it_v; std::map<int, int>::iterator it_m; std::vector<std::pair<int, int> >::iterator it_rev_m; }; Synchronizer::Synchronizer(const int i) : size (i) {} Synchronizer::~Synchronizer(){ } void Synchronizer::init_data(){ srand(unsigned(time(0))); int num; // заполнить вектор for (int i = 0; i < Synchronizer::size; i++){ num = (rand() % 9) + 1; vec.push_back(num); } // заполнить мап for (int i = 0; i < Synchronizer::size; i++){ num = (rand() % 9) + 1; // ключ будет индекс элемента map.insert(std::make_pair(map.size(), num)); } } void Synchronizer::delete_data(){ int num_to_del; srand(unsigned(time(0))); if (Synchronizer::size < 15) { num_to_del = (rand() % Synchronizer::size) + 1; } else { num_to_del = (rand() % 15) + 1; } while (num_to_del > 1){ vec.erase(vec.begin()); map.erase(map.begin()); num_to_del--; } } void Synchronizer::sync_data(){ // создать новый вектор с парами, где каждая пара состоит из элементов помененных местами std::vector<std::pair<int, int> > reverse_map; for (it_m = Synchronizer::map.begin(); it_m != Synchronizer::map.end(); it_m++){ reverse_map.push_back(std::make_pair((*it_m).second, (*it_m).first)); } std::sort(vec.begin(), vec.end()); std::sort(reverse_map.begin(), reverse_map.end()); std::vector<int>::iterator new_it_v; it_rev_m = reverse_map.begin(); for (it_v = vec.begin(), new_it_v = vec.begin(); it_v != vec.end(); it_v = new_it_v){ // базовый вариант // больше нет элементов в мап if (it_rev_m == reverse_map.end()) { it_v = vec.erase(it_v); } // элементы одинаковые else if ((*it_v) == (*it_rev_m).first) { new_it_v++; it_rev_m++; } // элемент в вектор меньше всех в мап else if ((*it_v) < (*it_rev_m).first) { it_v = vec.erase(it_v); } // элемент в вектор больше всех в мап else { it_rev_m = reverse_map.erase(it_rev_m); } } // удалить все лишные элементы из конца сохраненных элементов мапа if (vec.size() < reverse_map.size()) { reverse_map.erase(reverse_map.begin() + vec.size(), reverse_map.end()); } map.clear(); // переписать нужные элементы в мап if (!reverse_map.empty()){ for (it_rev_m = reverse_map.begin(); it_rev_m != reverse_map.end(); it_rev_m++){ map.insert(std::make_pair((*it_rev_m).second, (*it_rev_m).first)); } } } void Synchronizer::print_data(){ for (it_v = Synchronizer::vec.begin(); it_v != Synchronizer::vec.end(); it_v++){ std::cout << (*it_v) << ' '; } std::cout << std::endl; for (it_m = Synchronizer::map.begin(); it_m != Synchronizer::map.end(); it_m++){ std::cout << (*it_m).second << ' '; } std::cout << std::endl; } int main(int argc, char** argv){ int i = std::stoi(argv[1]); Synchronizer sync = Synchronizer(i); sync.init_data(); sync.delete_data(); sync.sync_data(); }
[ "lkavanagh010@gmail.com" ]
lkavanagh010@gmail.com
24ba7616aec8ddc5e22d8eaf47004fc5611f36e4
0fd5d6e3ec7ff94ca30a2b4fd6e4b1fa23bf7cc9
/2dEngine/RenderList.cpp
48f8d019be94430b9ee1d30ea1cc801aa364bd73
[]
no_license
florianPat/2dEngine
65e274820f7a7fa15149ff8ea9005505994e2ec7
5f95243eed94034342703ab4e512f64f4c7eb8c0
refs/heads/master
2022-07-21T19:53:22.476877
2020-05-20T05:49:07
2020-05-20T05:49:07
116,250,493
0
0
null
null
null
null
UTF-8
C++
false
false
2,633
cpp
#include "RenderList.h" namespace eg { void RenderList::transform(const eg::Mat4x4& transform, eg::TransformCase transformCase) { switch (transformCase) { case eg::TransformCase::LOCAL_COORDS_ONLY: { for (uint32_t i = 0; i < nPolygons; ++i) { if (uint32_t state = vertexBuffer[i].state; !(state & eg::State::ACTIVE) || (state & eg::State::BACKFACE) || (state & eg::State::CLIPPED)) { continue; } for (uint32_t j = 0; j < 3; ++j) { vertexBuffer[i].localCoords[j] = transform * vertexBuffer[i].localCoords[j]; } } break; } case eg::TransformCase::TRANSFORM_COORDS_ONLY: { for (uint32_t i = 0; i < nPolygons; ++i) { if (uint32_t state = vertexBuffer[i].state; !(state & eg::State::ACTIVE) || (state & eg::State::BACKFACE) || (state & eg::State::CLIPPED)) { continue; } for (uint32_t j = 0; j < 3; ++j) { vertexBuffer[i].transformedCoords[j] = transform * vertexBuffer[i].transformedCoords[j]; } } break; } case eg::TransformCase::LOCAL_COORDS_TO_TRANSFORM_COORDS: { for (uint32_t i = 0; i < nPolygons; ++i) { if (uint32_t state = vertexBuffer[i].state; !(state & eg::State::ACTIVE) || (state & eg::State::BACKFACE) || (state & eg::State::CLIPPED)) { continue; } for (uint32_t j = 0; j < 3; ++j) { vertexBuffer[i].transformedCoords[j] = transform * vertexBuffer[i].localCoords[j]; } } break; } default: { InvalidCodePath; break; } } } void RenderList::translate(const Vector3f& worldPos, TransformCase transformCase) { switch (transformCase) { case TransformCase::LOCAL_COORDS_TO_TRANSFORM_COORDS: { for (uint32_t i = 0; i < nPolygons; ++i) { if (uint32_t state = vertexBuffer[i].state; !(state & State::ACTIVE) || state & State::CLIPPED || state & State::BACKFACE) { continue; } for (uint32_t j = 0; j < 3; ++j) { vertexBuffer[i].transformedCoords[j] = vertexBuffer[i].localCoords[j] + worldPos; } } break; } case TransformCase::TRANSFORM_COORDS_ONLY: { for (uint32_t i = 0; i < nPolygons; ++i) { if (uint32_t state = vertexBuffer[i].state; !(state & State::ACTIVE) || state & State::CLIPPED || state & State::BACKFACE) { continue; } for (uint32_t j = 0; j < 3; ++j) { vertexBuffer[i].transformedCoords[j] = vertexBuffer[i].transformedCoords[j] + worldPos; } } break; } default: { InvalidCodePath; break; } } } }
[ "florian.patruck@gmx.de" ]
florian.patruck@gmx.de
2cf46eb87f306c6b738795d6df610084151b5e2b
40b20d35481b234b6aeebb08fe8d595802a2de81
/lib/poly_channelizer_impl.h
b4e55186636b55c7e21166607b88808bc9c859a0
[]
no_license
zsqdtc/rfnoc-pfb-channelizer
4ab7cb279a0b293af364b022b5652a3425c97d65
fb3aa46c9008352d09526662d50242e459ee9d3c
refs/heads/master
2020-06-21T15:38:59.280230
2018-03-09T23:43:35
2018-03-09T23:43:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,998
h
/* -*- c++ -*- */ /* * Copyright 2017 <+YOU OR YOUR COMPANY+>. * * This is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this software; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_PFB_CHANNELIZER_POLY_CHANNELIZER_IMPL_H #define INCLUDED_PFB_CHANNELIZER_POLY_CHANNELIZER_IMPL_H #include <pfb_channelizer/poly_channelizer.h> namespace gr { namespace pfb_channelizer { class poly_channelizer_impl : public poly_channelizer { private: // Nothing to declare in this block. size_t d_fft_size; int d_offset; std::vector<int> d_channel_map; gr::thread::mutex d_mutex; // mutex to protect set/work access public: poly_channelizer_impl(const int fft_size, const std::vector<int> &map); ~poly_channelizer_impl(); void set_block_size(const int fft_size); int get_block_size(); void set_channel_map(const std::vector<int> &map) ; std::vector<int> get_channel_map() const; // Where all the action really happens void forecast (int noutput_items, gr_vector_int &ninput_items_required); int general_work(int noutput_items, gr_vector_int &ninput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items); }; } // namespace pfb_channelizer } // namespace gr #endif /* INCLUDED_PFB_CHANNELIZER_POLY_CHANNELIZER_IMPL_H */
[ "martin.braun@ettus.com" ]
martin.braun@ettus.com
7014124f03749ac2a817c3c6336a4f25ce0a421c
f58657a9f198bdf7b9c95e8aa64d250c7c1d5176
/src/utils.cpp
95e13854da6d6888646ac8a0c626b3a7414e84b8
[]
no_license
nurikk/you-dash
c1a0bada7b0fca74357295e5c92b6ba3f4df5a73
1778a5ef0f1fbf24842723c7c26ba391f3abb915
refs/heads/master
2020-03-29T11:55:54.475272
2019-02-07T14:28:09
2019-02-07T14:28:09
149,877,340
0
0
null
null
null
null
UTF-8
C++
false
false
2,678
cpp
#include <WString.h> #include <WiFiClientSecure.h> #include <ArduinoLog.h> #include <ArduinoJson.h> String urlencode(String str) { String encodedString = ""; char c; char code0; char code1; for (unsigned int i = 0; i < str.length(); i++) { c = str.charAt(i); if (c == ' ') { encodedString += '+'; } else if (isalnum(c)) { encodedString += c; } else { code1 = (c & 0xf) + '0'; if ((c & 0xf) > 9) { code1 = (c & 0xf) - 10 + 'A'; } c = (c >> 4) & 0xf; code0 = c + '0'; if (c > 9) { code0 = c - 10 + 'A'; } encodedString += '%'; encodedString += code0; encodedString += code1; } yield(); } return encodedString; } JsonObject &request(const char *server, const int port, String data, DynamicJsonBuffer *jsonBuffer) { jsonBuffer->clear(); WiFiClientSecure client; Log.notice("Connecting to: %s:%d\n", server, port); if (!client.connect(server, port)) { Log.error("Connection failed\n"); return jsonBuffer->createObject(); } Log.trace("Request ->\n%s\n<-\n", data.c_str()); client.print(data); while (client.connected()) { String line = client.readStringUntil('\n'); Log.trace("%s\n", line.c_str()); if (line == "\r") { Log.trace("Headers received\n"); break; } } return jsonBuffer->parseObject(client); } JsonObject &postRequest(const char *server, const int port, String header, String data, DynamicJsonBuffer *jsonBuffer) { return request(server, port, header + data, jsonBuffer); } JsonObject &getRequest(const char *server, const int port, String data, DynamicJsonBuffer *jsonBuffer) { return request(server, port, data, jsonBuffer); } time_t DatePlusDays(time_t startTime, int days) { const time_t ONE_DAY = 24 * 60 * 60; return startTime + (days * ONE_DAY); } char *ultos_recursive(unsigned long val, char *s, unsigned radix, int pos) { int c; if (val >= radix) s = ultos_recursive(val / radix, s, radix, pos+1); c = val % radix; c += (c < 10 ? '0' : 'a' - 10); *s++ = c; if (pos % 3 == 0) *s++ = ','; return s; } char *ltos(long val, char *s, int radix) { if (radix < 2 || radix > 36) { s[0] = 0; } else { char *p = s; if (radix == 10 && val < 0) { val = -val; *p++ = '-'; } p = ultos_recursive(val, p, radix, 0) - 1; *p = 0; } return s; }
[ "nur.php@gmail.com" ]
nur.php@gmail.com
09ae0c266e9ebceea397d77a24715253d3d43dfa
6f2b6e9d77fc4dd5e1dae8ba6e5a66eb7c7ae849
/sstd_boost/sstd/boost/lambda/construct.hpp
90a309dbc5c556c5d175a3cee5696294a012da0f
[ "BSL-1.0" ]
permissive
KqSMea8/sstd_library
9e4e622e1b01bed5de7322c2682539400d13dd58
0fcb815f50d538517e70a788914da7fbbe786ce1
refs/heads/master
2020-05-03T21:07:01.650034
2019-04-01T00:10:47
2019-04-01T00:10:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,276
hpp
// - construct.hpp -- Lambda Library ------------- // // Copyright (C) 2000 Gary Powell (powellg@amazon.com) // Copyright (C) 1999, 2000 Jaakko Jarvi (jaakko.jarvi@cs.utu.fi) // // 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) // // For more information, see http://www.boost.org // // ----------------------------------------------- #if !defined(BOOST_LAMBDA_CONSTRUCT_HPP) #define BOOST_LAMBDA_CONSTRUCT_HPP #include "sstd/boost/type_traits/remove_cv.hpp" #include "sstd/boost/type_traits/is_pointer.hpp" namespace boost { namespace lambda { // constructor is used together with bind. constructor<A> creates a bindable // function object that passes its arguments forward to a constructor call // of type A template<class T> struct constructor { template <class U> struct sig { typedef T type; }; T operator()() const { return T(); } template<class A1> T operator()(A1& a1) const { return T(a1); } template<class A1, class A2> T operator()(A1& a1, A2& a2) const { return T(a1, a2); } template<class A1, class A2, class A3> T operator()(A1& a1, A2& a2, A3& a3) const { return T(a1, a2, a3); } template<class A1, class A2, class A3, class A4> T operator()(A1& a1, A2& a2, A3& a3, A4& a4) const { return T(a1, a2, a3, a4); } template<class A1, class A2, class A3, class A4, class A5> T operator()(A1& a1, A2& a2, A3& a3, A4& a4, A5& a5) const { return T(a1, a2, a3, a4, a5); } template<class A1, class A2, class A3, class A4, class A5, class A6> T operator()(A1& a1, A2& a2, A3& a3, A4& a4, A5& a5, A6& a6) const { return T(a1, a2, a3, a4, a5, a6); } template<class A1, class A2, class A3, class A4, class A5, class A6, class A7> T operator()(A1& a1, A2& a2, A3& a3, A4& a4, A5& a5, A6& a6, A7& a7) const { return T(a1, a2, a3, a4, a5, a6, a7); } template<class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8> T operator()(A1& a1, A2& a2, A3& a3, A4& a4, A5& a5, A6& a6, A7& a7, A8& a8) const { return T(a1, a2, a3, a4, a5, a6, a7, a8); } template<class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, class A9> T operator()(A1& a1, A2& a2, A3& a3, A4& a4, A5& a5, A6& a6, A7& a7, A8& a8, A9& a9) const { return T(a1, a2, a3, a4, a5, a6, a7, a8, a9); } template<class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, class A9, class A10> T operator()(A1& a1, A2& a2, A3& a3, A4& a4, A5& a5, A6& a6, A7& a7, A8& a8, A9& a9, A10& a10) const { return T(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10); } }; namespace detail { // A standard conforming compiler could disambiguate between // A1* and A1&, but not all compilers do that, so we need the // helpers template <bool IsPointer> struct destructor_helper { template<class A1> static void exec(A1& a1) { // remove all the qualifiers, not sure whether it is necessary typedef typename boost::remove_cv<A1>::type plainA1; a1.~plainA1(); } }; template <> struct destructor_helper<true> { template<class A1> static void exec(A1* a1) { typedef typename boost::remove_cv<A1>::type plainA1; (*a1).~plainA1(); } }; } // destructor funtion object struct destructor { template <class T> struct sig { typedef void type; }; template<class A1> void operator()(A1& a1) const { typedef typename boost::remove_cv<A1>::type plainA1; detail::destructor_helper<boost::is_pointer<plainA1>::value>::exec(a1); } }; // new_ptr is used together with bind. // note: placement new is not supported template<class T> struct new_ptr { template <class U> struct sig { typedef T* type; }; T* operator()() const { return new T(); } template<class A1> T* operator()(A1& a1) const { return new T(a1); } template<class A1, class A2> T* operator()(A1& a1, A2& a2) const { return new T(a1, a2); } template<class A1, class A2, class A3> T* operator()(A1& a1, A2& a2, A3& a3) const { return new T(a1, a2, a3); } template<class A1, class A2, class A3, class A4> T* operator()(A1& a1, A2& a2, A3& a3, A4& a4) const { return new T(a1, a2, a3, a4); } template<class A1, class A2, class A3, class A4, class A5> T* operator()(A1& a1, A2& a2, A3& a3, A4& a4, A5& a5) const { return new T(a1, a2, a3, a4, a5); } template<class A1, class A2, class A3, class A4, class A5, class A6> T* operator()(A1& a1, A2& a2, A3& a3, A4& a4, A5& a5, A6& a6) const { return new T(a1, a2, a3, a4, a5, a6); } template<class A1, class A2, class A3, class A4, class A5, class A6, class A7> T* operator()(A1& a1, A2& a2, A3& a3, A4& a4, A5& a5, A6& a6, A7& a7) const { return new T(a1, a2, a3, a4, a5, a6, a7); } template<class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8> T* operator()(A1& a1, A2& a2, A3& a3, A4& a4, A5& a5, A6& a6, A7& a7, A8& a8) const { return new T(a1, a2, a3, a4, a5, a6, a7, a8); } template<class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, class A9> T* operator()(A1& a1, A2& a2, A3& a3, A4& a4, A5& a5, A6& a6, A7& a7, A8& a8, A9& a9) const { return new T(a1, a2, a3, a4, a5, a6, a7, a8, a9); } template<class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, class A9, class A10> T* operator()(A1& a1, A2& a2, A3& a3, A4& a4, A5& a5, A6& a6, A7& a7, A8& a8, A9& a9, A10& a10) const { return new T(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10); } }; // delete_ptr return void struct delete_ptr { template <class U> struct sig { typedef void type; }; template <class A1> void operator()(A1& a1) const { delete a1; } }; // new_array is used together with bind. template<class T> struct new_array { template <class U> struct sig { typedef T* type; }; T* operator()(int size) const { return new T[size]; } }; // delete_ptr return void struct delete_array { template <class U> struct sig { typedef void type; }; template <class A1> void operator()(A1& a1) const { delete[] a1; } }; } // namespace lambda } // namespace boost #endif
[ "zhaixueqiang@hotmail.com" ]
zhaixueqiang@hotmail.com
1a64825f51bee865dd2e1915d33a65519c089312
c0caed81b5b3e1498cbca4c1627513c456908e38
/src/protocols/coarse_rna/MultipleDomainMover.cc
cd183b874942f72a736c4c4a0e0cd6af9eb115a3
[]
no_license
malaifa/source
5b34ac0a4e7777265b291fc824da8837ecc3ee84
fc0af245885de0fb82e0a1144422796a6674aeae
refs/heads/master
2021-01-19T22:10:22.942155
2017-04-19T14:13:07
2017-04-19T14:13:07
88,761,668
0
2
null
null
null
null
UTF-8
C++
false
false
10,444
cc
// -*- mode:c++;tab-width:2;indent-tabs-mode:t;show-trailing-whitespace:t;rm-trailing-spaces:t -*- // vi: set ts=2 noet: // // (c) Copyright Rosetta Commons Member Institutions. // (c) This file is part of the Rosetta software suite and is made available under license. // (c) The Rosetta software is developed by the contributing members of the Rosetta Commons. // (c) For more information, see http://www.rosettacommons.org. Questions about this can be // (c) addressed to University of Washington UW TechTransfer, email: license@u.washington.edu. /// @file relax_protocols /// @brief protocols that are specific to MultipleDomainMover /// @details /// @author Rhiju Das #include <protocols/coarse_rna/MultipleDomainMover.hh> #include <core/conformation/Conformation.hh> #include <core/conformation/Residue.hh> #include <core/id/AtomID.hh> #include <core/id/NamedAtomID.hh> #include <core/kinematics/FoldTree.hh> #include <core/kinematics/Jump.hh> #include <core/kinematics/Stub.hh> #include <core/pose/Pose.hh> #include <core/types.hh> #include <basic/Tracer.hh> #include <protocols/coarse_rna/CoarseRNA_LoopCloser.hh> #include <protocols/rigid/RigidBodyMover.hh> #include <protocols/toolbox/AtomLevelDomainMap.hh> #include <protocols/toolbox/AtomID_Mapper.hh> // Utility headers #include <utility/vector1.hh> // ObjexxFCL Headers #include <ObjexxFCL/FArray1D.hh> // Numeric headers #include <numeric/random/random.hh> #include <numeric/xyz.functions.hh> //C++ headers #include <vector> #include <string> #include <sstream> using namespace core; using basic::T; typedef numeric::xyzMatrix< Real > Matrix; namespace protocols { namespace farna { ///////////////////////////////////// MultipleDomainMover::MultipleDomainMover( pose::Pose const & pose, protocols::coarse_rna::CoarseRNA_LoopCloserOP rna_loop_closer ): verbose_( false ), rot_mag_( 10.0 ), trans_mag_( 0.5 ), num_domains_( 0 ), rna_loop_closer_( rna_loop_closer ) { Mover::type("MultipleDomainMover"); initialize( pose, rna_loop_closer_->atom_level_domain_map() ); } //////////////////////////////////////////////////////////////// void MultipleDomainMover::apply( core::pose::Pose & pose ) { apply_and_return_jump( pose ); } /////////////////////////////////////////////////////////////////////////////// //////////////////////// std::string MultipleDomainMover::get_name() const { return "MultipleDomainMover"; } //////////////////////////////////////////////////////////////// Size MultipleDomainMover::apply_and_return_jump( core::pose::Pose & pose ) { Size const n = static_cast<Size> ( numeric::random::rg().uniform() * num_domains_ ) + 1; return apply_at_domain( pose, n ); } //////////////////////////////////////////////////////////////// Size MultipleDomainMover::apply_at_domain( core::pose::Pose & pose, Size const & n ) { rb_movers_[ n ]->apply( pose ); slide_back_to_origin( pose ); return jump_numbers_[ n ]; } //////////////////////////////////////////////////////////////// void MultipleDomainMover::initialize( pose::Pose const & pose,toolbox::AtomLevelDomainMapOP atom_level_domain_map ){ // std::cout << "HELLO! " << pose.residue_type( pose.total_residue() ).name3() << std::endl; if ( pose.residue_type( pose.total_residue() ).name3() != "XXX" /*virtual residue*/ ) return; setup_jump_numbers_and_partner( pose ); setup_ok_for_centroid_calculation( atom_level_domain_map ); initialize_rigid_body_movers(); } ///////////////////////////////////// void MultipleDomainMover::randomize_pose_rigid_bodies( pose::Pose & pose ){ randomize_orientations( pose ); try_to_slide_into_contact( pose ); close_all_loops( pose ); slide_back_to_origin( pose ); } ///////////////////////////////////// Vector MultipleDomainMover::get_centroid( pose::Pose const & pose ){ Vector cen( 0.0, 0.0, 0.0 ); Size nres( 0 ); // Look at all residues except anchor (last residue). for ( Size i = 1; i < pose.total_residue(); i++ ) { if ( ok_for_centroid_calculation_[ i ] ) { cen += pose.xyz( core::id::AtomID( 1, i ) ); nres += 1; } } cen /= nres; return cen; } ///////////////////////////////////// void MultipleDomainMover::slide_back_to_origin( pose::Pose & pose ){ using namespace core::kinematics; if ( num_domains_ < 2 ) return; Vector cen = get_centroid( pose ); // std::cout << "CENTROID1: " << cen(1) << ' ' << cen(2) << ' ' << cen(3) << std::endl; for ( Size n = 1; n <= num_domains_; n++ ) { Size jumpno( jump_numbers_[ n ] ); Jump j( pose.jump( jumpno ) ); Stub stub = pose.conformation().upstream_jump_stub( jumpno ); Vector new_translation = j.get_translation() - stub.M.transposed() * cen; j.set_translation( new_translation); pose.set_jump( jumpno, j ); } // cen = get_centroid( pose ); // std::cout << "CENTROID2: " << cen(1) << ' ' << cen(2) << ' ' << cen(3) << std::endl; } ///////////////////////////////////// void MultipleDomainMover::setup_jump_numbers_and_partner( pose::Pose const & pose ){ using namespace protocols::moves; // create rigid body mover for segment 1 Size const virt_res = pose.total_residue(); jump_numbers_.clear(); partner_.clear(); for ( Size n = 1; n <= pose.fold_tree().num_jump(); n++ ) { Size const i = pose.fold_tree().upstream_jump_residue( n ); Size const j = pose.fold_tree().downstream_jump_residue( n ); if ( i == virt_res || j == virt_res ) { jump_numbers_.push_back( n ); if ( i == virt_res ) { //partner.push_back( rigid::partner_downstream ); partner_.push_back( rigid::partner_upstream ); } else { partner_.push_back( rigid::partner_downstream ); //partner.push_back( rigid::partner_upstream ); } } } num_domains_ = jump_numbers_.size(); } ///////////////////////////////////// void MultipleDomainMover::setup_ok_for_centroid_calculation(toolbox::AtomLevelDomainMapOP & atom_level_domain_map ){ // Need to find jump number [Can try alternate constructor later] ok_for_centroid_calculation_.clear(); for ( Size i = 1; i <= atom_level_domain_map->atom_id_mapper()->nres(); i++ ) { ok_for_centroid_calculation_.push_back( !atom_level_domain_map->get( core::id::AtomID( 2, i) ) ); if ( verbose_ ) std::cout << "OK " << i << " " << ok_for_centroid_calculation_[ i ] << std::endl; } } ///////////////////////////////////// void MultipleDomainMover::randomize_orientations( pose::Pose & pose ) { using namespace protocols::moves; for ( Size n = 1; n<= num_domains_; n++ ) { rigid::RigidBodyRandomizeMover rb( pose, jump_numbers_[ n ], partner_[ n ] ); rb.apply( pose ); } if ( verbose_ ) pose.dump_pdb( "random.pdb" ); } ///////////////////////////////////////////////////////////////////////////////////// // slide into contact - actually just try to get overlap at cutpoint_closed //////////////////////////////////////////////////////////////////////////////////// void MultipleDomainMover::try_to_slide_into_contact( pose::Pose & pose ) { using namespace core::kinematics; utility::vector1< bool > slid_into_contact( pose.total_residue(), false ); for ( Size n = 2; n <= num_domains_; n++ ) { // no need to move domain 1. Size jumpno( jump_numbers_[ n ] ); // find cutpoint_closed rna_loop_closer_->apply_after_jump_change( pose, jumpno ); utility::vector1< Size > const & cutpos_list = rna_loop_closer_->cutpos_list(); Size cutpoint_closed( 0 ); for ( Size i = 1; i <= cutpos_list.size() ; i++ ) { if ( !slid_into_contact[ cutpos_list[ i ] ] ) { cutpoint_closed = cutpos_list[ i ]; break; } } if ( verbose_ ) std::cout << "CUTPOINT_CLOSED: " << cutpoint_closed << std::endl; if ( cutpoint_closed == 0 ) continue; // find locations of overlap atoms. // figure out translation Vector diff = pose.residue( cutpoint_closed ).xyz( "OVL1" ) - pose.residue( cutpoint_closed+1 ).xyz( " P " ); if ( verbose_ ) std::cout << "OLD VEC " << diff.length() << std::endl; // apply translation // This could be generalized. Note that this relies on one partner being // the VRT residue at the origin!!! Jump j( pose.jump( jumpno ) ); if ( verbose_ ) { std::cout << "OLD JUMP " << j << std::endl; std::cout << "UPSTREAM DOWNSTREAM " << pose.fold_tree().upstream_jump_residue( jumpno ) <<' ' << pose.fold_tree().downstream_jump_residue( jumpno ) << std::endl; } ObjexxFCL::FArray1D< bool > const & partition_definition = rna_loop_closer_->partition_definition(); int sign_jump = ( partition_definition( cutpoint_closed ) == partition_definition( pose.fold_tree().downstream_jump_residue( jumpno ) ) ? -1: 1); Stub stub = pose.conformation().upstream_jump_stub( jumpno ); if ( verbose_ ) std::cout << ' ' << stub.M.col_x()[0]<< ' ' << stub.M.col_x()[1]<< ' ' << stub.M.col_x()[2] << std::endl; Vector new_translation = j.get_translation() + sign_jump * stub.M.transposed() * diff; j.set_translation( new_translation );//+ Vector( 50.0, 0.0, 0.0 ) ); pose.set_jump( jumpno, j ); if ( verbose_ ) std::cout << "NEW JUMP " << pose.jump( jumpno ) << std::endl; Vector diff2 = pose.residue( cutpoint_closed ).xyz( "OVL1" ) - pose.residue( cutpoint_closed+1 ).xyz( " P " ); if ( verbose_ ) std::cout << "NEW VEC " << diff2.length() << std::endl << std::endl; slid_into_contact[ cutpoint_closed ] = true; } if ( verbose_ ) pose.dump_pdb( "slide.pdb" ); } ////////////////////////////////////////////////////////////////////////////////// void MultipleDomainMover::close_all_loops( pose::Pose & pose ) { for ( Size n = 2; n <= num_domains_; n++ ) { rna_loop_closer_->apply_after_jump_change( pose, n ); } if ( verbose_ ) pose.dump_pdb( "closed.pdb" ); } ///////////////////////////////////// void MultipleDomainMover::initialize_rigid_body_movers(){ using namespace protocols::moves; rb_movers_.clear(); std::cout << "NUM_DOMAINS: " << num_domains_ << std::endl; for ( Size n = 1; n <= num_domains_; n++ ) { rb_movers_.push_back( protocols::rigid::RigidBodyPerturbMoverOP( new rigid::RigidBodyPerturbMover( jump_numbers_[ n ], rot_mag_, trans_mag_, partner_[ n ], ok_for_centroid_calculation_ ) ) ); } } ///////////////////////////////////// void MultipleDomainMover::update_rot_trans_mag( Real const & rot_mag, Real const & trans_mag ){ rot_mag_ = rot_mag; trans_mag_ = trans_mag; for ( Size n = 1; n <= num_domains_; n++ ) { rb_movers_[ n ]->rot_magnitude( rot_mag_ ); rb_movers_[ n ]->trans_magnitude( rot_mag_ ); } } } //farna } //protocols
[ "malaifa@yahoo.com" ]
malaifa@yahoo.com
a11658a2e1da2e759f8959e1dde87b29be62d77b
39eff1a79b697519939bec6d03adba4e16e86be6
/STL2/List.h
4b4f2d0cc2759f840e8689b43c62a75730aab80c
[]
no_license
NanlinW/NanlinCode
eeed6b4d9771ff496baa36b74586fdb5c1c9c563
d2c6a72dccab015d9c25503e2cf7d9d8a6d25777
refs/heads/master
2021-09-01T18:57:53.322243
2021-08-16T16:26:36
2021-08-16T16:26:36
221,634,926
0
1
null
null
null
null
GB18030
C++
false
false
4,824
h
#pragma once namespace bite { template<class T> struct ListNode { ListNode<T>* next; ListNode<T>* prev; T val; ListNode(const T& value = T()) : next(nullptr) , prev(nullptr) , val(value) {} }; // list的迭代器必须要对原生态指针(节点类型的指针)进行封装 template<class T, class Ref, class Ptr> struct ListIterator { public: typedef ListNode<T> Node; typedef ListIterator<T, Ref, Ptr> Self; public: // 构造 ListIterator(Node* node = nullptr) : _node(node) {} // 具有类似指针的行为 Ref operator*() { return _node->val; } Ptr operator->() { // return &(_node->val); return &(operator*()); } // 迭代器能够移动 // 前置++ Self& operator++() { _node = _node->next; return *this; } // 后置++ Self operator++(int) { Self temp(*this); _node = _node->next; return temp; } // 前置-- Self& operator--() { _node = _node->prev; return *this; } // 后置++ Self operator--(int) { Self temp(*this); _node = _node->prev; return temp; } //比较 bool operator!=(const Self& s)const { return _node != s._node; } bool operator==(const Self& s)const { return _node == s._node; } Node* _node; }; template<class T> class list { typedef ListNode<T> Node; // typedef T* iterator; // list的迭代器能否给成原生态的指针??? // 不行,对于list迭代器如果使用原生态的指针,当对迭代器进行++操作时,无法取到下一个节点 // 链表取下一个节点只能通过next来进行获取 public: typedef ListIterator<T, T&, T*> iterator; typedef ListIterator<T, const T&, const T*> const_iterator; public: list() { CreateHead(); } list(int n, const T& value = T()) { CreateHead(); for (int i = 0; i < n; ++i) push_back(value); } template<class Iterator> list(Iterator first, Iterator last) { CreateHead(); while (first != last) { push_back(*first++); } } list(list<T>& L) { CreateHead(); auto it = L.begin(); while (it != L.end()) { push_back(*it++); } } list<T>& operator=(const list<T>& L); ~list() { // 1. 删除有效节点 // 2. 删除头结点 erase(begin(), end()); delete head; head = nullptr; } /////////////////////////////////////////////// // 迭代器操作 iterator begin() { return iterator(head->next); } iterator end() { return iterator(head); } const_iterator cbegin()const { return const_iterator(head->next); } const_iterator cend()const { return const_iterator(head); } /////////////////////////////////////////////// // 容量相关的操作 size_t size()const { size_t count = 0; auto it = cbegin(); while (it != cend()) ++it, ++count; return count; } bool empty()const { return head->next == head; } void resize(size_t newsize, const T& data = T()) { size_t oldsize = size(); if (newsize < oldsize) { for (size_t i = newsize; i < oldsize; ++i) pop_back(); } else { for (size_t i = oldsize; i < newsize; ++i) push_back(data); } } ///////////////////////////////////////////////// // 元素访问 // 访问链表中第一个元素 T& front() { return head->next->val; } const T& front()const { return head->next->val; } // 访问链表最后一个节点中的元素 T& back() { return head->prev->val; } const T& back()const { return head->prev->val; } //////////////////////////////////////////////////// // 修改操作 void push_back(const T& data) { insert(end(), data); } void pop_back() { auto it = end(); erase(--it); } void push_front(const T& data) { insert(begin(), data); } void pop_front() { erase(begin()); } // 在pos位置插入值为data的元素,返回新插入元素的位置 iterator insert(iterator pos, const T& data) { Node* newNode = new Node(data); newNode->prev = pos._node->prev; newNode->next = pos._node; newNode->prev->next = newNode; pos._node->prev = newNode; return iterator(newNode); } iterator erase(iterator pos) { Node* ret = pos._node->next; Node* cur = pos._node; cur->prev->next = cur->next; cur->next->prev = cur->prev; delete cur; return iterator(ret); } iterator erase(iterator first, iterator last) { while (first != last) { first = erase(first); } return end(); } void clear() { erase(begin(), end()); } void swap(list<T>& l) { std::swap(head, L.head); } private: void CreateHead() { head = new Node; head->prev = head; head->next = head; } private: Node* head; }; }
[ "nanlinw@163.com" ]
nanlinw@163.com
c7c73103650ca878ef8672ce80599e54a179a293
df5274956502f5430e176faef166ebf843883d6c
/EmptyScene.h
75a7e369eb79bbe6a35698794b0f8e47fe67e0d2
[ "MIT" ]
permissive
danielHPeters/fight-dude
a878ad64d2a14de9aa8c05e336411dbb7a791e13
812c65c093cff31e66b0c17c956bc9cbaf620ede
refs/heads/master
2021-06-04T05:31:17.751648
2020-05-09T09:23:37
2020-05-09T09:23:37
106,569,214
0
0
null
null
null
null
UTF-8
C++
false
false
383
h
#ifndef FIGHT_DUDE_EMPTYSCENE_H #define FIGHT_DUDE_EMPTYSCENE_H #include "Scene.h" #include "InputState.h" namespace fightdude { class EmptyScene : public Scene<int> { public: void update(int elapsedTime, InputState inputState) override; void render() override; void onEnter() override; void onExit() override; }; } //namespace fightdude #endif //FIGHT_DUDE_EMPTYSCENE_H
[ "daniel.peters.ch@gmail.com" ]
daniel.peters.ch@gmail.com
9b3b1ff41dba13b28aa0d23b7e5296c1f770d841
10c1af697bd0e2bd05370d9329249ff705ba5150
/include/core/dcp/model/constant/DcpScope.hpp
ea3bc4f370dee0d5356312bf85e6281ce0462525
[ "BSD-3-Clause" ]
permissive
ChKater/DCPLib
75a6e4f30ba48729caa4715a7a77d520e515bf3a
4912ebdbfd333c8571c66c05f587bd70852dabe5
refs/heads/master
2020-04-08T15:03:19.383980
2019-02-14T09:33:07
2019-02-14T09:33:07
159,463,333
0
0
null
null
null
null
MacCentralEurope
C++
false
false
1,693
hpp
/* * Copyright (C) 2019, FG Simulation und Modellierung, Leibniz Universitšt Hannover, Germany * * All rights reserved. * * This software may be modified and distributed under the terms * of the BSD 3-CLause license. See the LICENSE file for details. */ #ifndef DCPLIB_DCPSCOPE_HPP #define DCPLIB_DCPSCOPE_HPP #include <string> #if defined(DEBUG) || defined(LOGGING) #include <sstream> #endif enum class DcpScope : uint8_t { /** * Configuration PDUs for data ids with scope Initialization_Run_NonRealTime are valid in the superstates * Initialization, Run & NonRealTime. */ Initialization_Run_NonRealTime = 0x00, /** * Configuration PDUs for data ids with scope Initialization_Run_NonRealTime are valid in the superstates * Initialization. */ Initialization = 0x01, /** * Configuration PDUs for data ids with scope Initialization_Run_NonRealTime are valid in the superstates * Run & NonRealTime. */ Run_NonRealTime = 0x02, }; #if defined(DEBUG) || defined(LOGGING) static std::ostream &operator<<(std::ostream &os, DcpScope scope) { switch (scope) { case DcpScope::Initialization_Run_NonRealTime: return os << "Initialization/Run/NonRealTime"; case DcpScope::Initialization: return os << "Initialization"; case DcpScope::Run_NonRealTime: return os << "Run/NonRealTime"; default: return os << "UNKNOWN(" << (unsigned((uint8_t) scope)) << ")"; } return os; } static std::string to_string(DcpScope scope) { std::ostringstream oss; oss << scope; return oss.str(); } #endif #endif //DCPLIB_DCPSCOPE_HPP
[ "ch.kater@gmail.com" ]
ch.kater@gmail.com
167048c003772fb03cce1fc19022634505608990
7f67fb29806bf037b1f0b1ec2134f82435c73082
/plugins/osgaudio/include2/openalpp/Sample.h
a063a735579a412539523bea3a53ec8972575f4e
[]
no_license
popoca/OSG_ShootingGallery
a65f92c121ea8741750c8a572123a0062a331db9
75f9b58b0dddc274d05deda716072354f7e23f31
refs/heads/master
2020-04-09T02:40:51.579783
2010-12-17T10:11:01
2010-12-17T10:11:01
1,242,956
0
1
null
null
null
null
IBM852
C++
false
false
2,265
h
/* -*-c++-*- */ /** * osgAudio - OpenSceneGraph Audio Library * Copyright (C) 2010 AlphaPixel, LLC * based on a fork of: * Osg AL - OpenSceneGraph Audio Library * Copyright (C) 2004 VRlab, Umeň University * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * Please see COPYING file for special static-link exemption to LGPL. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. */ #ifndef OPENALPP_SAMPLE_H #define OPENALPP_SAMPLE_H 1 #include <openalpp/windowsstuff.h> #include <openalpp/SoundData.h> #include <openalpp/Error.h> #include <string> namespace openalpp { /** * Class for loading sampled files. */ class OPENALPP_API Sample : public SoundData { public: /** * Constructor. * @param filename is name of file to load. */ Sample(const std::string& filename ) throw (FileError); /** * Copy constructor. */ Sample(const Sample &sample); /** * Constructor. * @param format to use to create sample from data. * @param data use to create sample. * @param size of data. * @param freq of data. */ Sample(ALenum format,ALvoid* data,ALsizei size,ALsizei freq) throw (FileError); /** * Get file name of loaded file. * @return file name. */ std::string getFileName() const; /** * Assignment operator. */ Sample &operator=(const Sample &sample); protected: /** * Destructor */ virtual ~Sample(); private: /** * File name. */ std::string filename_; }; /** * Check how large a sample is in the given format. */ unsigned int sampleSize(SampleFormat format); unsigned int sampleSize(ALenum format); } #endif /* OPENALPP_SAMPLE_H */
[ "albinkun@gmail.com" ]
albinkun@gmail.com
08939f7595c2b664ff12a9e46849914f499dab35
bdf82570da38aa5677e583718d80a6bac90964a7
/LxDairy/src/module_collection/StarEditor.cpp
adb077359cbd9a98332cfb6d8e1c0bd3f5dfffe5
[]
no_license
519984307/FengZhiHong
46f43a673af329b962fcb9a98efbdccace8dcb22
15c77f96ca114b57db865e98f3ae3b0c6789524b
refs/heads/master
2023-04-15T14:00:46.917141
2021-04-30T03:13:02
2021-04-30T03:13:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,044
cpp
#include <QtWidgets> #include <cmath> #include "StarEditor.h" static const qreal s_nPaintingScaleFactor = 20.0; static const int s_nMaxStarCount = 5; CStarEditor::CStarEditor(QWidget* parent) : QWidget(parent) { setMouseTracking(true); setAutoFillBackground(true); m_dRating = 0; m_nMaxStarCount = s_nMaxStarCount; m_bReadOnly = false; bLeftMousePress = false; bDelegateEedit = false; } void CStarEditor::drawFiveStarRating(QPainter *painter, const QRect &rect, const QPalette & palette , qreal dRating, bool bReadOnly) { // 五星路径 单元(半径0.5) QPolygonF polygonStar; polygonStar << QPointF(1.0, 0.5); for (int i = 1; i < 5; ++i) { polygonStar << QPointF(0.5 + 0.5 * std::cos(0.8 * i * 3.14), 0.5 + 0.5 * std::sin(0.8 * i * 3.14)); } // 砖石路径 单元 QPolygonF polygonDiamond; polygonDiamond << QPointF(0.4, 0.5) << QPointF(0.5, 0.4) << QPointF(0.6, 0.5) << QPointF(0.5, 0.6) << QPointF(0.4, 0.5); painter->save(); painter->setRenderHint(QPainter::Antialiasing, true); painter->setPen(Qt::NoPen); if (bReadOnly) { painter->setBrush(palette.foreground()); } else { painter->setBrush(palette.highlight()); } int yOffset = (rect.height() - s_nPaintingScaleFactor) / 2; painter->translate(rect.x(), rect.y() + yOffset); // 放大坐标系 painter->scale(s_nPaintingScaleFactor, s_nPaintingScaleFactor); // 整数部分 int nRating = (int) dRating; // 余数部分 qreal dMOD = dRating - nRating; int nRatingAdd1 = nRating + 1; for (int i = 0; i < s_nMaxStarCount; ++i) { if (i < nRating) { painter->drawPolygon(polygonStar, Qt::WindingFill); } else if (i < nRatingAdd1) { QPolygonF polygonRectMod; polygonRectMod << QPointF(0.0, 0.0) << QPointF(dMOD, 0.0) << QPointF(dMOD, 1.0) << QPointF(0.0, 1.0); // QPainterPath painterPath; // painterPath.addPolygon(polygonStar); // QRectF rectMOD(0, 0, dMOD, 1.0); // QPainterPath painterPathMod; // painterPathMod.addRect(rectMOD); // QPainterPath pathIntersected = painterPath.intersected(painterPathMod); // painter->drawPath(pathIntersected); QPolygonF polygonIntersected = polygonStar.intersected(polygonRectMod); painter->drawPolygon(polygonIntersected, Qt::WindingFill); } else if (!bReadOnly) { painter->drawPolygon(polygonDiamond, Qt::WindingFill); } // 不断平移坐标系 painter->translate(1.0, 0.0); } painter->restore(); } QSize CStarEditor::sizeHint() const { // s_nPaintingScaleFactor右边距 return s_nPaintingScaleFactor * QSize(m_nMaxStarCount, 1) + QSize(s_nPaintingScaleFactor,0); } void CStarEditor::paintEvent(QPaintEvent*) { QPainter painter(this); drawFiveStarRating(&painter, rect(), this->palette(), m_dRating, m_bReadOnly); } void CStarEditor::mousePressEvent(QMouseEvent *event) { bLeftMousePress = true; } void CStarEditor::mouseMoveEvent(QMouseEvent* event) { if (bDelegateEedit) { qreal dRating = event->x() / s_nPaintingScaleFactor; if (dRating < 0) { dRating = 0; } if ( dRating > m_nMaxStarCount) { dRating = m_nMaxStarCount; } m_dRating = dRating; update(); } } void CStarEditor::mouseReleaseEvent(QMouseEvent* event) { bLeftMousePress = false; if (!bDelegateEedit) { qreal dRating = event->x() / s_nPaintingScaleFactor; if (dRating < 0) { dRating = 0; } if ( dRating > m_nMaxStarCount) { dRating = m_nMaxStarCount; } m_dRating = dRating; update(); } emit editingFinished(); emit editingFinished(m_dRating); }
[ "654380976@qq.com" ]
654380976@qq.com
c447cec6ee35512a6ff47badc62c45e6142cbc60
1ba69d50e41c1df6bb5dc61b3de10d17180120b1
/src/names.h
cecb4e7c18b5c43a0ee9938e98d6b6e5fb86c24b
[]
no_license
filipnovotny/turtlesim_pioneer
7c7b3e00faf5be826fa66fdabf461996eb2494ce
7d4d09aff8304687863f9ac6347cd0664ee23ae8
refs/heads/master
2016-09-06T06:41:24.542247
2012-09-05T10:21:08
2012-09-05T10:21:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,576
h
/**************************************************************************** * * $Id: file.h 3496 2011-11-22 15:14:32Z fnovotny $ * * This file is part of the ViSP software. * Copyright (C) 2005 - 2012 by INRIA. All rights reserved. * * This software is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * ("GPL") version 2 as published by the Free Software Foundation. * See the file LICENSE.txt at the root directory of this source * distribution for additional information about the GNU GPL. * * For using ViSP with software that can not be combined with the GNU * GPL, please contact INRIA about acquiring a ViSP Professional * Edition License. * * See http://www.irisa.fr/lagadic/visp/visp.html for more information. * * This software was developed at: * INRIA Rennes - Bretagne Atlantique * Campus Universitaire de Beaulieu * 35042 Rennes Cedex * France * http://www.irisa.fr/lagadic * * If you have questions regarding the use of this file, please contact * INRIA at visp@inria.fr * * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. * * Contact visp@irisa.fr if any conditions of this licensing are * not clear to you. * * Description: * File containing names of topics or services used all accross the package * * Authors: * Filip Novotny * * *****************************************************************************/ /*! \file names.h \brief File containing names of topics or services used all accross the package */ #ifndef __visp_hand2eye_calibration_NAMES_H__ # define __visp_hand2eye_calibration_NAMES_H__ # include <string> // define topic and service names for the visp_hand2eye_calibration package. namespace turtlesim_pioneer { extern std::string joy_topic; extern std::string velocity_topic; extern std::string velocity_sub_topic; extern std::string cancel_topic; extern std::string goal_topic; extern std::string goal_cancel_topic; extern std::string odometry_topic; extern std::string odometry_pub_topic; extern std::string axis_linear_param; extern std::string axis_angular_param; extern std::string scale_linear_param; extern std::string scale_angular_param; extern std::string parent_frame_param; extern std::string child_frame_param; extern std::string offset_x_param; extern std::string offset_y_param; extern std::string offset_z_param; extern std::string cancel_param; void remap(); } #endif
[ "filip.novotny@inria.fr" ]
filip.novotny@inria.fr
185e7dfd350fa008fc4026bc6df26bbdde8e4b55
8c08677d9a6afb793cf885f0f3844d7b4cf2e1b2
/src/rpcdump.cpp
fef0c4e6aaf14f35aeb9ebfc8e36294e72cbfa83
[ "MIT" ]
permissive
bitstakecore/skw-no-master
4838edefc2a28f8250273f9434fa988f39644309
b3dc493cbf18901de7414732ac406d3e58bce2dc
refs/heads/master
2020-04-28T05:20:29.842350
2019-03-22T02:27:20
2019-03-22T02:27:20
175,016,099
0
0
null
null
null
null
UTF-8
C++
false
false
19,224
cpp
// Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2018 The PIVX developers // Copyright (c) 2018 The SKW Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "bip38.h" #include "init.h" #include "main.h" #include "rpcserver.h" #include "script/script.h" #include "script/standard.h" #include "sync.h" #include "util.h" #include "utilstrencodings.h" #include "utiltime.h" #include "wallet.h" #include <fstream> #include <secp256k1.h> #include <stdint.h> #include <boost/algorithm/string.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <openssl/aes.h> #include <openssl/sha.h> #include <univalue.h> using namespace std; void EnsureWalletIsUnlocked(); std::string static EncodeDumpTime(int64_t nTime) { return DateTimeStrFormat("%Y-%m-%dT%H:%M:%SZ", nTime); } int64_t static DecodeDumpTime(const std::string& str) { static const boost::posix_time::ptime epoch = boost::posix_time::from_time_t(0); static const std::locale loc(std::locale::classic(), new boost::posix_time::time_input_facet("%Y-%m-%dT%H:%M:%SZ")); std::istringstream iss(str); iss.imbue(loc); boost::posix_time::ptime ptime(boost::date_time::not_a_date_time); iss >> ptime; if (ptime.is_not_a_date_time()) return 0; return (ptime - epoch).total_seconds(); } std::string static EncodeDumpString(const std::string& str) { std::stringstream ret; BOOST_FOREACH (unsigned char c, str) { if (c <= 32 || c >= 128 || c == '%') { ret << '%' << HexStr(&c, &c + 1); } else { ret << c; } } return ret.str(); } std::string DecodeDumpString(const std::string& str) { std::stringstream ret; for (unsigned int pos = 0; pos < str.length(); pos++) { unsigned char c = str[pos]; if (c == '%' && pos + 2 < str.length()) { c = (((str[pos + 1] >> 6) * 9 + ((str[pos + 1] - '0') & 15)) << 4) | ((str[pos + 2] >> 6) * 9 + ((str[pos + 2] - '0') & 15)); pos += 2; } ret << c; } return ret.str(); } UniValue importprivkey(const UniValue& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 3) throw runtime_error( "importprivkey \"BSprivkey\" ( \"label\" rescan )\n" "\nAdds a private key (as returned by dumpprivkey) to your wallet.\n" "\nArguments:\n" "1. \"BSprivkey\" (string, required) The private key (see dumpprivkey)\n" "2. \"label\" (string, optional, default=\"\") An optional label\n" "3. rescan (boolean, optional, default=true) Rescan the wallet for transactions\n" "\nNote: This call can take minutes to complete if rescan is true.\n" "\nExamples:\n" "\nDump a private key\n" + HelpExampleCli("dumpprivkey", "\"myaddress\"") + "\nImport the private key with rescan\n" + HelpExampleCli("importprivkey", "\"mykey\"") + "\nImport using a label and without rescan\n" + HelpExampleCli("importprivkey", "\"mykey\" \"testing\" false") + "\nAs a JSON-RPC call\n" + HelpExampleRpc("importprivkey", "\"mykey\", \"testing\", false")); LOCK2(cs_main, pwalletMain->cs_wallet); EnsureWalletIsUnlocked(); string strSecret = params[0].get_str(); string strLabel = ""; if (params.size() > 1) strLabel = params[1].get_str(); // Whether to perform rescan after import bool fRescan = true; if (params.size() > 2) fRescan = params[2].get_bool(); CBitcoinSecret vchSecret; bool fGood = vchSecret.SetString(strSecret); if (!fGood) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key encoding"); CKey key = vchSecret.GetKey(); if (!key.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Private key outside allowed range"); CPubKey pubkey = key.GetPubKey(); assert(key.VerifyPubKey(pubkey)); CKeyID vchAddress = pubkey.GetID(); { pwalletMain->MarkDirty(); pwalletMain->SetAddressBook(vchAddress, strLabel, "receive"); // Don't throw error in case a key is already there if (pwalletMain->HaveKey(vchAddress)) return NullUniValue; pwalletMain->mapKeyMetadata[vchAddress].nCreateTime = 1; if (!pwalletMain->AddKeyPubKey(key, pubkey)) throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet"); // whenever a key is imported, we need to scan the whole chain pwalletMain->nTimeFirstKey = 1; // 0 would be considered 'no value' if (fRescan) { pwalletMain->ScanForWalletTransactions(chainActive.Genesis(), true); } } return NullUniValue; } UniValue importaddress(const UniValue& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 3) throw runtime_error( "importaddress \"address\" ( \"label\" rescan )\n" "\nAdds an address or script (in hex) that can be watched as if it were in your wallet but cannot be used to spend.\n" "\nArguments:\n" "1. \"address\" (string, required) The address\n" "2. \"label\" (string, optional, default=\"\") An optional label\n" "3. rescan (boolean, optional, default=true) Rescan the wallet for transactions\n" "\nNote: This call can take minutes to complete if rescan is true.\n" "\nExamples:\n" "\nImport an address with rescan\n" + HelpExampleCli("importaddress", "\"myaddress\"") + "\nImport using a label without rescan\n" + HelpExampleCli("importaddress", "\"myaddress\" \"testing\" false") + "\nAs a JSON-RPC call\n" + HelpExampleRpc("importaddress", "\"myaddress\", \"testing\", false")); LOCK2(cs_main, pwalletMain->cs_wallet); CScript script; CBitcoinAddress address(params[0].get_str()); if (address.IsValid()) { script = GetScriptForDestination(address.Get()); } else if (IsHex(params[0].get_str())) { std::vector<unsigned char> data(ParseHex(params[0].get_str())); script = CScript(data.begin(), data.end()); } else { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid BS address or script"); } string strLabel = ""; if (params.size() > 1) strLabel = params[1].get_str(); // Whether to perform rescan after import bool fRescan = true; if (params.size() > 2) fRescan = params[2].get_bool(); { if (::IsMine(*pwalletMain, script) == ISMINE_SPENDABLE) throw JSONRPCError(RPC_WALLET_ERROR, "The wallet already contains the private key for this address or script"); // add to address book or update label if (address.IsValid()) pwalletMain->SetAddressBook(address.Get(), strLabel, "receive"); // Don't throw error in case an address is already there if (pwalletMain->HaveWatchOnly(script)) return NullUniValue; pwalletMain->MarkDirty(); if (!pwalletMain->AddWatchOnly(script)) throw JSONRPCError(RPC_WALLET_ERROR, "Error adding address to wallet"); if (fRescan) { pwalletMain->ScanForWalletTransactions(chainActive.Genesis(), true); pwalletMain->ReacceptWalletTransactions(); } } return NullUniValue; } UniValue importwallet(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "importwallet \"filename\"\n" "\nImports keys from a wallet dump file (see dumpwallet).\n" "\nArguments:\n" "1. \"filename\" (string, required) The wallet file\n" "\nExamples:\n" "\nDump the wallet\n" + HelpExampleCli("dumpwallet", "\"test\"") + "\nImport the wallet\n" + HelpExampleCli("importwallet", "\"test\"") + "\nImport using the json rpc call\n" + HelpExampleRpc("importwallet", "\"test\"")); LOCK2(cs_main, pwalletMain->cs_wallet); EnsureWalletIsUnlocked(); ifstream file; file.open(params[0].get_str().c_str(), std::ios::in | std::ios::ate); if (!file.is_open()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file"); int64_t nTimeBegin = chainActive.Tip()->GetBlockTime(); bool fGood = true; int64_t nFilesize = std::max((int64_t)1, (int64_t)file.tellg()); file.seekg(0, file.beg); pwalletMain->ShowProgress(_("Importing..."), 0); // show progress dialog in GUI while (file.good()) { pwalletMain->ShowProgress("", std::max(1, std::min(99, (int)(((double)file.tellg() / (double)nFilesize) * 100)))); std::string line; std::getline(file, line); if (line.empty() || line[0] == '#') continue; std::vector<std::string> vstr; boost::split(vstr, line, boost::is_any_of(" ")); if (vstr.size() < 2) continue; CBitcoinSecret vchSecret; if (!vchSecret.SetString(vstr[0])) continue; CKey key = vchSecret.GetKey(); CPubKey pubkey = key.GetPubKey(); assert(key.VerifyPubKey(pubkey)); CKeyID keyid = pubkey.GetID(); if (pwalletMain->HaveKey(keyid)) { LogPrintf("Skipping import of %s (key already present)\n", CBitcoinAddress(keyid).ToString()); continue; } int64_t nTime = DecodeDumpTime(vstr[1]); std::string strLabel; bool fLabel = true; for (unsigned int nStr = 2; nStr < vstr.size(); nStr++) { if (boost::algorithm::starts_with(vstr[nStr], "#")) break; if (vstr[nStr] == "change=1") fLabel = false; if (vstr[nStr] == "reserve=1") fLabel = false; if (boost::algorithm::starts_with(vstr[nStr], "label=")) { strLabel = DecodeDumpString(vstr[nStr].substr(6)); fLabel = true; } } LogPrintf("Importing %s...\n", CBitcoinAddress(keyid).ToString()); if (!pwalletMain->AddKeyPubKey(key, pubkey)) { fGood = false; continue; } pwalletMain->mapKeyMetadata[keyid].nCreateTime = nTime; if (fLabel) pwalletMain->SetAddressBook(keyid, strLabel, "receive"); nTimeBegin = std::min(nTimeBegin, nTime); } file.close(); pwalletMain->ShowProgress("", 100); // hide progress dialog in GUI CBlockIndex* pindex = chainActive.Tip(); while (pindex && pindex->pprev && pindex->GetBlockTime() > nTimeBegin - 7200) pindex = pindex->pprev; if (!pwalletMain->nTimeFirstKey || nTimeBegin < pwalletMain->nTimeFirstKey) pwalletMain->nTimeFirstKey = nTimeBegin; LogPrintf("Rescanning last %i blocks\n", chainActive.Height() - pindex->nHeight + 1); pwalletMain->ScanForWalletTransactions(pindex); pwalletMain->MarkDirty(); if (!fGood) throw JSONRPCError(RPC_WALLET_ERROR, "Error adding some keys to wallet"); return NullUniValue; } UniValue dumpprivkey(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "dumpprivkey \"BSaddress\"\n" "\nReveals the private key corresponding to 'BSaddress'.\n" "Then the importprivkey can be used with this output\n" "\nArguments:\n" "1. \"BSaddress\" (string, required) The BS address for the private key\n" "\nResult:\n" "\"key\" (string) The private key\n" "\nExamples:\n" + HelpExampleCli("dumpprivkey", "\"myaddress\"") + HelpExampleCli("importprivkey", "\"mykey\"") + HelpExampleRpc("dumpprivkey", "\"myaddress\"")); LOCK2(cs_main, pwalletMain->cs_wallet); EnsureWalletIsUnlocked(); string strAddress = params[0].get_str(); CBitcoinAddress address; if (!address.SetString(strAddress)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid BS address"); CKeyID keyID; if (!address.GetKeyID(keyID)) throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to a key"); CKey vchSecret; if (!pwalletMain->GetKey(keyID, vchSecret)) throw JSONRPCError(RPC_WALLET_ERROR, "Private key for address " + strAddress + " is not known"); return CBitcoinSecret(vchSecret).ToString(); } UniValue dumpwallet(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "dumpwallet \"filename\"\n" "\nDumps all wallet keys in a human-readable format.\n" "\nArguments:\n" "1. \"filename\" (string, required) The filename\n" "\nExamples:\n" + HelpExampleCli("dumpwallet", "\"test\"") + HelpExampleRpc("dumpwallet", "\"test\"")); LOCK2(cs_main, pwalletMain->cs_wallet); EnsureWalletIsUnlocked(); ofstream file; file.open(params[0].get_str().c_str()); if (!file.is_open()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file"); std::map<CKeyID, int64_t> mapKeyBirth; std::set<CKeyID> setKeyPool; pwalletMain->GetKeyBirthTimes(mapKeyBirth); pwalletMain->GetAllReserveKeys(setKeyPool); // sort time/key pairs std::vector<std::pair<int64_t, CKeyID> > vKeyBirth; for (std::map<CKeyID, int64_t>::const_iterator it = mapKeyBirth.begin(); it != mapKeyBirth.end(); it++) { vKeyBirth.push_back(std::make_pair(it->second, it->first)); } mapKeyBirth.clear(); std::sort(vKeyBirth.begin(), vKeyBirth.end()); // produce output file << strprintf("# Wallet dump created by BS %s (%s)\n", CLIENT_BUILD, CLIENT_DATE); file << strprintf("# * Created on %s\n", EncodeDumpTime(GetTime())); file << strprintf("# * Best block at time of backup was %i (%s),\n", chainActive.Height(), chainActive.Tip()->GetBlockHash().ToString()); file << strprintf("# mined on %s\n", EncodeDumpTime(chainActive.Tip()->GetBlockTime())); file << "\n"; for (std::vector<std::pair<int64_t, CKeyID> >::const_iterator it = vKeyBirth.begin(); it != vKeyBirth.end(); it++) { const CKeyID& keyid = it->second; std::string strTime = EncodeDumpTime(it->first); std::string strAddr = CBitcoinAddress(keyid).ToString(); CKey key; if (pwalletMain->GetKey(keyid, key)) { if (pwalletMain->mapAddressBook.count(keyid)) { file << strprintf("%s %s label=%s # addr=%s\n", CBitcoinSecret(key).ToString(), strTime, EncodeDumpString(pwalletMain->mapAddressBook[keyid].name), strAddr); } else if (setKeyPool.count(keyid)) { file << strprintf("%s %s reserve=1 # addr=%s\n", CBitcoinSecret(key).ToString(), strTime, strAddr); } else { file << strprintf("%s %s change=1 # addr=%s\n", CBitcoinSecret(key).ToString(), strTime, strAddr); } } } file << "\n"; file << "# End of dump\n"; file.close(); return NullUniValue; } UniValue bip38encrypt(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 2) throw runtime_error( "bip38encrypt \"BSaddress\"\n" "\nEncrypts a private key corresponding to 'BSaddress'.\n" "\nArguments:\n" "1. \"BSaddress\" (string, required) The BS address for the private key (you must hold the key already)\n" "2. \"passphrase\" (string, required) The passphrase you want the private key to be encrypted with - Valid special chars: !#$%&'()*+,-./:;<=>?`{|}~ \n" "\nResult:\n" "\"key\" (string) The encrypted private key\n" "\nExamples:\n"); LOCK2(cs_main, pwalletMain->cs_wallet); EnsureWalletIsUnlocked(); string strAddress = params[0].get_str(); string strPassphrase = params[1].get_str(); CBitcoinAddress address; if (!address.SetString(strAddress)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid BS address"); CKeyID keyID; if (!address.GetKeyID(keyID)) throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to a key"); CKey vchSecret; if (!pwalletMain->GetKey(keyID, vchSecret)) throw JSONRPCError(RPC_WALLET_ERROR, "Private key for address " + strAddress + " is not known"); uint256 privKey = vchSecret.GetPrivKey_256(); string encryptedOut = BIP38_Encrypt(strAddress, strPassphrase, privKey, vchSecret.IsCompressed()); UniValue result(UniValue::VOBJ); result.push_back(Pair("Addess", strAddress)); result.push_back(Pair("Encrypted Key", encryptedOut)); return result; } UniValue bip38decrypt(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 2) throw runtime_error( "bip38decrypt \"BSaddress\"\n" "\nDecrypts and then imports password protected private key.\n" "\nArguments:\n" "1. \"encryptedkey\" (string, required) The encrypted private key\n" "2. \"passphrase\" (string, required) The passphrase you want the private key to be encrypted with\n" "\nResult:\n" "\"key\" (string) The decrypted private key\n" "\nExamples:\n"); LOCK2(cs_main, pwalletMain->cs_wallet); EnsureWalletIsUnlocked(); /** Collect private key and passphrase **/ string strKey = params[0].get_str(); string strPassphrase = params[1].get_str(); uint256 privKey; bool fCompressed; if (!BIP38_Decrypt(strPassphrase, strKey, privKey, fCompressed)) throw JSONRPCError(RPC_WALLET_ERROR, "Failed To Decrypt"); UniValue result(UniValue::VOBJ); result.push_back(Pair("privatekey", HexStr(privKey))); CKey key; key.Set(privKey.begin(), privKey.end(), fCompressed); if (!key.IsValid()) throw JSONRPCError(RPC_WALLET_ERROR, "Private Key Not Valid"); CPubKey pubkey = key.GetPubKey(); pubkey.IsCompressed(); assert(key.VerifyPubKey(pubkey)); result.push_back(Pair("Address", CBitcoinAddress(pubkey.GetID()).ToString())); CKeyID vchAddress = pubkey.GetID(); { pwalletMain->MarkDirty(); pwalletMain->SetAddressBook(vchAddress, "", "receive"); // Don't throw error in case a key is already there if (pwalletMain->HaveKey(vchAddress)) throw JSONRPCError(RPC_WALLET_ERROR, "Key already held by wallet"); pwalletMain->mapKeyMetadata[vchAddress].nCreateTime = 1; if (!pwalletMain->AddKeyPubKey(key, pubkey)) throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet"); // whenever a key is imported, we need to scan the whole chain pwalletMain->nTimeFirstKey = 1; // 0 would be considered 'no value' pwalletMain->ScanForWalletTransactions(chainActive.Genesis(), true); } return result; }
[ "admin@bitstake.org" ]
admin@bitstake.org
cfbd74dae30c85431d562b4bf6cbec592aad5d70
66850287022cb5be903052d74bb5c9b1f48581ca
/src/iscript.cpp
945d5c1cc6ead942c9d26dd2189ca9757a8094f5
[ "MIT" ]
permissive
heinermann/teippi
1088586081bd77b34bed077a73954d16f39aaba8
dbcdf65313df1fc1fda8ba1f1d8cf2b9b360db44
refs/heads/master
2020-12-25T10:24:44.380784
2015-09-02T16:03:41
2015-09-02T16:03:41
41,609,412
0
0
null
2015-08-29T22:35:28
2015-08-29T22:35:28
null
UTF-8
C++
false
false
27,024
cpp
#include "iscript.h" #include "offsets.h" #include "image.h" #include "unit.h" #include "bullet.h" #include "rng.h" #include "lofile.h" #include "sprite.h" #include "flingy.h" #include "upgrade.h" #include "warn.h" #include "yms.h" #include "console/assert.h" std::string Iscript::Command::DebugStr() const { switch (opcode) { case IscriptOpcode::PlayFram: return "playfram"; case IscriptOpcode::PlayFramTile: return "playframtile"; case IscriptOpcode::SetHorPos: return "sethorpos"; case IscriptOpcode::SetVertPos: return "setvertpos"; case IscriptOpcode::SetPos: return "setpos"; case IscriptOpcode::Wait: return "wait"; case IscriptOpcode::WaitRand: return "waitrand"; case IscriptOpcode::Goto: return "goto"; case IscriptOpcode::ImgOl: return "imgol"; case IscriptOpcode::ImgUl: return "imgul"; case IscriptOpcode::ImgOlOrig: return "imgolorig"; case IscriptOpcode::SwitchUl: return "switchul"; case IscriptOpcode::UnusedC: return "unusedc"; case IscriptOpcode::ImgOlUseLo: return "imgoluselo"; case IscriptOpcode::ImgUlUseLo: return "imguluselo"; case IscriptOpcode::SprOl: return "sprol"; case IscriptOpcode::HighSprOl: return "highsprol"; case IscriptOpcode::LowSprUl: return "lowsprul"; case IscriptOpcode::UflUnstable: return "uflunstable"; case IscriptOpcode::SprUlUseLo: return "spruluselo"; case IscriptOpcode::SprUl: return "sprul"; case IscriptOpcode::SprOlUseLo: return "sproluselo"; case IscriptOpcode::End: return "end"; case IscriptOpcode::SetFlipState: return "setflipstate"; case IscriptOpcode::PlaySnd: return "playsnd"; case IscriptOpcode::PlaySndRand: return "playsndrand"; case IscriptOpcode::PlaySndBtwn: return "playsndbtwn"; case IscriptOpcode::DoMissileDmg: return "domissiledmg"; case IscriptOpcode::AttackMelee: return "attackmelee"; case IscriptOpcode::FollowMainGraphic: return "followmaingraphic"; case IscriptOpcode::RandCondJmp: return "randcondjmp"; case IscriptOpcode::TurnCcWise: return "turnccwise"; case IscriptOpcode::TurnCWise: return "turncwise"; case IscriptOpcode::Turn1CWise: return "turn1cwise"; case IscriptOpcode::TurnRand: return "turnrand"; case IscriptOpcode::SetSpawnFrame: return "setspawnframe"; case IscriptOpcode::SigOrder: return "sigorder"; case IscriptOpcode::AttackWith: return "attackwith"; case IscriptOpcode::Attack: return "attack"; case IscriptOpcode::CastSpell: return "castspell"; case IscriptOpcode::UseWeapon: return "useweapon"; case IscriptOpcode::Move: return "move"; case IscriptOpcode::GotoRepeatAttk: return "gotorepeatattk"; case IscriptOpcode::EngFrame: return "engframe"; case IscriptOpcode::EngSet: return "engset"; case IscriptOpcode::HideCursorMarker: return "hidecursormarker"; case IscriptOpcode::NoBrkCodeStart: return "nobrkcodestart"; case IscriptOpcode::NoBrkCodeEnd: return "nobrkcodeend"; case IscriptOpcode::IgnoreRest: return "ignorerest"; case IscriptOpcode::AttkShiftProj: return "attkshiftproj"; case IscriptOpcode::TmpRmGraphicStart: return "tmprmgraphicstart"; case IscriptOpcode::TmpRmGraphicEnd: return "tmprmgraphicend"; case IscriptOpcode::SetFlDirect: return "setfldirect"; case IscriptOpcode::Call: return "call"; case IscriptOpcode::Return: return "return"; case IscriptOpcode::SetFlSpeed: return "setflspeed"; case IscriptOpcode::CreateGasOverlays: return "creategasoverlays"; case IscriptOpcode::PwrupCondJmp: return "pwrupcondjmp"; case IscriptOpcode::TrgtRangeCondJmp: return "trgtrangecondjmp"; case IscriptOpcode::TrgtArcCondJmp: return "trgtarccondjmp"; case IscriptOpcode::CurDirectCondJmp: return "curdirectcondjmp"; case IscriptOpcode::ImgUlNextId: return "imgulnextid"; case IscriptOpcode::Unused3e: return "unused3e"; case IscriptOpcode::LiftoffCondJmp: return "liftoffcondjmp"; case IscriptOpcode::WarpOverlay: return "warpoverlay"; case IscriptOpcode::OrderDone: return "orderdone"; case IscriptOpcode::GrdSprOl: return "grdsprol"; case IscriptOpcode::Unused43: return "unused43"; case IscriptOpcode::DoGrdDamage: return "dogrddamage"; default: { char buf[32]; snprintf(buf, sizeof buf, "Unknown (%x)", opcode); return buf; } } } Image *Image::Iscript_AddOverlay(const IscriptContext *ctx, int image_id_, int x, int y, bool above) { Image *img = Allocate(); if (above) { img->list.prev = nullptr; img->list.next = parent->first_overlay; parent->first_overlay->list.prev = img; parent->first_overlay = img; } else { img->list.next = nullptr; img->list.prev = parent->last_overlay; parent->last_overlay->list.next = img; parent->last_overlay = img; } InitializeImageFull(image_id_, img, x, y, parent); if (img->drawfunc == Normal && ctx->unit && ctx->unit->flags & UnitStatus::Hallucination) { if (ctx->unit->CanLocalPlayerControl() || IsReplay()) img->SetDrawFunc(Hallucination, nullptr); } if (img->flags & 0x8) { if (IsFlipped()) SetImageDirection32(img, 32 - direction); else SetImageDirection32(img, direction); } if (img->frame != img->frameset + img->direction) { img->frame = img->frameset + img->direction; img->flags |= 0x1; } if (ctx->unit && ctx->unit->IsInvisible()) { if (images_dat_draw_if_cloaked[img->image_id]) { // Note: main_img may be null if this is some death anim overlay // Related to comment in Image::SingleDelete auto main_img = parent->main_image; if (img->drawfunc == Normal && main_img && main_img->drawfunc >= Cloaking && main_img->drawfunc <= DetectedDecloaking) img->SetDrawFunc(main_img->drawfunc, main_img->drawfunc_param); } else img->Hide(); } return img; } bool Image::IscriptCmd(const Iscript::Command &cmd, IscriptContext *ctx, Rng *rng) { using namespace IscriptOpcode; switch (cmd.opcode) { case PlayFram: if (cmd.val + direction < grp->frame_count) SetFrame(cmd.val); else Warning("Iscript for image %x sets image to invalid frame %x", image_id, cmd.val); break; case PlayFramTile: if (cmd.val + *bw::tileset < grp->frame_count) SetFrame(cmd.val + *bw::tileset); break; case SetHorPos: SetOffset(cmd.point.x, y_off); break; case SetVertPos: if (!ctx->unit || !ctx->unit->IsInvisible()) SetOffset(x_off, cmd.point.y); break; case SetPos: SetOffset(cmd.point.x, cmd.point.y); break; case Wait: iscript.wait = cmd.val - 1; break; case WaitRand: iscript.wait = cmd.val1() + rng->Rand(cmd.val2() - cmd.val1() + 1); break; case ImgOl: case ImgUl: Iscript_AddOverlay(ctx, cmd.val, x_off + cmd.point.x, y_off + cmd.point.y, cmd.opcode == ImgOl); break; case ImgOlOrig: case SwitchUl: { Image *other = Iscript_AddOverlay(ctx, cmd.val, 0, 0, cmd.opcode == ImgOlOrig); if (other && ~other->flags & 0x80) { other->flags |= 0x80; SetOffsetToParentsSpecialOverlay(other); } } break; case ImgOlUseLo: case ImgUlUseLo: { // Yeah, it's not actually point Point32 point = LoFile::GetOverlay(image_id, cmd.point.x).GetValues(this, cmd.point.y); Iscript_AddOverlay(ctx, cmd.val, point.x + x_off, point.y + y_off, cmd.opcode == ImgOlUseLo); } break; case ImgUlNextId: Iscript_AddOverlay(ctx, image_id + 1, cmd.point.x + x_off, cmd.point.y + y_off, false); break; case SprOl: { int sprite_id = cmd.val; if (ctx->bullet && ctx->bullet->parent && ctx->bullet->parent->IsGoliath()) { Unit *goliath = ctx->bullet->parent; if (GetUpgradeLevel(Upgrade::CharonBooster, goliath->player) || (units_dat_flags[goliath->unit_id] & UnitFlags::Hero && *bw::is_bw)) { sprite_id = Sprite::HaloRocketsTrail; } } Sprite::Spawn(this, sprite_id, cmd.point, parent->elevation + 1); } break; case HighSprOl: Sprite::Spawn(this, cmd.val, cmd.point, parent->elevation - 1); break; case LowSprUl: Sprite::Spawn(this, cmd.val, cmd.point, 1); break; case UflUnstable: { Warning("Flingy creation not implemented (image %x)", image_id); /*Flingy *flingy = CreateFlingy(cmd.val, parent->player, cmd.point); if (flingy) { flingy->GiveRandomMoveTarget(rng); flingy->sprite->UpdateVisibilityPoint(); }*/ } break; case SprUlUseLo: case SprUl: { int elevation = parent->elevation; if (cmd.opcode == SprUl) elevation -= 1; if (!ctx->unit || !ctx->unit->IsInvisible() || images_dat_draw_if_cloaked[cmd.val]) { Sprite *sprite = Sprite::Spawn(this, cmd.val, cmd.point, elevation); if (sprite) { if (flags & 0x2) sprite->SetDirection32(32 - direction); else sprite->SetDirection32(direction); } } } break; case SprOlUseLo: { // Again using the "point" for additional storage Point32 point = LoFile::GetOverlay(image_id, cmd.point.x).GetValues(this, 0); Sprite *sprite = Sprite::Spawn(this, cmd.val, point.ToPoint16(), parent->elevation + 1); if (sprite) { if (flags & 0x2) sprite->SetDirection32(32 - direction); else sprite->SetDirection32(direction); } } break; case SetFlipState: SetFlipping(cmd.val); break; case PlaySnd: PlaySoundAtPos(cmd.val, parent->position.AsDword(), 1, 0); break; case PlaySndRand: { int num = rng->Rand(cmd.data[0]); int sound = *(uint16_t *)(cmd.data + 1 + num * 2); PlaySoundAtPos(sound, parent->position.AsDword(), 1, 0); } break; case PlaySndBtwn: { int num = rng->Rand(cmd.val2() - cmd.val1() + 1); PlaySoundAtPos(cmd.val1() + num, parent->position.AsDword(), 1, 0); } break; case FollowMainGraphic: if (parent->main_image) { Image *main_img = parent->main_image; if (main_img->frame != frame || (main_img->flags & 0x2) != (flags & 0x2)) { int new_frame = main_img->frameset + main_img->direction; if (new_frame >= grp->frame_count) Warning("Iscript for image %x requested to play frame %x with followmaingraphic", image_id, new_frame); else { frameset = main_img->frameset; direction = main_img->direction; SetFlipping(main_img->flags & 0x2); UpdateFrameToDirection(); } } } break; case TurnCcWise: case TurnCWise: case Turn1CWise: { Flingy *entity = ctx->unit != nullptr ? (Flingy *)ctx->unit : (Flingy *)ctx->bullet; if (entity == nullptr) { Warning("Iscript for image %x uses turn opcode without parent object", image_id); } else { int direction = 1; if (cmd.opcode == TurnCcWise) direction = 0 - cmd.val; else if (cmd.opcode == TurnCWise) direction = cmd.val; SetDirection(entity, entity->facing_direction + direction * 8); } } break; case SetFlDirect: { Flingy *entity = ctx->unit != nullptr ? (Flingy *)ctx->unit : (Flingy *)ctx->bullet; if (entity == nullptr) { Warning("Iscript for image %x uses setfldirect without parent object", image_id); } else { SetDirection(entity, cmd.val * 8); } } break; case TurnRand: { Flingy *entity = ctx->unit != nullptr ? (Flingy *)ctx->unit : (Flingy *)ctx->bullet; if (entity == nullptr) { Warning("Iscript for image %x uses turnrand without parent object", image_id); } else { int num = rng->Rand(4); if (num == 0) SetDirection(entity, entity->facing_direction - cmd.val * 8); else SetDirection(entity, entity->facing_direction + cmd.val * 8); } } break; case SetSpawnFrame: SetMoveTargetToNearbyPoint(cmd.val, ctx->unit); break; case SigOrder: case OrderDone: { Unit *entity = ctx->unit != nullptr ? ctx->unit : (Unit *)ctx->bullet; if (entity == nullptr) { Warning("Iscript for image %x uses sigorder/orderdone without parent object", image_id); } else { if (cmd.opcode == SigOrder) entity->order_signal |= cmd.val; else entity->order_signal &= ~cmd.val; } } break; case AttackWith: Iscript_AttackWith(ctx->unit, cmd.val); break; case Attack: if (!ctx->unit->target || ctx->unit->target->IsFlying()) Iscript_AttackWith(ctx->unit, 0); else Iscript_AttackWith(ctx->unit, 1); break; case CastSpell: if (orders_dat_targeting_weapon[ctx->unit->order] != Weapon::None && !ShouldStopOrderedSpell(ctx->unit)) FireWeapon(ctx->unit, orders_dat_targeting_weapon[ctx->unit->order]); break; case UseWeapon: Iscript_UseWeapon(cmd.val, ctx->unit); break; case GotoRepeatAttk: if (ctx->unit) ctx->unit->flingy_flags &= ~0x8; break; case EngFrame: frameset = cmd.val; direction = parent->main_image->direction; SetFlipping(parent->main_image->IsFlipped()); UpdateFrameToDirection(); break; case EngSet: frameset = parent->main_image->frameset + parent->main_image->grp->frame_count * cmd.val; direction = parent->main_image->direction; SetFlipping(parent->main_image->IsFlipped()); UpdateFrameToDirection(); break; case HideCursorMarker: *bw::draw_cursor_marker = 0; break; case NoBrkCodeStart: ctx->unit->flags |= UnitStatus::Nobrkcodestart; ctx->unit->sprite->flags |= 0x80; break; case NoBrkCodeEnd: if (ctx->unit) { ctx->unit->flags &= ~UnitStatus::Nobrkcodestart; ctx->unit->sprite->flags &= ~0x80; if (ctx->unit->order_queue_begin && ctx->unit->order_flags & 0x1) { ctx->unit->IscriptToIdle(); ctx->unit->DoNextQueuedOrder(); } } // This actually is feature ._. bunkers can create lone flamethrower sprites // whose default iscript has nobreakcodeend //else //Warning("Iscript for image %x used nobrkcodeend without having unit", image_id); break; case IgnoreRest: if (ctx->unit->target == nullptr) ctx->unit->IscriptToIdle(); else { iscript.wait = 10; iscript.pos -= cmd.Size(); // Loop on this cmd } break; case AttkShiftProj: // Sigh weapons_dat_x_offset[ctx->unit->GetGroundWeapon()] = cmd.val; Iscript_AttackWith(ctx->unit, 1); break; case TmpRmGraphicStart: Hide(); break; case TmpRmGraphicEnd: Show(); break; case SetFlSpeed: ctx->unit->flingy_top_speed = cmd.val; break; case CreateGasOverlays: { Image *img = Allocate(); if (parent->first_overlay == this) { Assert(list.prev == nullptr); parent->first_overlay = img; } img->list.prev = list.prev; img->list.next = this; if (list.prev) list.prev->list.next = img; list.prev = img; int smoke_img = VespeneSmokeOverlay1 + cmd.val; // Bw can be misused to have this check for loaded nuke and such // Even though resource_amount is word, it won't report incorrect values as unit array starts from 0x0059CCA8 // (The lower word is never 0 if the union contains unit) // But with dynamic allocation, that is not the case if (units_dat_flags[ctx->unit->unit_id] & UnitFlags::ResourceContainer) { if (ctx->unit->building.resource.resource_amount == 0) smoke_img = VespeneSmallSmoke1 + cmd.val; } else { if (ctx->unit->building.silo.nuke == nullptr) smoke_img = VespeneSmallSmoke1 + cmd.val; } Point pos = LoFile::GetOverlay(image_id, Overlay::Special).GetValues(this, cmd.val).ToPoint16(); InitializeImageFull(smoke_img, img, pos.x + x_off, pos.y + y_off, parent); } break; case WarpOverlay: flags |= 0x1; drawfunc_param = (void *)cmd.val; break; case GrdSprOl: { int x = parent->position.x + x_off + cmd.point.x; int y = parent->position.y + y_off + cmd.point.y; // Yes, it checks if unit id 0 can fit there if (DoesFitHere(Unit::Marine, x, y)) Sprite::Spawn(this, cmd.val, cmd.point, parent->elevation + 1); } break; default: return false; } return true; } Iscript::Command Iscript::ProgressUntilCommand(const IscriptContext *ctx, Rng *rng) { using namespace IscriptOpcode; Command cmd = Decode(ctx->iscript + pos); pos += cmd.Size(); switch (cmd.opcode) { case Goto: pos = cmd.pos; break; case PwrupCondJmp: if (ctx->img->parent && ctx->img->parent->main_image != ctx->img) pos = cmd.pos; break; case LiftoffCondJmp: if (ctx->unit && ctx->unit->IsFlying()) pos = cmd.pos; break; case TrgtRangeCondJmp: // Bw checks also for !ctx->constant but why should it? if (ctx->unit->target) { uint32_t x, y; GetClosestPointOfTarget(ctx->unit, &x, &y); if (IsPointInArea(ctx->unit, cmd.val, x, y)) pos = cmd.pos; } break; case TrgtArcCondJmp: { // Here would also be if (!ctx->constant) const Point *own = &ctx->unit->sprite->position; const Unit *target = ctx->unit->target; if (target) { int dir = GetFacingDirection(own->x, own->y, target->sprite->position.x, target->sprite->position.y); if (abs(dir - cmd.val1()) < cmd.val2()) pos = cmd.pos; } } break; case CurDirectCondJmp: if (abs(ctx->unit->facing_direction - cmd.val1()) < cmd.val2()) pos = cmd.pos; break; case Call: return_pos = pos; pos = cmd.pos; break; case Return: pos = return_pos; break; case RandCondJmp: if (cmd.val > rng->Rand(256)) pos = cmd.pos; break; default: return cmd; } return ProgressUntilCommand(ctx, rng); } int Iscript::Command::ParamsLength() const { using namespace IscriptOpcode; switch (opcode) { case PlayFram: case PlayFramTile: case SetPos: case WaitRand: case Goto: case ImgOlOrig: case SwitchUl: case UflUnstable: case SetFlSpeed: case PwrupCondJmp: case ImgUlNextId: case LiftoffCondJmp: case PlaySnd: case Call: case WarpOverlay: return 2; case SetHorPos: case SetVertPos: case Wait: case SetFlipState: case TurnCcWise: case TurnCWise: case TurnRand: case SetSpawnFrame: case SigOrder: case AttackWith: case UseWeapon: case Move: case AttkShiftProj: case SetFlDirect: case CreateGasOverlays: case OrderDone: case EngFrame: case EngSet: return 1; case ImgOl: case ImgUl: case ImgUlUseLo: case ImgOlUseLo: case SprOl: case SprUl: case LowSprUl: case HighSprOl: case SprUlUseLo: case PlaySndBtwn: case TrgtRangeCondJmp: case GrdSprOl: return 4; case TrgtArcCondJmp: case CurDirectCondJmp: return 6; case UnusedC: case End: case DoMissileDmg: case FollowMainGraphic: case Turn1CWise: case Attack: case CastSpell: case GotoRepeatAttk: case HideCursorMarker: case NoBrkCodeStart: case NoBrkCodeEnd: case IgnoreRest: case TmpRmGraphicStart: case TmpRmGraphicEnd: case Return: case Unused3e: case Unused43: case DoGrdDamage: return 0; case RandCondJmp: case SprOlUseLo: return 3; case PlaySndRand: case AttackMelee: return 1 + 2 * data[0]; default: return 0; } } Iscript::Command Iscript::Decode(const uint8_t *data) const { Command cmd(data[0]); using namespace IscriptOpcode; switch (cmd.opcode) { case WaitRand: cmd.vals[0] = data[1]; cmd.vals[1] = data[2]; break; case SetPos: case ImgUlNextId: cmd.point.x = *(int8_t *)(data + 1); cmd.point.y = *(int8_t *)(data + 2); break; case PlayFram: case PlayFramTile: case ImgOlOrig: case SwitchUl: case UflUnstable: case PlaySnd: case SetFlSpeed: case WarpOverlay: cmd.val = *(int16_t *)(data + 1); break; case EngFrame: case EngSet: cmd.val = *(uint8_t *)(data + 1); break; case PwrupCondJmp: case LiftoffCondJmp: case Call: case Goto: cmd.pos = *(uint16_t *)(data + 1); break; case SetHorPos: cmd.point = Point(*(int8_t *)(data + 1), 0); break; case SetVertPos: cmd.point = Point(0, *(int8_t *)(data + 1)); break; case Wait: case SetFlipState: case TurnCcWise: case TurnCWise: case TurnRand: case SetSpawnFrame: case SigOrder: case AttackWith: case UseWeapon: case Move: case AttkShiftProj: case SetFlDirect: case OrderDone: cmd.val = data[1]; break; case CreateGasOverlays: cmd.val = *(int8_t *)(data + 1); break; case ImgOl: case ImgUl: case ImgUlUseLo: case ImgOlUseLo: case SprOl: case SprUl: case LowSprUl: case HighSprOl: case SprUlUseLo: case SprOlUseLo: case GrdSprOl: cmd.val = *(uint16_t *)(data + 1); cmd.point.x = *(int8_t *)(data + 3); cmd.point.y = *(int8_t *)(data + 4); break; case PlaySndBtwn: cmd.vals[0] = *(uint16_t *)(data + 1); cmd.vals[1] = *(uint16_t *)(data + 3); break; case TrgtRangeCondJmp: cmd.val = *(uint16_t *)(data + 1); cmd.pos = *(uint16_t *)(data + 3); break; case TrgtArcCondJmp: case CurDirectCondJmp: cmd.vals[0] = *(uint16_t *)(data + 1); cmd.vals[1] = *(uint16_t *)(data + 3); cmd.pos = *(uint16_t *)(data + 5); break; case UnusedC: case End: case DoMissileDmg: case FollowMainGraphic: case Turn1CWise: case Attack: case CastSpell: case GotoRepeatAttk: case HideCursorMarker: case NoBrkCodeStart: case NoBrkCodeEnd: case IgnoreRest: case TmpRmGraphicStart: case TmpRmGraphicEnd: case Return: case Unused3e: case Unused43: break; case DoGrdDamage: cmd.opcode = DoMissileDmg; break; case RandCondJmp: cmd.val = data[1]; cmd.pos = *(uint16_t *)(data + 2); break; case PlaySndRand: case AttackMelee: cmd.data = data + 1; break; default: break; } return cmd; } bool Iscript::GetCommands_C::IgnoreRestCheck(const Iscript::Command &cmd) const { return cmd.opcode == IscriptOpcode::IgnoreRest && ctx->unit->target != nullptr; }
[ "ittevien@gmail.com" ]
ittevien@gmail.com
2642f1e2ac1cea612cc94adc317f4c4decf77229
4c958d966495f7886c89b101f65cf968712139ef
/DNSServer/include/DNSNameserver.h
f599bca974b672555f8f437a683e39f70046af71
[]
no_license
van76007/SecureDNS
94ca27e1aa37f7b6537961ee6293138e8879af51
db8df79c85aa8d5cec94e8c48cfe201ee49f4e33
refs/heads/master
2016-09-06T10:21:21.873168
2015-01-25T08:34:26
2015-01-25T08:34:26
29,673,454
0
1
null
null
null
null
UTF-8
C++
false
false
2,544
h
/** * @file * @author SNU <snu@csis.dk> * @author DCO <dco@csis.dk> * @brief Header file for DNSNamserver * * @section Description * This file contains the definition of DNSNamserver * * */ #ifndef NAMESERVER_DNS_H #define NAMESERVER_DNS_H #include <DNSEntity.h> #include <sys/types.h> #include <stdlib.h> #include <unistd.h> #include <sys/socket.h> #include <netinet/in.h> #include <string.h> #include <netdb.h> #include <stdio.h> #include <iostream> #include <arpa/inet.h> #include <pthread.h> #include <mysql/mysql.h> #include <boost/thread/thread.hpp> #include <time.h> #include <fcntl.h> #include <map> #include <mysql/mysql.h> #include <boost/algorithm/string.hpp> #include <boost/lexical_cast.hpp> #include <vector> //#include "ExceptionHandler.h" #include <stddef.h> #define DNSLENGTH 512 #define PRODUCTION namespace Nameserver { /** * @brief Nameserver * * The Nameserver is a singleton object that on first initialization * will probe and gather various information. This includes: * @section Purpose * To gather and expose various relevant information. * * * @section Limitations * None * */ class DNSNameserver : public DNSEntity { private: /**s * @brief Constructor Private -> singleton * The constructor is called from getInstance. * * @section Pre-conditions * The Constructor has not been called before and no infomation * is available. * @section Post-conditions * The variables is initialized and are exposed. * Or An exception is thrown should some variables be unavailable * * @see getInstance */ /** * @brief A destructor. * A more elaborate description of the destructor. */ /* Disable copy constructor */ DNSNameserver( const DNSNameserver& ){}; int ListenUDP( int main_socket, socklen_t socket_length, struct sockaddr_in server_info, std::vector <int> statusParser); public: DNSNameserver(); ~DNSNameserver(); /** * @brief Get an instance of the DNSNameserver * * * @return DNSNameserver a pointer to the DNSNameserver object. * @see DNSNameserver() */ static DNSNameserver * GetInstance(); int StartNameServer( int local_port, std::string IPAddress, std::vector <int> statusParser ); private: static DNSNameserver* mpsInstance; ///< Pointer to the singleton OTFEStore struct hostent *primary_nameserver; }; }; //namespace Namserver #endif // NAMESERVER_DNS_H
[ "vanvu7609@gmail.com" ]
vanvu7609@gmail.com
a7e38da769f5b1735d4e71e616028c1028a97b10
32db25033ee74e334c7489d0a12b150b0d0f568a
/contests/hackercup-14/round 1/New folder (2)/hackercup_coinsgame.cpp
d4c9bdb4a9c8b733dc056541e769dfdff35dbd00
[ "Apache-2.0" ]
permissive
pandian4github/competitive-programming
cefdea741bbbfae4a77d861c9678afa9c27ceb78
52bee5032f4c5dea47803db392a64b86640ca719
refs/heads/master
2020-05-20T10:47:01.453418
2014-01-18T23:44:01
2014-01-18T23:44:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,028
cpp
#include<stdio.h> //#include<math.h> #include<string.h> #include<stdlib.h> #include<iostream> #include<vector> #include<map> #include<string> #include<set> #include<queue> #include<stack> #include<algorithm> using namespace std; #define fori(a,b) for(i = a; i <= b; i++) #define forj(a,b) for(j = a; j <= b; j++) #define fork(a,b) for(k = a; k <= b; k++) #define scani(a) scanf("%d",&a); #define scanlli(a) scanf("%lld", &a); #define scanc(c) scanf("%c",&c); #define scans(s) scanf("%s", s); #define mp(a,b) make_pair(a, b) #define ll long long int #define vi vector<int> #define vc vector<char> #define vs vector<string> #define println printf("\n"); #define sz(v) v.size() #define len(s) s.length() #define max(a,b) (a > b) ? a : b #define min(a,b) (a < b) ? a : b #define ll(a) (long long int)(a) int main() { int t, i, j, k, minn, eq, rem, tot, n, c, count, flag, tempc, flagadd; scani(t) forj(1, t) { scani(n) scani(k) scani(c) minn = 1000000000; tempc = c; fori(1, n) { //printf("before %d minn : %d\n", i, minn); tempc = c; count = 0; eq = k / i; if(eq == 0) break; rem = k % i; if(i == n && rem != 0) break; tot = i; flagadd = 0; if(rem != 0) { tot++; flagadd = 1; } count = count + n - tot; printf("i : %d eq : %d rem : %d tot : %d count : %d\n", i, eq, rem, tot, count); if(c <= tot) { count = count + c; if(count < minn) minn = count; c = tempc; continue; } count += tot; eq--; rem--; c = c - tot; flag = 0; while(eq > 0 && rem > 0) { if(c > tot) { eq--; rem--; c = c - tot; count += tot; } else { count+=c; flag = 1; break; } } if(flag == 1) { if(count < minn) minn = count; c = tempc; continue; } if(eq == 0) count = count + i + c; else count = count + flagadd + c; if(count < minn) minn = count; c = tempc; } printf("Case #%d: %d\n", j, minn); } return 0; }
[ "pandian4mail@gmail.com" ]
pandian4mail@gmail.com
d4a2341a907b9850d49d2da3fbaf543813494e51
72bf7299e6e3309d15f47e69d2f9c3617a805ff4
/example-thickwireframe/src/testApp.h
383d7dc65b673f411ea08a22a69d979337e34eb9
[ "MIT" ]
permissive
edap/ofxGpuThicklines
4aa8c86804553aab4241d94b413ff38b6ae03563
811af160bf10de648421a67045195425e5593d8b
refs/heads/master
2020-03-17T03:45:46.716440
2017-03-02T16:32:21
2017-03-02T16:32:21
133,249,589
1
0
null
2018-05-13T15:26:38
2018-05-13T15:26:38
null
UTF-8
C++
false
false
669
h
#pragma once #include "ofMain.h" #include "ofxGpuThicklines.h" class testApp : public ofBaseApp{ public: void setup(); void update(); void draw(); void exit(); void keyPressed(int key); void keyReleased(int key); void mouseMoved(int x, int y); void mouseDragged(int x, int y, int button); void mousePressed(int x, int y, int button); void mouseReleased(int x, int y, int button); void windowResized(int w, int h); void dragEvent(ofDragInfo dragInfo); void gotMessage(ofMessage msg); ofMesh sphere; ofxGpuThicklines m_curves; size_t m_mouseIdx; ofEasyCam m_cam; float m_w; float m_h; };
[ "m.rue@picodesign.de" ]
m.rue@picodesign.de
bbb38813316504a47d26e005b17b7e0613260234
d0fb46aecc3b69983e7f6244331a81dff42d9595
/vs/include/alibabacloud/vs/model/DescribePresetsResult.h
6d5ddfd0f76d864a32a04b0e56e8945c963f5ea3
[ "Apache-2.0" ]
permissive
aliyun/aliyun-openapi-cpp-sdk
3d8d051d44ad00753a429817dd03957614c0c66a
e862bd03c844bcb7ccaa90571bceaa2802c7f135
refs/heads/master
2023-08-29T11:54:00.525102
2023-08-29T03:32:48
2023-08-29T03:32:48
115,379,460
104
82
NOASSERTION
2023-09-14T06:13:33
2017-12-26T02:53:27
C++
UTF-8
C++
false
false
1,507
h
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef ALIBABACLOUD_VS_MODEL_DESCRIBEPRESETSRESULT_H_ #define ALIBABACLOUD_VS_MODEL_DESCRIBEPRESETSRESULT_H_ #include <string> #include <vector> #include <utility> #include <alibabacloud/core/ServiceResult.h> #include <alibabacloud/vs/VsExport.h> namespace AlibabaCloud { namespace Vs { namespace Model { class ALIBABACLOUD_VS_EXPORT DescribePresetsResult : public ServiceResult { public: struct Preset { std::string id; std::string name; }; DescribePresetsResult(); explicit DescribePresetsResult(const std::string &payload); ~DescribePresetsResult(); std::vector<Preset> getPresets()const; std::string getId()const; protected: void parse(const std::string &payload); private: std::vector<Preset> presets_; std::string id_; }; } } } #endif // !ALIBABACLOUD_VS_MODEL_DESCRIBEPRESETSRESULT_H_
[ "sdk-team@alibabacloud.com" ]
sdk-team@alibabacloud.com
340a12dac15189e3498914701885d0d82eeb0676
ec7796aa677b2fb2637d500eceabadabe0d377d5
/맵툴/iniTestScene.cpp
a01e16c15e3646badbc4a218cbffd775526e4663
[]
no_license
Seokhwan-choi/MapTool
185e7cfce3beee9355919fb10018ab0784f49f8a
20c1edde1b73a7d7ac42aa55f1269a92747afb6b
refs/heads/master
2020-05-02T07:21:26.794130
2019-03-26T15:24:41
2019-03-26T15:24:41
177,815,830
0
0
null
null
null
null
UHC
C++
false
false
815
cpp
#include "stdafx.h" #include "iniTestScene.h" HRESULT iniTestScene::init(void) { return S_OK; } void iniTestScene::release(void) { } void iniTestScene::update(void) { if (KEYMANAGER->isOnceKeyDown(VK_LBUTTON)) { //섹션, 키, 밸류 //[플밍12기] //동현=100 //우현=90 //지연=80 //... INIDATA->addData("플밍12기", "동현", "100.5"); INIDATA->addData("플밍12기", "우현", "90"); INIDATA->addData("플밍12기", "지연", "80"); //파일이름으로 세이브 INIDATA->saveINI("플밍플밍"); } if (KEYMANAGER->isOnceKeyDown(VK_RBUTTON)) { int num = INIDATA->loadDataInteger("플밍플밍", "플밍12기", "동현"); //float num = INIDATA->loadDataFloat("플밍플밍", "플밍12기", "동현"); cout << num << endl; } } void iniTestScene::render(void) { }
[ "choiseok35@nate.com" ]
choiseok35@nate.com
1263ef0c7606175299f3dbf7a116c70435a2f015
68e8f6bf9ea4f5c2b1e5c99b61911b69c546db60
/include/REL/Relocation.h
b62ebe1b6c7e99724cd9747f58297a5df3eeb960
[ "MIT" ]
permissive
FruitsBerriesMelons123/CommonLibSSE
aaa2d4cd66d39f7cb4d25f076735ef4b0187353e
7ae21d11b9e9c86b0596fc1cfa58b6993a568125
refs/heads/master
2021-01-16T12:36:20.612433
2020-02-25T09:58:05
2020-02-25T09:58:05
243,124,317
0
0
MIT
2020-02-25T23:24:47
2020-02-25T23:24:47
null
UTF-8
C++
false
false
21,906
h
#pragma once #include <array> #include <cassert> #include <cstdint> #include <exception> #include <functional> #include <istream> #include <string> #include <string_view> #include <type_traits> #include <unordered_map> #include <variant> #include <vector> #include "SKSE/SafeWrite.h" #include "SKSE/Version.h" namespace RE { namespace RTTI { struct CompleteObjectLocator; struct TypeDescriptor; } } namespace REL { namespace Impl { // msvc's safety checks increase debug builds' execution time by several orders of magnitude // so i've introduced this class to speed up debug builds which leverage exe scanning template <class T> class Array { public: using value_type = T; using size_type = std::size_t; using reference = value_type&; using const_reference = const value_type&; using pointer = value_type*; Array() = delete; Array(size_type a_size) : _data(0), _size(a_size), _owned(true) { _data = new value_type[_size]; } Array(pointer a_data, size_type a_size) : _data(a_data), _size(a_size), _owned(false) {} Array(const std::vector<value_type>& a_vec) : _data(0), _size(0), _owned(true) { _size = a_vec.size(); _data = new value_type[_size]; for (size_type i = 0; i < _size; ++i) { _data[i] = a_vec[i]; } } ~Array() { if (_owned) { delete[] _data; } } reference operator[](size_type a_pos) { return _data[a_pos]; } const_reference operator[](size_type a_pos) const { return _data[a_pos]; } size_type size() const { return _size; } private: pointer _data; size_type _size; bool _owned; }; // https://en.wikipedia.org/wiki/Knuth-Morris-Pratt_algorithm constexpr auto NPOS = static_cast<std::size_t>(-1); void kmp_table(const Array<std::uint8_t>& W, Array<std::size_t>& T); void kmp_table(const Array<std::uint8_t>& W, const Array<bool>& M, Array<std::size_t>& T); std::size_t kmp_search(const Array<std::uint8_t>& S, const Array<std::uint8_t>& W); std::size_t kmp_search(const Array<std::uint8_t>& S, const Array<std::uint8_t>& W, const Array<bool>& M); template <class T> struct is_any_function : std::disjunction< std::is_function<T>, std::is_function<std::remove_pointer_t<T>>, // is_function_pointer std::is_member_function_pointer<T>> {}; // https://docs.microsoft.com/en-us/cpp/build/x64-calling-convention template <class T, class Enable = void> struct meets_length_req : std::false_type {}; template <class T> struct meets_length_req<T, std::enable_if_t<sizeof(T) == 1>> : std::true_type {}; template <class T> struct meets_length_req<T, std::enable_if_t<sizeof(T) == 2>> : std::true_type {}; template <class T> struct meets_length_req<T, std::enable_if_t<sizeof(T) == 4>> : std::true_type {}; template <class T> struct meets_length_req<T, std::enable_if_t<sizeof(T) == 8>> : std::true_type {}; template <class T> struct meets_length_req<T, std::enable_if_t<sizeof(T) == 16>> : std::true_type {}; template <class T> struct meets_length_req<T, std::enable_if_t<sizeof(T) == 32>> : std::true_type {}; template <class T> struct meets_length_req<T, std::enable_if_t<sizeof(T) == 64>> : std::true_type {}; template <class T> struct meets_function_req : std::conjunction< std::is_trivially_constructible<T>, std::is_trivially_destructible<T>, std::is_trivially_copy_assignable<T>, std::negation<std::is_polymorphic<T>>> {}; template <class T> struct meets_member_req : std::is_standard_layout<T> {}; template <class T, class Enable = void> struct is_msvc_pod : std::true_type {}; template <class T> struct is_msvc_pod<T, std::enable_if_t<std::is_union<T>::value>> : std::false_type {}; template <class T> struct is_msvc_pod<T, std::enable_if_t<std::is_class<T>::value>> : std::conjunction< meets_length_req<T>, meets_function_req<T>, meets_member_req<T>> {}; template <class F> struct member_function_pod; // normal template <class R, class Cls, class... Args> struct member_function_pod<R(Cls::*)(Args...)> { using type = R(Cls*, Args...); }; // const template <class R, class Cls, class... Args> struct member_function_pod<R(Cls::*)(Args...) const> { using type = R(const Cls*, Args...); }; // variadic template <class R, class Cls, class... Args> struct member_function_pod<R(Cls::*)(Args..., ...)> { using type = R(Cls*, Args..., ...); }; // variadic const template <class R, class Cls, class... Args> struct member_function_pod<R(Cls::*)(Args..., ...) const> { using type = R(const Cls*, Args..., ...); }; template <class F> using member_function_pod_t = typename member_function_pod<F>::type; template <class F> struct member_function_non_pod; // normal template <class R, class Cls, class... Args> struct member_function_non_pod<R(Cls::*)(Args...)> { using type = R&(Cls*, void*, Args...); }; // normal const template <class R, class Cls, class... Args> struct member_function_non_pod<R(Cls::*)(Args...) const> { using type = R&(const Cls*, void*, Args...); }; // variadic template <class R, class Cls, class... Args> struct member_function_non_pod<R(Cls::*)(Args..., ...)> { using type = R&(Cls*, void*, Args..., ...); }; // variadic const template <class R, class Cls, class... Args> struct member_function_non_pod<R(Cls::*)(Args..., ...) const> { using type = R&(const Cls*, void*, Args..., ...); }; template <class F> using member_function_non_pod_t = typename member_function_non_pod<F>::type; template <class R, class F, class... Args> R InvokeMemberFunctionPOD(F&& a_fn, Args&&... a_args) { using NF = member_function_pod_t<std::decay_t<F>>; auto func = unrestricted_cast<NF*>(a_fn); return func(std::forward<Args>(a_args)...); } // return by value on a non-pod type means caller allocates space for the object // and passes it in rcx, unless its a member function, in which case it passes in rdx // all other arguments shift over to compensate template <class R, class F, class T1, class... Args> R InvokeMemberFunctionNonPOD(F&& a_fn, T1&& a_object, Args&&... a_args) { using NF = member_function_non_pod_t<std::decay_t<F>>; auto func = unrestricted_cast<NF*>(a_fn); std::aligned_storage_t<sizeof(R), alignof(R)> result; return func(std::forward<T1>(a_object), &result, std::forward<Args>(a_args)...); } template <class R, class F, class... Args> R Invoke(F&& a_fn, Args&&... a_args) { if constexpr (std::is_member_function_pointer<std::decay_t<F>>::value) { // the compiler chokes on member functions if constexpr (Impl::is_msvc_pod<R>::value) { // no need to shift if it's a pod type return InvokeMemberFunctionPOD<R>(std::forward<F>(a_fn), std::forward<Args>(a_args)...); } else { return InvokeMemberFunctionNonPOD<R>(std::forward<F>(a_fn), std::forward<Args>(a_args)...); } } else { return a_fn(std::forward<Args>(a_args)...); } } } // generic solution for calling relocated functions template <class F, class... Args, typename std::enable_if_t<std::is_invocable<F, Args...>::value, int> = 0> decltype(auto) Invoke(F&& a_fn, Args&&... a_args) { return Impl::Invoke<std::invoke_result_t<F, Args...>>(std::forward<F>(a_fn), std::forward<Args>(a_args)...); } class Module { public: struct IDs { enum ID { kTextX, kIData, kRData, kData, kPData, kTLS, kTextW, kGFIDs, kTotal }; }; using ID = IDs::ID; class Section { public: constexpr Section() : addr(0xDEADBEEF), size(0xDEADBEEF), rva(0xDEADBEEF) {} std::uint32_t RVA() const; std::uintptr_t BaseAddr() const; std::size_t Size() const; template <class T = void> inline T* BasePtr() const { return reinterpret_cast<T*>(BaseAddr()); } protected: friend class Module; std::uintptr_t addr; std::size_t size; std::uint32_t rva; }; static std::uintptr_t BaseAddr(); static std::size_t Size(); static Section GetSection(ID a_id); static SKSE::Version GetVersion() noexcept; template <class T = void> inline static T* BasePtr() { return reinterpret_cast<T*>(_info.base); } private: struct ModuleInfo { public: struct Sections { struct Elem { constexpr Elem(const char* a_name) : Elem(a_name, 0) {} constexpr Elem(const char* a_name, DWORD a_flags) : name(std::move(a_name)), section(), flags(a_flags) {} std::string_view name; Section section; DWORD flags; }; constexpr Sections() : arr{ Elem(".text", static_cast<DWORD>(IMAGE_SCN_MEM_EXECUTE)), ".idata", ".rdata", ".data", ".pdata", ".tls", Elem(".text", static_cast<DWORD>(IMAGE_SCN_MEM_WRITE)), ".gfids" } {} std::array<Elem, ID::kTotal> arr; }; ModuleInfo(); HMODULE handle; std::uintptr_t base; std::size_t size; Sections sections; SKSE::Version version; private: void BuildVersionInfo(); }; static ModuleInfo _info; }; class IDDatabase { public: [[nodiscard]] static bool Init(); #ifdef _DEBUG [[nodiscard]] static std::uint64_t OffsetToID(std::uint64_t a_address); #endif [[nodiscard]] static std::uint64_t IDToOffset(std::uint64_t a_id); private: IDDatabase() = delete; IDDatabase(const IDDatabase&) = delete; IDDatabase(IDDatabase&&) = delete; IDDatabase& operator=(const IDDatabase&) = delete; IDDatabase& operator=(IDDatabase&&) = delete; class IDDatabaseImpl { public: [[nodiscard]] bool Load(); [[nodiscard]] bool Load(std::uint16_t a_major, std::uint16_t a_minor, std::uint16_t a_revision, std::uint16_t a_build); [[nodiscard]] bool Load(SKSE::Version a_version); #ifdef _DEBUG [[nodiscard]] std::uint64_t OffsetToID(std::uint64_t a_address); #endif [[nodiscard]] std::uint64_t IDToOffset(std::uint64_t a_id); private: class IStream { public: using stream_type = std::istream; using pointer = stream_type*; using const_pointer = const stream_type*; using reference = stream_type&; using const_reference = const stream_type&; constexpr IStream(stream_type& a_stream) : _stream(a_stream) {} [[nodiscard]] constexpr reference operator*() noexcept { return _stream; } [[nodiscard]] constexpr const_reference operator*() const noexcept { return _stream; } [[nodiscard]] constexpr pointer operator->() noexcept { return std::addressof(_stream); } [[nodiscard]] constexpr const_pointer operator->() const noexcept { return std::addressof(_stream); } template <class T> inline void readin(T& a_val) { _stream.read(reinterpret_cast<char*>(std::addressof(a_val)), sizeof(T)); } template <class T, typename std::enable_if_t<std::is_arithmetic_v<T>, int> = 0> inline T readout() { T val; readin(val); return val; } private: stream_type& _stream; }; class Header { public: inline Header() noexcept : _exeName(), _part1(), _part2() {} void Read(IStream& a_input); [[nodiscard]] constexpr decltype(auto) AddrCount() const noexcept { return static_cast<std::size_t>(_part2.addressCount); } [[nodiscard]] constexpr decltype(auto) PSize() const noexcept { return static_cast<std::uint64_t>(_part2.pointerSize); } [[nodiscard]] inline decltype(auto) GetVersion() const { return SKSE::Version(_part1.version); } private: struct Part1 { constexpr Part1() : format(0), version{ 0 }, nameLen(0) {} void Read(IStream& a_input); std::int32_t format; std::int32_t version[4]; std::int32_t nameLen; }; struct Part2 { constexpr Part2() : pointerSize(0), addressCount(0) {} void Read(IStream& a_input); std::int32_t pointerSize; std::int32_t addressCount; }; std::string _exeName; Part1 _part1; Part2 _part2; }; [[nodiscard]] bool DoLoad(IStream& a_input); void DoLoadImpl(IStream& a_input, Header& a_header); std::vector<std::uint64_t> _offsets; #ifdef _DEBUG std::unordered_map<std::uint64_t, std::uint64_t> _ids; #endif }; static IDDatabaseImpl _db; }; // converts an id within the database to its equivalent offset class ID { public: constexpr ID() noexcept : ID(static_cast<std::uint64_t>(0)) {} explicit constexpr ID(std::uint64_t a_id) noexcept : _id(a_id) {} constexpr ID& operator=(std::uint64_t a_id) noexcept { _id = a_id; return *this; } [[nodiscard]] std::uint64_t operator*() const; [[nodiscard]] std::uint64_t GetOffset() const; private: std::uint64_t _id; }; // relocates the given offset in the exe and reinterprets it as the given type template <class T> class Offset { public: using value_type = T; Offset() = delete; constexpr Offset(std::uintptr_t a_offset) : _impl(a_offset) {} explicit constexpr Offset(ID a_id) : Offset(std::move(a_id), 0) {} constexpr Offset(ID a_id, std::size_t a_mod) : _impl(std::make_pair(a_id, a_mod)) {} template <class U = T, typename std::enable_if_t<std::is_pointer<U>::value, int> = 0> std::add_lvalue_reference_t<std::remove_pointer_t<U>> operator*() { return *GetType(); } template <class U = T, typename std::enable_if_t<std::is_pointer<U>::value, int> = 0> U operator->() { return GetType(); } template <class... Args, class F = T, typename std::enable_if_t<std::is_invocable<F, Args...>::value, int> = 0> decltype(auto) operator()(Args&&... a_args) { return Invoke(GetType(), std::forward<Args>(a_args)...); } value_type GetType() { return unrestricted_cast<value_type>(GetAddress()); } std::uintptr_t GetAddress() { switch (_impl.index()) { case kID: _impl = *std::get<kID>(_impl).first + std::get<kID>(_impl).second; break; } return Module::BaseAddr() + std::get<kRaw>(_impl); } std::uintptr_t GetOffset() { return GetAddress() - Module::BaseAddr(); } template <class U = T, typename std::enable_if_t<std::is_same<U, std::uintptr_t>::value, int> = 0> std::uintptr_t WriteVFunc(std::size_t a_idx, std::uintptr_t a_newFunc) { constexpr auto PSIZE = sizeof(void*); auto addr = GetAddress() + (PSIZE * a_idx); auto result = *reinterpret_cast<std::uintptr_t*>(addr); SKSE::SafeWrite64(addr, a_newFunc); return result; } template <class F, class U = T, typename std::enable_if_t<std::is_same<U, std::uintptr_t>::value, int> = 0> std::uintptr_t WriteVFunc(std::size_t a_idx, F a_newFunc) { return WriteVFunc(a_idx, unrestricted_cast<std::uintptr_t>(a_newFunc)); } private: enum : std::size_t { kRaw, kID }; std::variant<std::uintptr_t, std::pair<ID, std::size_t>> _impl; }; // pattern scans exe for given sig // sig must be an ida pattern, and must be unique (first found match is returned) template <class T> class DirectSig { public: using value_type = T; DirectSig() = delete; DirectSig(const char* a_sig) : _address(0xDEADBEEF) { std::vector<std::uint8_t> sig; std::vector<bool> mask; std::string buf; buf.resize(2); for (std::size_t i = 0; a_sig[i] != '\0';) { switch (a_sig[i]) { case ' ': ++i; break; case '?': mask.push_back(false); sig.push_back(0x00); do { ++i; } while (a_sig[i] == '?'); break; default: mask.push_back(true); buf[0] = a_sig[i++]; buf[1] = a_sig[i++]; sig.push_back(static_cast<std::uint8_t>(std::stoi(buf, 0, 16))); break; } } auto text = Module::GetSection(Module::ID::kTextX); Impl::Array<std::uint8_t> haystack(text.BasePtr<std::uint8_t>(), text.Size()); Impl::Array<std::uint8_t> needle(sig.data(), sig.size()); Impl::Array<bool> needleMask(mask); _address = Impl::kmp_search(haystack, needle, needleMask); if (_address == 0xDEADBEEF) { assert(false); // sig scan failed } else { _address += text.BaseAddr(); } } template <class U = T, typename std::enable_if_t<std::is_pointer<U>::value, int> = 0> std::add_lvalue_reference_t<std::remove_pointer_t<U>> operator*() const { return *GetType(); } template <class U = T, typename std::enable_if_t<std::is_pointer<U>::value, int> = 0> U operator->() const { return GetType(); } template <class... Args, class F = T, typename std::enable_if_t<std::is_invocable<F, Args...>::value, int> = 0> decltype(auto) operator()(Args&&... a_args) const { return Invoke(GetType(), std::forward<Args>(a_args)...); } value_type GetType() const { return unrestricted_cast<value_type>(GetAddress()); } std::uintptr_t GetAddress() const { assert(_address != 0xDEADBEEF); return _address; } std::uintptr_t GetOffset() const { return GetAddress() - Module::BaseAddr(); } protected: mutable std::uintptr_t _address; }; // pattern scans exe for given sig, reads offset from first opcode, and calculates effective address from next op code template <class T> class IndirectSig : public DirectSig<T> { public: IndirectSig() = delete; IndirectSig(const char* a_sig) : DirectSig<T>(a_sig) { auto offset = reinterpret_cast<std::int32_t*>(_address + 1); auto nextOp = _address + 5; _address = nextOp + *offset; } protected: using Base = DirectSig<T>; using Base::_address; }; // scans exe for type descriptor name, then retrieves vtbl address at specified offset class VTable { public: VTable() = delete; VTable(const char* a_name, std::uint32_t a_offset = 0); void* GetPtr() const; std::uintptr_t GetAddress() const; std::uintptr_t GetOffset() const; private: using ID = Module::ID; RE::RTTI::TypeDescriptor* LocateTypeDescriptor(const char* a_name) const; RE::RTTI::CompleteObjectLocator* LocateCOL(RE::RTTI::TypeDescriptor* a_typeDesc, std::uint32_t a_offset) const; void* LocateVtbl(RE::RTTI::CompleteObjectLocator* a_col) const; std::uintptr_t _address; }; template <class, class = void> class Function; template <class T> class Function<T, std::enable_if_t<Impl::is_any_function<std::decay_t<T>>::value>> { public: using function_type = std::decay_t<T>; constexpr Function() : _storage() {} Function(const Function& a_rhs) : _storage(a_rhs._storage) {} Function(Function&& a_rhs) : _storage(std::move(a_rhs._storage)) {} explicit Function(const function_type& a_rhs) : _storage(a_rhs) {} explicit Function(function_type&& a_rhs) : _storage(std::move(a_rhs)) {} explicit Function(std::uintptr_t a_rhs) : _storage(a_rhs) {} explicit Function(const Offset<function_type>& a_rhs) : _storage(a_rhs.GetType()) {} explicit Function(const Offset<std::uintptr_t>& a_rhs) : _storage(a_rhs.GetAddress()) {} Function& operator=(const Function& a_rhs) { if (this == &a_rhs) { return *this; } _storage = a_rhs._storage; return *this; } Function& operator=(Function&& a_rhs) { if (this == &a_rhs) { return *this; } _storage = std::move(a_rhs._storage); return *this; } Function& operator=(const function_type& a_rhs) { _storage = a_rhs; return *this; } Function& operator=(function_type&& a_rhs) { _storage = std::move(a_rhs); return *this; } Function& operator=(std::uintptr_t a_rhs) { _storage = a_rhs; return *this; } Function& operator=(const Offset<function_type>& a_rhs) { _storage = a_rhs.GetAddress(); return *this; } Function& operator=(const Offset<std::uintptr_t>& a_rhs) { _storage = a_rhs.GetAddress(); return *this; } [[nodiscard]] explicit operator bool() const noexcept { return !Empty(); } template <class... Args, class F = function_type, typename std::enable_if_t<std::is_invocable<F, Args...>::value, int> = 0> std::invoke_result_t<F, Args...> operator()(Args&&... a_args) const { assert(InRange()); if (Empty()) { throw std::bad_function_call(); } return Invoke(_storage.func, std::forward<Args>(a_args)...); } private: enum : std::uintptr_t { kEmpty = 0 }; [[nodiscard]] bool Empty() const noexcept { return _storage.address == kEmpty; } [[nodiscard]] bool InRange() const noexcept { auto xText = Module::GetSection(Module::ID::kTextX); return xText.BaseAddr() <= _storage.address && _storage.address < xText.BaseAddr() + xText.Size(); } union Storage { constexpr Storage() : address(kEmpty) {} Storage(const Storage& a_rhs) : func(a_rhs.func) {} Storage(Storage&& a_rhs) : func(std::move(a_rhs.func)) { a_rhs.address = kEmpty; } explicit Storage(const function_type& a_rhs) : func(a_rhs) {} explicit Storage(function_type&& a_rhs) : func(std::move(a_rhs)) {} explicit Storage(std::uintptr_t a_rhs) : address(a_rhs) {} Storage& operator=(const Storage& a_rhs) { if (this == &a_rhs) { return *this; } func = a_rhs.func; return *this; } Storage& operator=(Storage&& a_rhs) { if (this == &a_rhs) { return *this; } func = std::move(a_rhs.func); a_rhs.address = kEmpty; return *this; } Storage& operator=(const function_type& a_rhs) { func = a_rhs; return *this; } Storage& operator=(function_type&& a_rhs) { func = std::move(a_rhs); return *this; } Storage& operator=(std::uintptr_t a_rhs) { address = a_rhs; return *this; } function_type func; std::uintptr_t address; }; Storage _storage; }; }
[ "ryan__mckenzie@hotmail.com" ]
ryan__mckenzie@hotmail.com
15a9b885217d14219be546b076e330579e6d811b
8569e94b7d9e30e0d9cfa61ad0c55578dd8182b0
/3rdparty/lzma/CPP/7zip/Compress/PpmdDecoder.h
3c2f4934972199260638970b83036137a6d288bd
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
Crisspl/IrrlichtBAW
443e542008fda0ce4810be64525ff9c064f2a2fe
a4502c6c453b2ebf260e1583b1328f686289aca8
refs/heads/master
2021-06-07T20:38:48.162430
2019-09-03T17:39:50
2019-09-03T17:39:50
118,658,221
5
3
Apache-2.0
2020-11-26T10:55:10
2018-01-23T19:26:21
C++
UTF-8
C++
false
false
2,195
h
// PpmdDecoder.h // 2009-03-11 : Igor Pavlov : Public domain #ifndef __COMPRESS_PPMD_DECODER_H #define __COMPRESS_PPMD_DECODER_H #include "../../../C/Ppmd7.h" #include "../../Common/MyCom.h" #include "../Common/CWrappers.h" #include "../ICoder.h" namespace NCompress { namespace NPpmd { class CDecoder : public ICompressCoder, public ICompressSetDecoderProperties2, public ICompressGetInStreamProcessedSize, #ifndef NO_READ_FROM_CODER public ICompressSetInStream, public ICompressSetOutStreamSize, public ISequentialInStream, #endif public CMyUnknownImp { Byte *_outBuf; CPpmd7z_RangeDec _rangeDec; CByteInBufWrap _inStream; CPpmd7 _ppmd; Byte _order; bool _outSizeDefined; int _status; UInt64 _outSize; UInt64 _processedSize; HRESULT CodeSpec(Byte *memStream, UInt32 size); public: #ifndef NO_READ_FROM_CODER CMyComPtr<ISequentialInStream> InSeqStream; #endif MY_QUERYINTERFACE_BEGIN2(ICompressCoder) MY_QUERYINTERFACE_ENTRY(ICompressSetDecoderProperties2) // MY_QUERYINTERFACE_ENTRY(ICompressSetFinishMode) MY_QUERYINTERFACE_ENTRY(ICompressGetInStreamProcessedSize) #ifndef NO_READ_FROM_CODER MY_QUERYINTERFACE_ENTRY(ICompressSetInStream) MY_QUERYINTERFACE_ENTRY(ICompressSetOutStreamSize) MY_QUERYINTERFACE_ENTRY(ISequentialInStream) #endif MY_QUERYINTERFACE_END MY_ADDREF_RELEASE STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream, const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress); STDMETHOD(SetDecoderProperties2)(const Byte *data, UInt32 size); STDMETHOD(GetInStreamProcessedSize)(UInt64 *value); STDMETHOD(SetOutStreamSize)(const UInt64 *outSize); #ifndef NO_READ_FROM_CODER STDMETHOD(SetInStream)(ISequentialInStream *inStream); STDMETHOD(ReleaseInStream)(); STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize); #endif CDecoder(): _outBuf(NULL), _outSizeDefined(false) { Ppmd7z_RangeDec_CreateVTable(&_rangeDec); _rangeDec.Stream = &_inStream.vt; Ppmd7_Construct(&_ppmd); } ~CDecoder(); }; }} #endif
[ "devsh.graphicsprogramming@gmail.com" ]
devsh.graphicsprogramming@gmail.com
ca16a7ee036555da4c859e511bf08c774928a439
587aaf4e7844a61f1e292009aae587053e6cb6a8
/Sources/InforSearch/Book4Times.h
1239ff9d7abacbf5b0c388a1b7c7cb9b31413b0f
[]
no_license
25311753/runshun_2008r2
15cd7eba2bec1661fb3749bc76539d5f2f2ef953
c069f00913eec20acf215da26121df3e3da8d3f1
refs/heads/master
2021-01-10T22:01:46.990290
2014-07-19T16:08:22
2014-07-19T16:08:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,322
h
//--------------------------------------------------------------------------- #ifndef Book4TimesH #define Book4TimesH //--------------------------------------------------------------------------- #include <Classes.hpp> #include <Controls.hpp> #include <StdCtrls.hpp> #include <Forms.hpp> #include <ComCtrls.hpp> //--------------------------------------------------------------------------- class TBook4TimesForm : public TForm { __published: // IDE-managed Components TLabel *Label1; TListView *lstView; TLabel *Label2; TEdit *edtDate0; TLabel *Label3; TEdit *edtDate1; TButton *btnQuery; TButton *btnToExcel; TButton *btnExit; TLabel *Label4; TComboBox *lstCorp; TLabel *Label5; TComboBox *lstDepart; TLabel *Label6; TEdit *edtTimes; void __fastcall btnExitClick(TObject *Sender); void __fastcall btnToExcelClick(TObject *Sender); void __fastcall btnQueryClick(TObject *Sender); void __fastcall FormShow(TObject *Sender); private: // User declarations CStringArray m_lstCorpID; CStringArray m_lstDepartID; public: // User declarations __fastcall TBook4TimesForm(TComponent* Owner); }; //--------------------------------------------------------------------------- extern PACKAGE TBook4TimesForm *Book4TimesForm; //--------------------------------------------------------------------------- #endif
[ "25311753@qq.com" ]
25311753@qq.com
4471abd16789fff3d9769d851f0fc031a09b60b1
b367fe5f0c2c50846b002b59472c50453e1629bc
/xbox_leak_may_2020/xbox trunk/xbox/private/windows/directx/dsound/tools/dspbuilder/dspbuilder.h
4dbc7e8cfdecc55559159aae5583b6cbccb8e12c
[]
no_license
sgzwiz/xbox_leak_may_2020
11b441502a659c8da8a1aa199f89f6236dd59325
fd00b4b3b2abb1ea6ef9ac64b755419741a3af00
refs/heads/master
2022-12-23T16:14:54.706755
2020-09-27T18:24:48
2020-09-27T18:24:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,061
h
/*++ Copyright (c) 2001 Microsoft Corporation Module Name: dspbuilder.h Abstract: Main head file Author: Robert Heitkamp (robheit) 08-Oct-2001 Revision History: 08-Oct-2001 robheit Initial Version --*/ #if !defined(AFX_DSPBUILDER_H__A4399BA9_E747_41EE_86C6_5881A0DA3E7E__INCLUDED_) #define AFX_DSPBUILDER_H__A4399BA9_E747_41EE_86C6_5881A0DA3E7E__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 //------------------------------------------------------------------------------ // Includes: //------------------------------------------------------------------------------ #include <afxwin.h> // MFC core and standard components #include <afxcmn.h> #include <afxext.h> // MFC extensions #include <afxdisp.h> // MFC Automation classes #include <afxdtctl.h> // MFC support for Internet Explorer 4 Common Controls #include "xboxverp.h" #include <stdio.h> #include <stdlib.h> #include "xboxdbg.h" #include "dsfxparmp.h" #include "parser.h" #include "..\inc\dsp.h" #include "..\inc\cipher.h" #include "resource.h" // main symbols //------------------------------------------------------------------------------ // Globals Defines: //------------------------------------------------------------------------------ #define MAX_SIZE 65535 #define SCALE 13 //------------------------------------------------------------------------------ // Globals Macros: //------------------------------------------------------------------------------ #define MAX(a,b) (((a) >= (b)) ? (a) : (b)) #define MIN(a,b) (((a) <= (b)) ? (a) : (b)) #define MEDIAN(a,b) (((a) <= (b)) ? (((b) - (a)) / 2 + (a)) : (((a) - (b)) / 2 + (b))) //------------------------------------------------------------------------------ // Globals Methods //------------------------------------------------------------------------------ inline BOOL IsPointInRect(int x, int y, const CRect& r) { return ((x >= r.left) && (x <= r.right) && (y >= r.top) && (y <= r.bottom)); }; //------------------------------------------------------------------------------ // CDspbuilderApp //------------------------------------------------------------------------------ class CDspbuilderApp : public CWinApp { public: CDspbuilderApp(); // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CDspbuilderApp) public: virtual BOOL InitInstance(); //}}AFX_VIRTUAL // Implementation public: //{{AFX_MSG(CDspbuilderApp) afx_msg void OnAppAbout(); // NOTE - the ClassWizard will add and remove member functions here. // DO NOT EDIT what you see in these blocks of generated code ! //}}AFX_MSG DECLARE_MESSAGE_MAP() }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_DSPBUILDER_H__A4399BA9_E747_41EE_86C6_5881A0DA3E7E__INCLUDED_)
[ "benjamin.barratt@icloud.com" ]
benjamin.barratt@icloud.com
046156790c71946de94470c7f1cd5acd0e07e278
a8fc203e20f71c28067d1ce550a44b418637d7ed
/src/test/unicode.cpp
d491c69f4d5b2a055a9d98cc8124242d5bb25b74
[]
no_license
SonnyX/jessilib
491641105a40ea9a58e758f8bd4eb81b0947f6c6
22f81473ba2cb6a1172dba4ba0d42fb23b1839fd
refs/heads/master
2022-12-14T17:08:06.565179
2020-09-15T06:16:56
2020-09-15T06:16:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,251
cpp
/** * Copyright (C) 2018 Jessica James. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * * Written by Jessica James <jessica.aj@outlook.com> */ #include "unicode.hpp" #include "test.hpp" using namespace jessilib; using namespace std::literals; /** encode_codepoint */ TEST(UTF8Test, encode_codepoint) { EXPECT_EQ(encode_codepoint_u8(U'\0'), u8"\0"sv); EXPECT_EQ(encode_codepoint_u8(U'A'), u8"A"sv); EXPECT_EQ(encode_codepoint_u8(U'z'), u8"z"sv); EXPECT_EQ(encode_codepoint_u8(U'\u007F'), u8"\u007F"sv); EXPECT_EQ(encode_codepoint_u8(U'\u0080'), u8"\u0080"sv); EXPECT_EQ(encode_codepoint_u8(U'\u07FF'), u8"\u07FF"sv); EXPECT_EQ(encode_codepoint_u8(U'\u0800'), u8"\u0800"sv); EXPECT_EQ(encode_codepoint_u8(U'\uFFFF'), u8"\uFFFF"sv); EXPECT_EQ(encode_codepoint_u8(U'\U00010000'), u8"\U00010000"sv); EXPECT_EQ(encode_codepoint_u8(U'\U0010FFFF'), u8"\U0010FFFF"sv); EXPECT_EQ(encode_codepoint_u8(U'\U0001F604'), u8"\U0001F604"sv); } TEST(UTF16Test, encode_codepoint) { EXPECT_EQ(encode_codepoint_u16(U'\0'), u"\0"sv); EXPECT_EQ(encode_codepoint_u16(U'A'), u"A"sv); EXPECT_EQ(encode_codepoint_u16(U'z'), u"z"sv); EXPECT_EQ(encode_codepoint_u16(U'\u007F'), u"\u007F"sv); EXPECT_EQ(encode_codepoint_u16(U'\u0080'), u"\u0080"sv); EXPECT_EQ(encode_codepoint_u16(U'\u07FF'), u"\u07FF"sv); EXPECT_EQ(encode_codepoint_u16(U'\u0800'), u"\u0800"sv); EXPECT_EQ(encode_codepoint_u16(U'\uFFFF'), u"\uFFFF"sv); EXPECT_EQ(encode_codepoint_u16(U'\U00010000'), u"\U00010000"sv); EXPECT_EQ(encode_codepoint_u16(U'\U0010FFFF'), u"\U0010FFFF"sv); EXPECT_EQ(encode_codepoint_u16(U'\U0001F604'), u"\U0001F604"sv); } TEST(UTF32Test, encode_codepoint) { EXPECT_EQ(encode_codepoint_u32(U'\0'), U"\0"sv); EXPECT_EQ(encode_codepoint_u32(U'A'), U"A"sv); EXPECT_EQ(encode_codepoint_u32(U'z'), U"z"sv); EXPECT_EQ(encode_codepoint_u32(U'\u007F'), U"\u007F"sv); EXPECT_EQ(encode_codepoint_u32(U'\u0080'), U"\u0080"sv); EXPECT_EQ(encode_codepoint_u32(U'\u07FF'), U"\u07FF"sv); EXPECT_EQ(encode_codepoint_u32(U'\u0800'), U"\u0800"sv); EXPECT_EQ(encode_codepoint_u32(U'\uFFFF'), U"\uFFFF"sv); EXPECT_EQ(encode_codepoint_u32(U'\U00010000'), U"\U00010000"sv); EXPECT_EQ(encode_codepoint_u32(U'\U0010FFFF'), U"\U0010FFFF"sv); EXPECT_EQ(encode_codepoint_u32(U'\U0001F604'), U"\U0001F604"sv); } /** decode_codepoint */ #define DECODE_CODEPOINT_TEST(IN_STR, IN_CODEPOINT, IN_UNITS) \ EXPECT_EQ(decode_codepoint( IN_STR ).codepoint, IN_CODEPOINT); \ EXPECT_EQ(decode_codepoint( IN_STR ).units, IN_UNITS) TEST(UTF8Test, decode_codepoint) { DECODE_CODEPOINT_TEST(u8""sv, U'\0', 0U); DECODE_CODEPOINT_TEST(u8"\0"sv, U'\0', 1U); DECODE_CODEPOINT_TEST(u8"A"sv, U'A', 1U); DECODE_CODEPOINT_TEST(u8"z"sv, U'z', 1U); DECODE_CODEPOINT_TEST(u8"\u007F"sv, U'\u007F', 1U); DECODE_CODEPOINT_TEST(u8"\u0080"sv, U'\u0080', 2U); DECODE_CODEPOINT_TEST(u8"\u07FF"sv, U'\u07FF', 2U); DECODE_CODEPOINT_TEST(u8"\u0800"sv, U'\u0800', 3U); DECODE_CODEPOINT_TEST(u8"\uFFFF"sv, U'\uFFFF', 3U); DECODE_CODEPOINT_TEST(u8"\U00010000"sv, U'\U00010000', 4U); DECODE_CODEPOINT_TEST(u8"\U0010FFFF"sv, U'\U0010FFFF', 4U); DECODE_CODEPOINT_TEST(u8"\U0001F604"sv, U'\U0001F604', 4U); } TEST(UTF16Test, decode_codepoint) { DECODE_CODEPOINT_TEST(u""sv, U'\0', 0U); DECODE_CODEPOINT_TEST(u"\0"sv, U'\0', 1U); DECODE_CODEPOINT_TEST(u"A"sv, U'A', 1U); DECODE_CODEPOINT_TEST(u"z"sv, U'z', 1U); DECODE_CODEPOINT_TEST(u"\u007F"sv, U'\u007F', 1U); DECODE_CODEPOINT_TEST(u"\u0080"sv, U'\u0080', 1U); DECODE_CODEPOINT_TEST(u"\u07FF"sv, U'\u07FF', 1U); DECODE_CODEPOINT_TEST(u"\u0800"sv, U'\u0800', 1U); DECODE_CODEPOINT_TEST(u"\uD7FF"sv, U'\uD7FF', 1U); DECODE_CODEPOINT_TEST(u"\uE000"sv, U'\uE000', 1U); DECODE_CODEPOINT_TEST(u"\uFFFF"sv, U'\uFFFF', 1U); DECODE_CODEPOINT_TEST(u"\U00010000"sv, U'\U00010000', 2U); DECODE_CODEPOINT_TEST(u"\U0010FFFF"sv, U'\U0010FFFF', 2U); DECODE_CODEPOINT_TEST(u"\U0001F604"sv, U'\U0001F604', 2U); } TEST(UTF32Test, decode_codepoint) { DECODE_CODEPOINT_TEST(U""sv, U'\0', 0U); DECODE_CODEPOINT_TEST(U"\0"sv, U'\0', 1U); DECODE_CODEPOINT_TEST(U"A"sv, U'A', 1U); DECODE_CODEPOINT_TEST(U"z"sv, U'z', 1U); DECODE_CODEPOINT_TEST(U"\u007F"sv, U'\u007F', 1U); DECODE_CODEPOINT_TEST(U"\u0080"sv, U'\u0080', 1U); DECODE_CODEPOINT_TEST(U"\u07FF"sv, U'\u07FF', 1U); DECODE_CODEPOINT_TEST(U"\u0800"sv, U'\u0800', 1U); DECODE_CODEPOINT_TEST(U"\uFFFF"sv, U'\uFFFF', 1U); DECODE_CODEPOINT_TEST(U"\U00010000"sv, U'\U00010000', 1U); DECODE_CODEPOINT_TEST(U"\U0010FFFF"sv, U'\U0010FFFF', 1U); DECODE_CODEPOINT_TEST(U"\U0001F604"sv, U'\U0001F604', 1U); }
[ "jessica.aj@outlook.com" ]
jessica.aj@outlook.com
3fda91cce45a39b20fef2511fcd36a167d325294
9493ce58ccf83dd5a1b4cd82aa12b96a8969c14c
/RATS/RATS/Modules/VFX/MeshDistorter/MeshDistorter.cpp
148490fb3485062dc98d39aa7a47323bfbd4c68d
[]
no_license
YvonneNeuland/RATS
6302dbe8e6e19c33c9daadbb673a78f838643297
33062f2b22a332408b40b9a0e048a4e9e278b154
refs/heads/master
2021-03-24T12:59:41.676093
2017-02-08T05:48:58
2017-02-08T05:48:58
72,884,449
1
1
null
null
null
null
UTF-8
C++
false
false
9,754
cpp
#include "stdafx.h" #include "MeshDistorter.h" #include "../../Renderer/D3DGraphics.h" #include "../../Upgrade System/GameData.h" #include "../../Object Manager/ObjectManager.h" extern D3DGraphics* globalGraphicsPointer; extern GameData* gameData; #define SAFEDELARR(ptr) if(ptr != nullptr) delete[] ptr; ptr = nullptr MeshDistorter::MeshDistorter() { } MeshDistorter::~MeshDistorter() { Shutdown(); } void MeshDistorter::Shutdown() { SAFEDELARR(meshPreserveOriginal); } void MeshDistorter::Reset(Mesh* newToDeform) { if (newToDeform != nullptr) { wave.Deactivate(this); XMFLOAT4X4 identity; XMStoreFloat4x4(&identity, XMMatrixIdentity()); GetTransform().SetLocalMatrix(identity); SAFEDELARR(meshPreserveOriginal); numMeshPreserveVerts = newToDeform->m_numVertices; meshPreserveOriginal = new POSUVNRM_VERTEX[newToDeform->m_numVertices]; for (unsigned int currVert = 0; currVert < newToDeform->m_numVertices; ++currVert) meshPreserveOriginal[currVert] = newToDeform->m_vertexArray[currVert]; wave.SetActive(newToDeform); } } void MeshDistorter::Wave::Deactivate(MeshDistorter* my) { if (myMesh != nullptr) { WaveTemplate& tmpWave = my->waveTemplate; for (unsigned int currRing = 0; currRing < tmpWave.GetNumRings(); ++currRing) { tmpWave.GetRing(currRing).Reset(myMesh, my->meshPreserveOriginal); } SaveToMesh(); globalGraphicsPointer->ReturnDistortionMesh(myMesh, gameData->m_levelShape); myMesh = nullptr; } currFront = 0; currLifetime = -1; active = false; } void MeshDistorter::SetEpicenter(Position pos) { Transform& myTrans = GetTransform(); XMFLOAT3 newX, newY, newZ; string& levelShape = gameData->m_levelShape; if (levelShape == "Torus") { // changes must be clamped to X-Z plane myTrans.SetScaleAll(1); } else if (levelShape == "RoundedCube") { myTrans.SetScaleAll(0.99f); } else // Sphere { XMStoreFloat3(&newY, XMVector3Normalize(XMLoadFloat3(&pos))); XMStoreFloat3(&newX, XMVector3Normalize(XMVector3Cross(XMLoadFloat3(&newY), XMLoadFloat3(myTrans.GetZAxis())))); if (XMVector3Length(XMLoadFloat3(&newX)).m128_f32[0] < 1) XMStoreFloat3(&newX, XMVector3Normalize(XMVector3Cross(XMLoadFloat3(&newY), XMLoadFloat3(myTrans.GetXAxis())))); XMStoreFloat3(&newZ, XMVector3Normalize(XMVector3Cross(XMLoadFloat3(&newX), XMLoadFloat3(&newY)))); myTrans.SetXAxis(newX); myTrans.SetYAxis(newY); myTrans.SetZAxis(newZ); myTrans.SetScaleAll(0.99f); } CreateTemplates(pos); } void MeshDistorter::Wave::SetActive(Mesh* newMesh) { myMesh = newMesh; currLifetime = 0; currFront = 0; active = true; } void SortVertInds(void* Arr, int leftbound, int rightbound) { struct VertInd { int index; float epiAxisDistance; }; VertInd* actualArr = (VertInd*)Arr; int leftIter = leftbound, rightIter = rightbound; float pivotVal = actualArr[(leftIter + rightIter) / 2].epiAxisDistance; VertInd tmp; while (leftIter <= rightIter) { while (actualArr[leftIter].epiAxisDistance < pivotVal) ++leftIter; while (actualArr[rightIter].epiAxisDistance > pivotVal) --rightIter; if (leftIter <= rightIter) { tmp = actualArr[leftIter]; actualArr[leftIter] = actualArr[rightIter]; actualArr[rightIter] = tmp; ++leftIter; --rightIter; } } if (leftbound < rightIter) SortVertInds(Arr, leftbound, rightIter); if (leftIter < rightbound) SortVertInds(Arr, leftIter, rightbound); } void MeshDistorter::CreateTemplates(Position epicenter) { struct VertInd { int index; float epiAxisDistance; }; XMStoreFloat3(&epicenter, XMVector3Transform(XMLoadFloat3(&epicenter), XMMatrixInverse(nullptr, XMLoadFloat4x4(&GetTransform().GetWorldMatrix())))); XMVECTOR epicenterAxis = XMVector3Normalize(XMLoadFloat3(GetTransform().GetPosition()) - XMLoadFloat3(&epicenter)); VertInd* toSort = new VertInd[numMeshPreserveVerts]; bool isTorus = gameData->m_levelShape == "Torus"; bool isRoundCube = gameData->m_levelShape == "RoundedCube"; XMFLOAT3* currPos; //XMVECTOR toCurrPos; //float dotDist; for (unsigned int currVert = 0; currVert < numMeshPreserveVerts; ++currVert) { toSort[currVert].index = currVert; currPos = (XMFLOAT3*)&meshPreserveOriginal[currVert].position; if (isTorus) toSort[currVert].epiAxisDistance = XMVector3AngleBetweenVectors(XMLoadFloat3(currPos) * XMLoadFloat3(&XMFLOAT3(1, 0, 1)), XMLoadFloat3(&epicenter) * XMLoadFloat3(&XMFLOAT3(1, 0, 1))).m128_f32[0]; //else if (isRoundCube) //{ // toCurrPos = XMVector3Normalize(XMLoadFloat3(currPos) - XMLoadFloat3(&epicenter)); // dotDist = XMVector3Dot(epicenterAxis, toCurrPos).m128_f32[0]; // toSort[currVert].epiAxisDistance = (dotDist * dotDist); //} else toSort[currVert].epiAxisDistance = XMVector3LengthSq(XMLoadFloat3(currPos) - XMLoadFloat3(&epicenter)).m128_f32[0]; } SortVertInds(toSort, 0, int(numMeshPreserveVerts) - 1); for (unsigned int currVert = 0; currVert < numMeshPreserveVerts; ++currVert) toSort[currVert].epiAxisDistance = sqrtf(toSort[currVert].epiAxisDistance); float waveThickness = (isTorus ? torusWaveThickness : (isRoundCube ? roundedCubeWaveThickness : sphereWaveThickness)); waveTemplate.Set(toSort, numMeshPreserveVerts, waveThickness); delete[] toSort; } void MeshDistorter::WaveTemplate::Set(void* Arr, unsigned int size, float waveThickness) { struct VertInd { int index; float epiAxisDistance; }; VertInd* actualArr = (VertInd*)Arr; float lastDistance = actualArr[0].epiAxisDistance; numRings = 0; unsigned int startIndex = 0, endIndex = 0; for (unsigned int currVert = 0; currVert < size; ++currVert) { if (actualArr[currVert].epiAxisDistance - lastDistance > waveThickness) { lastDistance = actualArr[currVert].epiAxisDistance; endIndex = currVert - 1; ringsUsed[numRings].Set(Arr, startIndex, endIndex); ++numRings; startIndex = currVert; } } ringsUsed[numRings].Set(Arr, startIndex, size - 1); ++numRings; if (numRings > MAXNUM_MESH_RINGS) DebugBreak(); switchWavesRatio = (1.0f / numRings) * maxLifetime; } void MeshDistorter::WaveTemplate::RingTemplate::Set(void* Arr, unsigned int startInd, unsigned int endInd) { struct VertInd { int index; float epiAxisDistance; }; VertInd* actualArr = (VertInd*)Arr; unsigned int chunkLength = endInd - startInd; numInds = 0; for (unsigned int currInd = 0; currInd <= chunkLength; ++currInd) { indicesUsed[currInd] = actualArr[startInd + currInd].index; ++numInds; } if (numInds > MAXNUM_INDICES_PER_RING) DebugBreak(); } void MeshDistorter::Update(float dt) { wave.Update(this, dt); } void MeshDistorter::Wave::Update(MeshDistorter* my, float dt) { if (active) { WaveTemplate& tmpWave = my->waveTemplate; currLifetime += dt; if (currLifetime > tmpWave.GetSwitchWaveThreshold()) { ++currFront; if (currFront > tmpWave.GetNumRings() + 1) { Deactivate(my); my->SetDead(); return; } currLifetime = 0; } if (int(currFront) - 2 >= 0) tmpWave.GetRing(currFront - 2).Reset(myMesh, my->meshPreserveOriginal); if (int(currFront) - 1 >= 0 && int(currFront) < tmpWave.GetNumRings()) tmpWave.GetRing(currFront - 1).Lower(myMesh, my->meshPreserveOriginal, my->offsetAmount * dt); if (currFront < tmpWave.GetNumRings()) tmpWave.GetRing(currFront).Raise(myMesh, my->meshPreserveOriginal, my->offsetAmount * dt, my->offsetAmount * 0.75f); SaveToMesh(); } } void MeshDistorter::Wave::SaveToMesh() { D3D11_MAPPED_SUBRESOURCE ms; globalGraphicsPointer->GetContext()->Map(myMesh->m_vertexBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &ms); memcpy(ms.pData, myMesh->m_vertexArray, sizeof(POSUVNRM_VERTEX) * myMesh->m_numVertices); globalGraphicsPointer->GetContext()->Unmap(myMesh->m_vertexBuffer, 0); } void MeshDistorter::WaveTemplate::RingTemplate::Raise(Mesh* toUse, POSUVNRM_VERTEX* origVerts, float offsAmt, float ceilingAmt) { POSUVNRM_VERTEX* verts = toUse->m_vertexArray; XMFLOAT3* currentPosition; XMFLOAT3* currentNormal; for (unsigned int i = 0; i < numInds; ++i) { currentPosition = (XMFLOAT3*)&verts[indicesUsed[i]].position; currentNormal = &verts[indicesUsed[i]].normal; XMStoreFloat3(currentPosition, XMLoadFloat3(currentPosition) + (XMLoadFloat3(&origVerts[indicesUsed[i]].normal) * offsAmt)); XMStoreFloat3(currentNormal, XMLoadFloat3(&origVerts[indicesUsed[i]].normal) * 2); if (XMVector3Length(XMLoadFloat3(currentPosition) - XMLoadFloat3((XMFLOAT3*)&origVerts[indicesUsed[i]].position)).m128_f32[0] > ceilingAmt) XMStoreFloat3(currentPosition, XMLoadFloat3((XMFLOAT3*)&origVerts[indicesUsed[i]].position) + (XMLoadFloat3(&origVerts[indicesUsed[i]].normal) * ceilingAmt)); } } void MeshDistorter::WaveTemplate::RingTemplate::Lower(Mesh* toUse, POSUVNRM_VERTEX* origVerts, float offsAmt) { POSUVNRM_VERTEX* verts = toUse->m_vertexArray; XMFLOAT3* currentPosition; XMFLOAT3* currentNormal; for (unsigned int i = 0; i < numInds; ++i) { currentPosition = (XMFLOAT3*)&verts[indicesUsed[i]].position; currentNormal = &verts[indicesUsed[i]].normal; XMStoreFloat3(currentPosition, XMLoadFloat3(currentPosition) - (XMLoadFloat3(&origVerts[indicesUsed[i]].normal) * offsAmt)); if (XMVector3Dot(XMLoadFloat3(currentPosition) - XMLoadFloat3((XMFLOAT3*)&origVerts[indicesUsed[i]].position), XMLoadFloat3(currentNormal)).m128_f32[0] < 0) *currentPosition = *(XMFLOAT3*)&origVerts[indicesUsed[i]].position; XMStoreFloat3(currentNormal, XMLoadFloat3(&origVerts[indicesUsed[i]].normal)); } } void MeshDistorter::WaveTemplate::RingTemplate::Reset(Mesh* toUse, POSUVNRM_VERTEX* origVerts) { POSUVNRM_VERTEX* verts = toUse->m_vertexArray; for (unsigned int i = 0; i < numInds; ++i) verts[indicesUsed[i]] = origVerts[indicesUsed[i]]; }
[ "YvonneNeuland@fullsail.edu" ]
YvonneNeuland@fullsail.edu
b76db2ad3fe9c574ae45a4e4ea8ce8061bd8007f
5d7807e52888b9505c4b5a0e24f5f87e4f6c343f
/cryengine/CryGame/ScriptBind_Weapon.cpp
9d6380c23fb6415dfadac1a4711e3ea918f7c00b
[]
no_license
CapsAdmin/oohh
01533c72450c5ac036a245ffbaba09b6fda00e69
b63abeb717e1cd1ee2d3483bd5f0954c81bfc6e9
refs/heads/master
2021-01-25T10:44:22.976777
2016-10-11T19:05:47
2016-10-11T19:05:47
32,117,923
1
1
null
null
null
null
UTF-8
C++
false
false
21,812
cpp
/************************************************************************* Crytek Source File. Copyright (C), Crytek Studios, 2001-2004. ------------------------------------------------------------------------- $Id$ $DateTime$ ------------------------------------------------------------------------- History: - 27:10:2004 11:29 : Created by Marcio Martins *************************************************************************/ #include "StdAfx.h" #include "ScriptBind_Weapon.h" #include "Item.h" #include "Weapon.h" #include "IGameObject.h" #include "Actor.h" #define REUSE_VECTOR(table, name, value) \ { if (table->GetValueType(name) != svtObject) \ { \ table->SetValue(name, (value)); \ } \ else \ { \ SmartScriptTable v; \ table->GetValue(name, v); \ v->SetValue("x", (value).x); \ v->SetValue("y", (value).y); \ v->SetValue("z", (value).z); \ } \ } //------------------------------------------------------------------------ // Helper that returns requested fire mode or current fire mode (if none specified). static IFireMode* GetRequestedFireMode(CWeapon* pWeapon, IFunctionHandler* pH, int nPosFireMode = 1) { CRY_ASSERT(pWeapon); CRY_ASSERT(pH); IFireMode* pFireMode = NULL; const char* szFireMode = NULL; int idxFireMode = 0; // If a fire mode index/name specified, use that. Else, use current. if (pH->GetParamCount() >= nPosFireMode) { if (pH->GetParamType(nPosFireMode) == svtString && pH->GetParam(nPosFireMode,szFireMode)) { pFireMode = pWeapon->GetFireMode(szFireMode); } else if (pH->GetParamType(nPosFireMode) == svtNumber && pH->GetParam(nPosFireMode,idxFireMode)) { pFireMode = pWeapon->GetFireMode(idxFireMode); } } else { idxFireMode = pWeapon->GetCurrentFireMode(); pFireMode = pWeapon->GetFireMode(idxFireMode); } return pFireMode; } //------------------------------------------------------------------------ CScriptBind_Weapon::CScriptBind_Weapon(ISystem *pSystem, IGameFramework *pGameFramework) : m_pSystem(pSystem), m_pSS(pSystem->GetIScriptSystem()), m_pGameFW(pGameFramework) { Init(m_pSS, 1); RegisterMethods(); RegisterGlobals(); } //------------------------------------------------------------------------ CScriptBind_Weapon::~CScriptBind_Weapon() { } //------------------------------------------------------------------------ void CScriptBind_Weapon::AttachTo(CWeapon *pWeapon) { IScriptTable *pScriptTable = ((CItem *)pWeapon)->GetEntity()->GetScriptTable(); if (pScriptTable) { SmartScriptTable thisTable(m_pSS); thisTable->SetValue("__this", ScriptHandle(pWeapon->GetEntityId())); thisTable->Delegate(GetMethodsTable()); pScriptTable->SetValue("weapon", thisTable); } } //------------------------------------------------------------------------ int CScriptBind_Weapon::SetAmmoCount(IFunctionHandler *pH) { CWeapon *pWeapon = GetWeapon(pH); if (!pWeapon) return pH->EndFunction(); IFireMode* pFireMode = GetRequestedFireMode(pWeapon, pH); if (pFireMode) { if (pH->GetParamType(2) != svtNumber) return pH->EndFunction(); const char *ammoName = 0; if (pH->GetParamType(1) == svtString) pH->GetParam(1, ammoName); IEntityClass* pAmmoType = pFireMode->GetAmmoType(); if (ammoName) pAmmoType = gEnv->pEntitySystem->GetClassRegistry()->FindClass(ammoName); int ammo = 0; pH->GetParam(2, ammo); pWeapon->SetAmmoCount(pAmmoType, ammo); } return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_Weapon::GetAmmoCount(IFunctionHandler *pH) { CWeapon *pWeapon = GetWeapon(pH); if (!pWeapon) return pH->EndFunction(); IFireMode* pFireMode = GetRequestedFireMode(pWeapon, pH); if (pFireMode) return pH->EndFunction(pFireMode->GetAmmoCount()); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_Weapon::GetClipSize(IFunctionHandler *pH) { CWeapon *pWeapon = GetWeapon(pH); if (!pWeapon) return pH->EndFunction(); IFireMode* pFireMode = GetRequestedFireMode(pWeapon, pH); if (pFireMode) return pH->EndFunction(pFireMode->GetClipSize()); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_Weapon::IsZoomed(IFunctionHandler *pH) { CWeapon *pWeapon = GetWeapon(pH); if (!pWeapon) return pH->EndFunction(); IZoomMode *pZoomMode = pWeapon->GetZoomMode(pWeapon->GetCurrentZoomMode()); if (pZoomMode) return pH->EndFunction(pZoomMode->IsZoomed()); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_Weapon::IsZooming(IFunctionHandler *pH) { CWeapon *pWeapon = GetWeapon(pH); if (!pWeapon) return pH->EndFunction(); IZoomMode *pZoomMode = pWeapon->GetZoomMode(pWeapon->GetCurrentZoomMode()); if (pZoomMode) return pH->EndFunction(pZoomMode->IsZoomingInOrOut()); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_Weapon::GetDamage(IFunctionHandler *pH) { CWeapon *pWeapon = GetWeapon(pH); if (!pWeapon) return pH->EndFunction(); IFireMode* pFireMode = GetRequestedFireMode(pWeapon, pH); if (pFireMode) return pH->EndFunction(pFireMode->GetDamage()); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_Weapon::GetAmmoType(IFunctionHandler *pH) { CWeapon *pWeapon = GetWeapon(pH); if (!pWeapon) return pH->EndFunction(); IFireMode* pFireMode = GetRequestedFireMode(pWeapon, pH); if (pFireMode) if (IEntityClass * pCls = pFireMode->GetAmmoType()) return pH->EndFunction(pCls->GetName()); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_Weapon::GetRecoil(IFunctionHandler *pH) { CWeapon *pWeapon = GetWeapon(pH); if (!pWeapon) return pH->EndFunction(); IFireMode* pFireMode = GetRequestedFireMode(pWeapon, pH); if (pFireMode) return pH->EndFunction(pFireMode->GetRecoil()); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_Weapon::GetSpread(IFunctionHandler *pH) { CWeapon *pWeapon = GetWeapon(pH); if (!pWeapon) return pH->EndFunction(); IFireMode* pFireMode = GetRequestedFireMode(pWeapon, pH); if (pFireMode) return pH->EndFunction(pFireMode->GetSpread()); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_Weapon::GetCrosshair(IFunctionHandler *pH) { CWeapon *pWeapon = GetWeapon(pH); if (!pWeapon) return pH->EndFunction(); IFireMode* pFireMode = GetRequestedFireMode(pWeapon, pH); if (pFireMode) return pH->EndFunction(pFireMode->GetCrosshair()); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_Weapon::GetCrosshairOpacity(IFunctionHandler *pH) { CWeapon *pWeapon = GetWeapon(pH); if (!pWeapon) return pH->EndFunction(); return pH->EndFunction(pWeapon->GetCrosshairOpacity()); } //------------------------------------------------------------------------ int CScriptBind_Weapon::GetCrosshairVisibility(IFunctionHandler *pH) { CWeapon *pWeapon = GetWeapon(pH); if (!pWeapon) return pH->EndFunction(); return pH->EndFunction(pWeapon->GetCrosshairVisibility()); } //------------------------------------------------------------------------ int CScriptBind_Weapon::EnableFireMode(IFunctionHandler *pH, const char* name, bool enable) { CWeapon *pWeapon = GetWeapon(pH); if (!pWeapon) return pH->EndFunction(); IFireMode* pFireMode = pWeapon->GetFireMode(name); if (pFireMode) { pFireMode->Enable(enable); } return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_Weapon::IsFireModeEnabled(IFunctionHandler *pH, const char* name) { CWeapon *pWeapon = GetWeapon(pH); if (!pWeapon) return pH->EndFunction(); bool bIsEnabled = false; IFireMode* pFireMode = pWeapon->GetFireMode(name); if (pFireMode) { bIsEnabled = pFireMode->IsEnabled(); } return pH->EndFunction(bIsEnabled); } //------------------------------------------------------------------------ int CScriptBind_Weapon::SetCurrentFireMode(IFunctionHandler *pH, const char *name) { CWeapon *pWeapon = GetWeapon(pH); if (!pWeapon) return pH->EndFunction(); pWeapon->SetCurrentFireMode(name); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_Weapon::SetCurrentZoomMode(IFunctionHandler *pH, const char *name) { CWeapon *pWeapon = GetWeapon(pH); if (!pWeapon) return pH->EndFunction(); pWeapon->SetCurrentZoomMode(name); return pH->EndFunction(); } int CScriptBind_Weapon::ModifyCommit(IFunctionHandler *pH) { CWeapon *pWeapon = GetWeapon(pH); if (!pWeapon) return pH->EndFunction(); pWeapon->RestoreLayers(); pWeapon->ReAttachAccessories(); return pH->EndFunction(); } class ScheduleAttachClass { public: ScheduleAttachClass(CWeapon *wep, const char *cname, bool attch) { m_pWeapon = wep; m_className = cname; m_attach = attch; } void execute(CItem *item) { //CryLogAlways("attaching %s", _className); m_pWeapon->AttachAccessory(m_className, m_attach, false); //delete this; } private: CWeapon *m_pWeapon; const char *m_className; bool m_attach; }; int CScriptBind_Weapon::ScheduleAttach(IFunctionHandler *pH, const char *className, bool attach) { CWeapon *pWeapon = GetWeapon(pH); if (!pWeapon) return pH->EndFunction(); pWeapon->GetScheduler()->ScheduleAction(CSchedulerAction<ScheduleAttachClass>::Create(ScheduleAttachClass(pWeapon, className, attach))); return pH->EndFunction(); } int CScriptBind_Weapon::SupportsAccessory(IFunctionHandler *pH, const char *accessoryName) { CWeapon *pWeapon = GetWeapon(pH); if (!pWeapon) return pH->EndFunction(); CItem::SAccessoryParams *params = pWeapon->GetAccessoryParams(accessoryName); return pH->EndFunction(params != 0); } int CScriptBind_Weapon::GetAccessory(IFunctionHandler *pH, const char *accessoryName) { CWeapon *pWeapon = GetWeapon(pH); if (!pWeapon) return pH->EndFunction(); CItem *pItem = pWeapon->GetAccessory(accessoryName); if(!pItem) return 0; IEntity *pEntity = pItem->GetEntity(); if(!pEntity) return 0; IScriptTable *pScriptTable = pEntity->GetScriptTable(); return pH->EndFunction( pScriptTable ); } int CScriptBind_Weapon::AttachAccessory(IFunctionHandler *pH, const char *className, bool attach, bool force) { CWeapon *pWeapon = GetWeapon(pH); if (!pWeapon) return pH->EndFunction(); if (className) pWeapon->AttachAccessory(className, attach, true, force); return pH->EndFunction(); } int CScriptBind_Weapon::SwitchAccessory(IFunctionHandler *pH, const char *className) { CWeapon *pWeapon = GetWeapon(pH); if (!pWeapon) return pH->EndFunction(); if (className) pWeapon->SwitchAccessory(className); return pH->EndFunction(); } int CScriptBind_Weapon::IsFiring(IFunctionHandler *pH) { CWeapon *pWeapon = GetWeapon(pH); if (!pWeapon) return pH->EndFunction(); int n=pWeapon->GetNumOfFireModes(); for (int i=0;i<n;i++) { if (IFireMode *pFireMode=pWeapon->GetFireMode(i)) { if (pFireMode->IsEnabled() && pFireMode->IsFiring()) return pH->EndFunction(true); } } return pH->EndFunction(); } int CScriptBind_Weapon::AttachAccessoryPlaceHolder(IFunctionHandler *pH, SmartScriptTable accessory, bool attach) { CWeapon *pWeapon = GetWeapon(pH); if (!pWeapon) return pH->EndFunction(); const char *accessoryName; accessory->GetValue("class", accessoryName); ScriptHandle id; accessory->GetValue("id", id); EntityId entId = (EntityId)id.n; //CryLogAlways("id = %d", entId); IEntity *attachment = gEnv->pEntitySystem->GetEntity(entId); if (accessoryName) { //CryLogAlways("got name: %s", accessoryName); if (pWeapon->GetAccessoryPlaceHolder(accessoryName)) { //CryLogAlways("found accessory place holder"); pWeapon->AttachAccessoryPlaceHolder(accessoryName, attach); } else { //CryLogAlways("accessory place holder not found"); CActor *pActor = pWeapon->GetOwnerActor(); IEntity *wep = pWeapon->GetEntity(); //IGameObject *pGameObject = pWeapon->GetOwnerActor()->GetGameObject(); IInventory *pInventory = pActor->GetInventory(); if (pInventory) { //CryLogAlways("found inventory"); if (attachment) { if (pInventory->FindItem(entId) != -1) { //CryLogAlways("found attachment in inventory already..."); } else { //CryLogAlways("attachment not found in inventory, adding..."); } //CryLogAlways("found attachment"); //attachment->DetachThis(0); //attachment->SetParentId(0); //CItem *t = (CItem *)attachment; //t->SetParentId(0); //pWeapon->GetEntity()->AttachChild(attachment, false) pInventory->AddItem(attachment->GetId()); //for (int i = 0; i < wep->GetChildCount(); i++) //{ // IEntity *cur = wep->GetChild(i); // CryLogAlways("none of these should be %s", attachment->GetName()); // CryLogAlways(" %s", cur->GetName()); //} pWeapon->AttachAccessoryPlaceHolder(accessoryName, attach); pInventory->RemoveItem(attachment->GetId()); } else { //CryLogAlways("!attachment"); } } } } return pH->EndFunction(); } int CScriptBind_Weapon::GetAttachmentHelperPos(IFunctionHandler *pH, const char *helperName) { CWeapon *pWeapon = GetWeapon(pH); if (!pWeapon) return pH->EndFunction(); Vec3 pos = pWeapon->GetSlotHelperPos(eIGS_FirstPerson, helperName, false); Vec3 tpos = pWeapon->GetSlotHelperPos(eIGS_FirstPerson, helperName, true); //gEnv->pRenderer->DrawPoint(tpos.x, tpos.y, tpos.z, 10.0f); //CryLogAlways("helperName: %s pos: x=%f y=%f z=%f", helperName, tpos.x, tpos.y, tpos.z); //gEnv->pRenderer->DrawBall(tpos, 0.2f); //gEnv->pRenderer->GetIRenderAuxGeom()->DrawSphere(tpos, 0.075f, ColorB( 255, 10, 10, 255 )); //gEnv->pRenderer->GetIRenderAuxGeom()->DrawLine(pWeapon->GetOwner()->GetWorldPos(), ColorB(0, 0, 255, 255), tpos, ColorB(255, 255, 0, 255)); return pH->EndFunction(tpos); } int CScriptBind_Weapon::GetShooter(IFunctionHandler *pH) { CWeapon *pWeapon = GetWeapon(pH); if (!pWeapon) return pH->EndFunction(); IEntity *owner = pWeapon->GetOwner(); return pH->EndFunction(owner->GetScriptTable()); } //------------------------------------------------------------------------ int CScriptBind_Weapon::AutoShoot(IFunctionHandler *pH, int shots, bool autoReload) { struct AutoShootHelper : public IWeaponEventListener { AutoShootHelper(int n, bool autoreload): m_nshots(n), m_reload(autoreload) {}; virtual ~AutoShootHelper() {}; int m_nshots; bool m_reload; virtual void OnShoot(IWeapon *pWeapon, EntityId shooterId, EntityId ammoId, IEntityClass* pAmmoType, const Vec3 &pos, const Vec3 &dir, const Vec3 &vel) {}; virtual void OnStartFire(IWeapon *pWeapon, EntityId shooterId) {}; virtual void OnStopFire(IWeapon *pWeapon, EntityId shooterId) {}; virtual void OnStartReload(IWeapon *pWeapon, EntityId shooterId, IEntityClass* pAmmoType) {}; virtual void OnEndReload(IWeapon *pWeapon, EntityId shooterId, IEntityClass* pAmmoType) {}; virtual void OnSetAmmoCount(IWeapon *pWeapon, EntityId shooterId) {} virtual void OnOutOfAmmo(IWeapon *pWeapon, IEntityClass* pAmmoType) { if (m_reload) pWeapon->Reload(false); else { pWeapon->StopFire(); pWeapon->RemoveEventListener(this); } }; virtual void OnReadyToFire(IWeapon *pWeapon) { if (!(--m_nshots)) { pWeapon->StopFire(); pWeapon->RemoveEventListener(this); } else { pWeapon->StartFire(); pWeapon->StopFire(); } }; virtual void OnPickedUp(IWeapon *pWeapon, EntityId actorId, bool destroyed){} virtual void OnDropped(IWeapon *pWeapon, EntityId actorId){} virtual void OnMelee(IWeapon* pWeapon, EntityId shooterId){} virtual void OnStartTargetting(IWeapon *pWeapon) {} virtual void OnStopTargetting(IWeapon *pWeapon) {} virtual void OnSelected(IWeapon *pWeapon, bool select) {} virtual void OnFireModeChanged(IWeapon *pWeapon, int currentFireMode) {} virtual void OnZoomChanged(IWeapon* pWeapon, bool zoomed, int idx) {} }; CWeapon *pWeapon = GetWeapon(pH); if (!pWeapon) return pH->EndFunction(); pWeapon->AddEventListener(new AutoShootHelper(shots, autoReload), __FUNCTION__); // FIXME: possible small memory leak here. pWeapon->StartFire(); pWeapon->StopFire(); return pH->EndFunction(); } // //------------------------------------------------------------------------ int CScriptBind_Weapon::Reload(IFunctionHandler *pH) { CWeapon *pWeapon = GetWeapon(pH); if (pWeapon) pWeapon->Reload(); return pH->EndFunction(); } //------------------------------------------------------------------------ void CScriptBind_Weapon::RegisterGlobals() { } //------------------------------------------------------------------------ void CScriptBind_Weapon::RegisterMethods() { #undef SCRIPT_REG_CLASSNAME #define SCRIPT_REG_CLASSNAME &CScriptBind_Weapon:: SCRIPT_REG_TEMPLFUNC(SetAmmoCount, ""); SCRIPT_REG_TEMPLFUNC(GetAmmoCount, ""); SCRIPT_REG_TEMPLFUNC(GetClipSize, ""); SCRIPT_REG_TEMPLFUNC(IsZoomed, ""); SCRIPT_REG_TEMPLFUNC(IsZooming, ""); SCRIPT_REG_TEMPLFUNC(GetDamage, ""); SCRIPT_REG_TEMPLFUNC(GetAmmoType, ""); SCRIPT_REG_TEMPLFUNC(GetRecoil, ""); SCRIPT_REG_TEMPLFUNC(GetSpread, ""); SCRIPT_REG_TEMPLFUNC(GetCrosshair, ""); SCRIPT_REG_TEMPLFUNC(GetCrosshairOpacity, ""); SCRIPT_REG_TEMPLFUNC(GetCrosshairVisibility, ""); SCRIPT_REG_TEMPLFUNC(ModifyCommit, ""); SCRIPT_REG_TEMPLFUNC(SupportsAccessory, "accessoryName"); SCRIPT_REG_TEMPLFUNC(GetAccessory, "accessoryName"); SCRIPT_REG_TEMPLFUNC(AttachAccessoryPlaceHolder, "accessory, attach"); SCRIPT_REG_TEMPLFUNC(GetAttachmentHelperPos, "helperName"); SCRIPT_REG_TEMPLFUNC(GetShooter, ""); SCRIPT_REG_TEMPLFUNC(ScheduleAttach, "accessoryName, attach"); SCRIPT_REG_TEMPLFUNC(AttachAccessory, "accessoryName, attach, force"); SCRIPT_REG_TEMPLFUNC(SwitchAccessory, "accessoryName"); SCRIPT_REG_TEMPLFUNC(IsFiring, ""); SCRIPT_REG_TEMPLFUNC(EnableFireMode, "name, enable"); SCRIPT_REG_TEMPLFUNC(IsFireModeEnabled, "name"); SCRIPT_REG_TEMPLFUNC(SetCurrentFireMode, "name"); SCRIPT_REG_TEMPLFUNC(GetCurrentFireMode, ""); SCRIPT_REG_TEMPLFUNC(GetFireMode, "idx"); SCRIPT_REG_TEMPLFUNC(GetFireModeIdx, "name"); SCRIPT_REG_TEMPLFUNC(GetNumOfFireModes, ""); SCRIPT_REG_TEMPLFUNC(SetCurrentZoomMode, "name"); SCRIPT_REG_TEMPLFUNC(AutoShoot, "nshots, autoReload"); SCRIPT_REG_TEMPLFUNC(Reload, ""); SCRIPT_REG_TEMPLFUNC(ActivateLamLaser, "activate"); SCRIPT_REG_TEMPLFUNC(ActivateLamLight, "activate"); } //------------------------------------------------------------------------ CItem *CScriptBind_Weapon::GetItem(IFunctionHandler *pH) { void *pThis = pH->GetThis(); if (pThis) { IItem *pItem = m_pGameFW->GetIItemSystem()->GetItem((EntityId)(UINT_PTR)pThis); if (pItem) return static_cast<CItem *>(pItem); } return 0; } //------------------------------------------------------------------------ CWeapon *CScriptBind_Weapon::GetWeapon(IFunctionHandler *pH) { void *pThis = pH->GetThis(); if (pThis) { IItem *pItem = m_pGameFW->GetIItemSystem()->GetItem((EntityId)(UINT_PTR)pThis); if (pItem) { IWeapon *pWeapon=pItem->GetIWeapon(); if (pWeapon) return static_cast<CWeapon *>(pWeapon); } } return 0; } //----------------------------------------------------------------------- int CScriptBind_Weapon::ActivateLamLaser(IFunctionHandler *pH, bool activate) { CWeapon *pWeapon = GetWeapon(pH); if (!pWeapon) return pH->EndFunction(); pWeapon->ActivateLamLaser(activate); return pH->EndFunction(); } //------------------------------------------------------------------------- int CScriptBind_Weapon::ActivateLamLight(IFunctionHandler *pH, bool activate) { CWeapon *pWeapon = GetWeapon(pH); if(!pWeapon) return pH->EndFunction(); pWeapon->ActivateLamLight(activate); return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_Weapon::GetCurrentFireMode(IFunctionHandler *pH) { CWeapon *pWeapon = GetWeapon(pH); if (!pWeapon) return pH->EndFunction(); int idx = pWeapon->GetCurrentFireMode(); IFireMode* pFireMode = pWeapon->GetFireMode(idx); if (pFireMode) { return pH->EndFunction(pFireMode->GetName()); } return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_Weapon::GetFireMode(IFunctionHandler *pH, int idx) { CWeapon *pWeapon = GetWeapon(pH); if (!pWeapon) return pH->EndFunction(); IFireMode* pFireMode = pWeapon->GetFireMode(idx); if (pFireMode) { return pH->EndFunction(pFireMode->GetName()); } return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_Weapon::GetFireModeIdx(IFunctionHandler *pH, const char* name) { CWeapon *pWeapon = GetWeapon(pH); if (!pWeapon) return pH->EndFunction(); const int idx = pWeapon->GetFireModeIdx(name); if (idx >= 0) { return pH->EndFunction(idx); } return pH->EndFunction(); } //------------------------------------------------------------------------ int CScriptBind_Weapon::GetNumOfFireModes(IFunctionHandler *pH) { CWeapon *pWeapon = GetWeapon(pH); int nCountFireModes = 0; if (pWeapon) { nCountFireModes = pWeapon->GetNumOfFireModes(); } return pH->EndFunction(nCountFireModes); } #undef REUSE_VECTOR
[ "eliashogstvedt@gmail.com" ]
eliashogstvedt@gmail.com
10e0b4dc4806ef7ccd44a11468d632830ef07721
f85cfed4ae3c54b5d31b43e10435bb4fc4875d7e
/sc-virt/src/include/llvm/IR/ModuleSummaryIndex.h
45d9bf7af706a3b581b15749acaaa9ba7b3f5301
[ "NCSA", "MIT" ]
permissive
archercreat/dta-vs-osc
2f495f74e0a67d3672c1fc11ecb812d3bc116210
b39f4d4eb6ffea501025fc3e07622251c2118fe0
refs/heads/main
2023-08-01T01:54:05.925289
2021-09-05T21:00:35
2021-09-05T21:00:35
438,047,267
1
1
MIT
2021-12-13T22:45:20
2021-12-13T22:45:19
null
UTF-8
C++
false
false
19,713
h
//===-- llvm/ModuleSummaryIndex.h - Module Summary Index --------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // /// @file /// ModuleSummaryIndex.h This file contains the declarations the classes that /// hold the module index and summary for function importing. // //===----------------------------------------------------------------------===// #ifndef LLVM_IR_MODULESUMMARYINDEX_H #define LLVM_IR_MODULESUMMARYINDEX_H #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/DenseSet.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/StringMap.h" #include "llvm/IR/Module.h" #include <array> namespace llvm { /// \brief Class to accumulate and hold information about a callee. struct CalleeInfo { /// The static number of callsites calling corresponding function. unsigned CallsiteCount; /// The cumulative profile count of calls to corresponding function /// (if using PGO, otherwise 0). uint64_t ProfileCount; CalleeInfo() : CallsiteCount(0), ProfileCount(0) {} CalleeInfo(unsigned CallsiteCount, uint64_t ProfileCount) : CallsiteCount(CallsiteCount), ProfileCount(ProfileCount) {} CalleeInfo &operator+=(uint64_t RHSProfileCount) { CallsiteCount++; ProfileCount += RHSProfileCount; return *this; } }; /// Struct to hold value either by GUID or Value*, depending on whether this /// is a combined or per-module index, respectively. struct ValueInfo { /// The value representation used in this instance. enum ValueInfoKind { VI_GUID, VI_Value, }; /// Union of the two possible value types. union ValueUnion { GlobalValue::GUID Id; const Value *V; ValueUnion(GlobalValue::GUID Id) : Id(Id) {} ValueUnion(const Value *V) : V(V) {} }; /// The value being represented. ValueUnion TheValue; /// The value representation. ValueInfoKind Kind; /// Constructor for a GUID value ValueInfo(GlobalValue::GUID Id = 0) : TheValue(Id), Kind(VI_GUID) {} /// Constructor for a Value* value ValueInfo(const Value *V) : TheValue(V), Kind(VI_Value) {} /// Accessor for GUID value GlobalValue::GUID getGUID() const { assert(Kind == VI_GUID && "Not a GUID type"); return TheValue.Id; } /// Accessor for Value* value const Value *getValue() const { assert(Kind == VI_Value && "Not a Value type"); return TheValue.V; } bool isGUID() const { return Kind == VI_GUID; } }; /// \brief Function and variable summary information to aid decisions and /// implementation of importing. class GlobalValueSummary { public: /// \brief Sububclass discriminator (for dyn_cast<> et al.) enum SummaryKind { AliasKind, FunctionKind, GlobalVarKind }; /// Group flags (Linkage, hasSection, isOptSize, etc.) as a bitfield. struct GVFlags { /// \brief The linkage type of the associated global value. /// /// One use is to flag values that have local linkage types and need to /// have module identifier appended before placing into the combined /// index, to disambiguate from other values with the same name. /// In the future this will be used to update and optimize linkage /// types based on global summary-based analysis. unsigned Linkage : 4; /// Indicate if the global value is located in a specific section. unsigned HasSection : 1; /// Convenience Constructors explicit GVFlags(GlobalValue::LinkageTypes Linkage, bool HasSection) : Linkage(Linkage), HasSection(HasSection) {} GVFlags(const GlobalValue &GV) : Linkage(GV.getLinkage()), HasSection(GV.hasSection()) {} }; private: /// Kind of summary for use in dyn_cast<> et al. SummaryKind Kind; /// This is the hash of the name of the symbol in the original file. It is /// identical to the GUID for global symbols, but differs for local since the /// GUID includes the module level id in the hash. GlobalValue::GUID OriginalName; /// \brief Path of module IR containing value's definition, used to locate /// module during importing. /// /// This is only used during parsing of the combined index, or when /// parsing the per-module index for creation of the combined summary index, /// not during writing of the per-module index which doesn't contain a /// module path string table. StringRef ModulePath; GVFlags Flags; /// List of values referenced by this global value's definition /// (either by the initializer of a global variable, or referenced /// from within a function). This does not include functions called, which /// are listed in the derived FunctionSummary object. std::vector<ValueInfo> RefEdgeList; protected: /// GlobalValueSummary constructor. GlobalValueSummary(SummaryKind K, GVFlags Flags) : Kind(K), Flags(Flags) {} public: virtual ~GlobalValueSummary() = default; /// Returns the hash of the original name, it is identical to the GUID for /// externally visible symbols, but not for local ones. GlobalValue::GUID getOriginalName() { return OriginalName; } /// Initialize the original name hash in this summary. void setOriginalName(GlobalValue::GUID Name) { OriginalName = Name; } /// Which kind of summary subclass this is. SummaryKind getSummaryKind() const { return Kind; } /// Set the path to the module containing this function, for use in /// the combined index. void setModulePath(StringRef ModPath) { ModulePath = ModPath; } /// Get the path to the module containing this function. StringRef modulePath() const { return ModulePath; } /// Get the flags for this GlobalValue (see \p struct GVFlags). GVFlags flags() { return Flags; } /// Return linkage type recorded for this global value. GlobalValue::LinkageTypes linkage() const { return static_cast<GlobalValue::LinkageTypes>(Flags.Linkage); } /// Sets the linkage to the value determined by global summary-based /// optimization. Will be applied in the ThinLTO backends. void setLinkage(GlobalValue::LinkageTypes Linkage) { Flags.Linkage = Linkage; } /// Return true if this summary is for a GlobalValue that needs promotion /// to be referenced from another module. bool needsRenaming() const { return GlobalValue::isLocalLinkage(linkage()); } /// Return true if this global value is located in a specific section. bool hasSection() const { return Flags.HasSection; } /// Record a reference from this global value to the global value identified /// by \p RefGUID. void addRefEdge(GlobalValue::GUID RefGUID) { RefEdgeList.push_back(RefGUID); } /// Record a reference from this global value to the global value identified /// by \p RefV. void addRefEdge(const Value *RefV) { RefEdgeList.push_back(RefV); } /// Record a reference from this global value to each global value identified /// in \p RefEdges. void addRefEdges(DenseSet<const Value *> &RefEdges) { for (auto &RI : RefEdges) addRefEdge(RI); } /// Return the list of values referenced by this global value definition. std::vector<ValueInfo> &refs() { return RefEdgeList; } const std::vector<ValueInfo> &refs() const { return RefEdgeList; } }; /// \brief Alias summary information. class AliasSummary : public GlobalValueSummary { GlobalValueSummary *AliaseeSummary; public: /// Summary constructors. AliasSummary(GVFlags Flags) : GlobalValueSummary(AliasKind, Flags) {} /// Check if this is an alias summary. static bool classof(const GlobalValueSummary *GVS) { return GVS->getSummaryKind() == AliasKind; } void setAliasee(GlobalValueSummary *Aliasee) { AliaseeSummary = Aliasee; } const GlobalValueSummary &getAliasee() const { return const_cast<AliasSummary *>(this)->getAliasee(); } GlobalValueSummary &getAliasee() { assert(AliaseeSummary && "Unexpected missing aliasee summary"); return *AliaseeSummary; } }; /// \brief Function summary information to aid decisions and implementation of /// importing. class FunctionSummary : public GlobalValueSummary { public: /// <CalleeValueInfo, CalleeInfo> call edge pair. typedef std::pair<ValueInfo, CalleeInfo> EdgeTy; private: /// Number of instructions (ignoring debug instructions, e.g.) computed /// during the initial compile step when the summary index is first built. unsigned InstCount; /// List of <CalleeValueInfo, CalleeInfo> call edge pairs from this function. std::vector<EdgeTy> CallGraphEdgeList; public: /// Summary constructors. FunctionSummary(GVFlags Flags, unsigned NumInsts) : GlobalValueSummary(FunctionKind, Flags), InstCount(NumInsts) {} /// Check if this is a function summary. static bool classof(const GlobalValueSummary *GVS) { return GVS->getSummaryKind() == FunctionKind; } /// Get the instruction count recorded for this function. unsigned instCount() const { return InstCount; } /// Record a call graph edge from this function to the function identified /// by \p CalleeGUID, with \p CalleeInfo including the cumulative profile /// count (across all calls from this function) or 0 if no PGO. void addCallGraphEdge(GlobalValue::GUID CalleeGUID, CalleeInfo Info) { CallGraphEdgeList.push_back(std::make_pair(CalleeGUID, Info)); } /// Record a call graph edge from this function to each function GUID recorded /// in \p CallGraphEdges. void addCallGraphEdges(DenseMap<GlobalValue::GUID, CalleeInfo> &CallGraphEdges) { for (auto &EI : CallGraphEdges) addCallGraphEdge(EI.first, EI.second); } /// Record a call graph edge from this function to the function identified /// by \p CalleeV, with \p CalleeInfo including the cumulative profile /// count (across all calls from this function) or 0 if no PGO. void addCallGraphEdge(const Value *CalleeV, CalleeInfo Info) { CallGraphEdgeList.push_back(std::make_pair(CalleeV, Info)); } /// Record a call graph edge from this function to each function recorded /// in \p CallGraphEdges. void addCallGraphEdges(DenseMap<const Value *, CalleeInfo> &CallGraphEdges) { for (auto &EI : CallGraphEdges) addCallGraphEdge(EI.first, EI.second); } /// Return the list of <CalleeValueInfo, CalleeInfo> pairs. std::vector<EdgeTy> &calls() { return CallGraphEdgeList; } const std::vector<EdgeTy> &calls() const { return CallGraphEdgeList; } }; /// \brief Global variable summary information to aid decisions and /// implementation of importing. /// /// Currently this doesn't add anything to the base \p GlobalValueSummary, /// but is a placeholder as additional info may be added to the summary /// for variables. class GlobalVarSummary : public GlobalValueSummary { public: /// Summary constructors. GlobalVarSummary(GVFlags Flags) : GlobalValueSummary(GlobalVarKind, Flags) {} /// Check if this is a global variable summary. static bool classof(const GlobalValueSummary *GVS) { return GVS->getSummaryKind() == GlobalVarKind; } }; /// 160 bits SHA1 typedef std::array<uint32_t, 5> ModuleHash; /// List of global value summary structures for a particular value held /// in the GlobalValueMap. Requires a vector in the case of multiple /// COMDAT values of the same name. typedef std::vector<std::unique_ptr<GlobalValueSummary>> GlobalValueSummaryList; /// Map from global value GUID to corresponding summary structures. /// Use a std::map rather than a DenseMap since it will likely incur /// less overhead, as the value type is not very small and the size /// of the map is unknown, resulting in inefficiencies due to repeated /// insertions and resizing. typedef std::map<GlobalValue::GUID, GlobalValueSummaryList> GlobalValueSummaryMapTy; /// Type used for iterating through the global value summary map. typedef GlobalValueSummaryMapTy::const_iterator const_gvsummary_iterator; typedef GlobalValueSummaryMapTy::iterator gvsummary_iterator; /// String table to hold/own module path strings, which additionally holds the /// module ID assigned to each module during the plugin step, as well as a hash /// of the module. The StringMap makes a copy of and owns inserted strings. typedef StringMap<std::pair<uint64_t, ModuleHash>> ModulePathStringTableTy; /// Map of global value GUID to its summary, used to identify values defined in /// a particular module, and provide efficient access to their summary. typedef std::map<GlobalValue::GUID, GlobalValueSummary *> GVSummaryMapTy; /// Class to hold module path string table and global value map, /// and encapsulate methods for operating on them. class ModuleSummaryIndex { private: /// Map from value name to list of summary instances for values of that /// name (may be duplicates in the COMDAT case, e.g.). GlobalValueSummaryMapTy GlobalValueMap; /// Holds strings for combined index, mapping to the corresponding module ID. ModulePathStringTableTy ModulePathStringTable; public: ModuleSummaryIndex() = default; // Disable the copy constructor and assignment operators, so // no unexpected copying/moving occurs. ModuleSummaryIndex(const ModuleSummaryIndex &) = delete; void operator=(const ModuleSummaryIndex &) = delete; gvsummary_iterator begin() { return GlobalValueMap.begin(); } const_gvsummary_iterator begin() const { return GlobalValueMap.begin(); } gvsummary_iterator end() { return GlobalValueMap.end(); } const_gvsummary_iterator end() const { return GlobalValueMap.end(); } /// Get the list of global value summary objects for a given value name. const GlobalValueSummaryList &getGlobalValueSummaryList(StringRef ValueName) { return GlobalValueMap[GlobalValue::getGUID(ValueName)]; } /// Get the list of global value summary objects for a given value name. const const_gvsummary_iterator findGlobalValueSummaryList(StringRef ValueName) const { return GlobalValueMap.find(GlobalValue::getGUID(ValueName)); } /// Get the list of global value summary objects for a given value GUID. const const_gvsummary_iterator findGlobalValueSummaryList(GlobalValue::GUID ValueGUID) const { return GlobalValueMap.find(ValueGUID); } /// Add a global value summary for a value of the given name. void addGlobalValueSummary(StringRef ValueName, std::unique_ptr<GlobalValueSummary> Summary) { GlobalValueMap[GlobalValue::getGUID(ValueName)].push_back( std::move(Summary)); } /// Add a global value summary for a value of the given GUID. void addGlobalValueSummary(GlobalValue::GUID ValueGUID, std::unique_ptr<GlobalValueSummary> Summary) { GlobalValueMap[ValueGUID].push_back(std::move(Summary)); } /// Find the summary for global \p GUID in module \p ModuleId, or nullptr if /// not found. GlobalValueSummary *findSummaryInModule(GlobalValue::GUID ValueGUID, StringRef ModuleId) const { auto CalleeInfoList = findGlobalValueSummaryList(ValueGUID); if (CalleeInfoList == end()) { return nullptr; // This function does not have a summary } auto Summary = llvm::find_if(CalleeInfoList->second, [&](const std::unique_ptr<GlobalValueSummary> &Summary) { return Summary->modulePath() == ModuleId; }); if (Summary == CalleeInfoList->second.end()) return nullptr; return Summary->get(); } /// Returns the first GlobalValueSummary for \p GV, asserting that there /// is only one if \p PerModuleIndex. GlobalValueSummary *getGlobalValueSummary(const GlobalValue &GV, bool PerModuleIndex = true) const { assert(GV.hasName() && "Can't get GlobalValueSummary for GV with no name"); return getGlobalValueSummary(GlobalValue::getGUID(GV.getName()), PerModuleIndex); } /// Returns the first GlobalValueSummary for \p ValueGUID, asserting that /// there /// is only one if \p PerModuleIndex. GlobalValueSummary *getGlobalValueSummary(GlobalValue::GUID ValueGUID, bool PerModuleIndex = true) const; /// Table of modules, containing module hash and id. const StringMap<std::pair<uint64_t, ModuleHash>> &modulePaths() const { return ModulePathStringTable; } /// Table of modules, containing hash and id. StringMap<std::pair<uint64_t, ModuleHash>> &modulePaths() { return ModulePathStringTable; } /// Get the module ID recorded for the given module path. uint64_t getModuleId(const StringRef ModPath) const { return ModulePathStringTable.lookup(ModPath).first; } /// Get the module SHA1 hash recorded for the given module path. const ModuleHash &getModuleHash(const StringRef ModPath) const { auto It = ModulePathStringTable.find(ModPath); assert(It != ModulePathStringTable.end() && "Module not registered"); return It->second.second; } /// Add the given per-module index into this module index/summary, /// assigning it the given module ID. Each module merged in should have /// a unique ID, necessary for consistent renaming of promoted /// static (local) variables. void mergeFrom(std::unique_ptr<ModuleSummaryIndex> Other, uint64_t NextModuleId); /// Convenience method for creating a promoted global name /// for the given value name of a local, and its original module's ID. static std::string getGlobalNameForLocal(StringRef Name, ModuleHash ModHash) { SmallString<256> NewName(Name); NewName += ".llvm."; NewName += utohexstr(ModHash[0]); // Take the first 32 bits return NewName.str(); } /// Helper to obtain the unpromoted name for a global value (or the original /// name if not promoted). static StringRef getOriginalNameBeforePromote(StringRef Name) { std::pair<StringRef, StringRef> Pair = Name.split(".llvm."); return Pair.first; } /// Add a new module path with the given \p Hash, mapped to the given \p /// ModID, and return an iterator to the entry in the index. ModulePathStringTableTy::iterator addModulePath(StringRef ModPath, uint64_t ModId, ModuleHash Hash = ModuleHash{{0}}) { return ModulePathStringTable.insert(std::make_pair( ModPath, std::make_pair(ModId, Hash))).first; } /// Check if the given Module has any functions available for exporting /// in the index. We consider any module present in the ModulePathStringTable /// to have exported functions. bool hasExportedFunctions(const Module &M) const { return ModulePathStringTable.count(M.getModuleIdentifier()); } /// Remove entries in the GlobalValueMap that have empty summaries due to the /// eager nature of map entry creation during VST parsing. These would /// also be suppressed during combined index generation in mergeFrom(), /// but if there was only one module or this was the first module we might /// not invoke mergeFrom. void removeEmptySummaryEntries(); /// Collect for the given module the list of function it defines /// (GUID -> Summary). void collectDefinedFunctionsForModule(StringRef ModulePath, GVSummaryMapTy &GVSummaryMap) const; /// Collect for each module the list of Summaries it defines (GUID -> /// Summary). void collectDefinedGVSummariesPerModule( StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries) const; }; } // End llvm namespace #endif
[ "sebi@quantstamp.com" ]
sebi@quantstamp.com
5b81af19dd2658ff8fe2a0a61306c3b37416112b
9f66154581e21d4f77ebad91a40884cfca0a4e58
/Hash.cpp
241c93974b63f52a7ce6624291d2143a54413386
[]
no_license
rogday/algs
d41f1a3a0dd11a988981634b6d660de0411a2575
09d0690131ce8a15919fca3f75c55dd0eb57da52
refs/heads/master
2021-05-07T21:39:29.387521
2018-11-30T21:42:33
2018-11-30T21:42:33
109,047,913
0
0
null
null
null
null
UTF-8
C++
false
false
460
cpp
#include "Hash.h" #include <iostream> #include <random> using namespace std; int main() { srand(time(nullptr)); Hash table(20000); int n; string str; for (int j = 0; j < 20; ++j) { for (int i = 0; i < 20000 - j * 1000; ++i) { n = 1 + rand() % 100; for (int k = 0; k < n; ++k) str += 1 + rand() % 254; table[str] = true; str.clear(); } cout << table.getCollisions() << endl; table.clear(); } }
[ "s.e.a.98@yandex.ru" ]
s.e.a.98@yandex.ru
b1d4d46ee3a284ab2b3dc796f1d6e5eaed85c760
4d5f2cdc0b7120f74ba6f357b21dac063e71b606
/xercesc/xerces-c1_7_0-win32/samples/SAXCount/SAXCount.hpp
e07b8e20aeb6c2f82781a26a1d276ed8c14cab47
[ "Apache-1.1", "Apache-2.0", "BSD-2-Clause" ]
permissive
anjingbin/starccm
cf499238ceb1e4f0235421cb6f3cb823b932a2cd
70db48004aa20bbb82cc24de80802b40c7024eff
refs/heads/master
2021-01-11T19:49:04.306906
2017-01-19T02:02:50
2017-01-19T02:02:50
79,404,002
2
0
null
null
null
null
UTF-8
C++
false
false
5,292
hpp
/* * The Apache Software License, Version 1.1 * * Copyright (c) 1999-2000 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * $Log: SAXCount.hpp,v $ * Revision 1.1 2003/11/12 01:58:43 AnJingBin * *** empty log message *** * * Revision 1.1 2003/10/23 20:58:30 AnJingBin * *** empty log message *** * * Revision 1.5 2002/02/01 22:41:07 peiyongz * sane_include * * Revision 1.4 2000/03/02 19:53:47 roddey * This checkin includes many changes done while waiting for the * 1.1.0 code to be finished. I can't list them all here, but a list is * available elsewhere. * * Revision 1.3 2000/02/11 02:46:39 abagchi * Removed StrX::transcode * * Revision 1.2 2000/02/06 07:47:23 rahulj * Year 2K copyright swat. * * Revision 1.1.1.1 1999/11/09 01:09:31 twl * Initial checkin * * Revision 1.5 1999/11/08 20:43:40 rahul * Swat for adding in Product name and CVS comment log variable. * */ // --------------------------------------------------------------------------- // Includes for all the program files to see // --------------------------------------------------------------------------- #include <stdlib.h> #include <string.h> #include <iostream.h> #include <xercesc/util/PlatformUtils.hpp> #include <xercesc/parsers/SAXParser.hpp> #include "SAXCountHandlers.hpp" // --------------------------------------------------------------------------- // This is a simple class that lets us do easy (though not terribly efficient) // trancoding of XMLCh data to local code page for display. // --------------------------------------------------------------------------- class StrX { public : // ----------------------------------------------------------------------- // Constructors and Destructor // ----------------------------------------------------------------------- StrX(const XMLCh* const toTranscode) { // Call the private transcoding method fLocalForm = XMLString::transcode(toTranscode); } ~StrX() { delete [] fLocalForm; } // ----------------------------------------------------------------------- // Getter methods // ----------------------------------------------------------------------- const char* localForm() const { return fLocalForm; } private : // ----------------------------------------------------------------------- // Private data members // // fLocalForm // This is the local code page form of the string. // ----------------------------------------------------------------------- char* fLocalForm; }; inline ostream& operator<<(ostream& target, const StrX& toDump) { target << toDump.localForm(); return target; }
[ "anjb@qkjr.com.cn" ]
anjb@qkjr.com.cn
f0ac5d3d9563040d969cbc51a80bb35135475379
438089df0a020dc8205a4b0df2a08e510f40fd3c
/extern/renderdoc/renderdoc/driver/shaders/dxbc/dxbc_container.cpp
26c3181fc4771e15c6d5209e2a3ad78afca89d71
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
minh0722/basic-directx11
59b5bbcc5de6ccf5f26fa68493d11512b20e5971
9e0b24d42497688fd5193327110432ab262234cf
refs/heads/master
2021-08-16T03:11:48.626639
2021-01-20T23:45:33
2021-01-20T23:45:33
72,579,642
0
0
null
null
null
null
UTF-8
C++
false
false
52,390
cpp
/****************************************************************************** * The MIT License (MIT) * * Copyright (c) 2019-2020 Baldur Karlsson * Copyright (c) 2014 Crytek * * 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 "dxbc_container.h" #include <algorithm> #include "api/app/renderdoc_app.h" #include "common/common.h" #include "driver/shaders/dxil/dxil_bytecode.h" #include "serialise/serialiser.h" #include "strings/string_utils.h" #include "dxbc_bytecode.h" #include "driver/dx/official/d3dcompiler.h" namespace DXBC { struct RDEFCBufferVariable { uint32_t nameOffset; uint32_t startOffset; // start offset in bytes of this variable in the cbuffer uint32_t size; // size in bytes of this type uint32_t flags; uint32_t typeOffset; // offset to a RDEFCBufferType uint32_t defaultValueOffset; // offset to [size] bytes where the default value can be found, or // 0 for no default value uint32_t unknown[4]; // this is only present for RDEFHeader.targetVersion >= 0x500. In earlier // versions, this is not in the file. }; struct RDEFCBuffer { uint32_t nameOffset; // relative to the same offset base position as others in this chunk - // after FourCC and chunk length. DXBC::CountOffset variables; uint32_t size; // size in bytes of this cbuffer uint32_t flags; uint32_t type; // followed immediately by [variables.count] RDEFCBufferVariables }; // mostly for nested structures struct RDEFCBufferChildType { uint32_t nameOffset; uint32_t typeOffset; // offset to a RDEFCBufferType uint32_t memberOffset; // byte offset in the parent structure - not a file offset }; struct RDEFCBufferType { uint16_t varClass; // D3D_SHADER_VARIABLE_CLASS uint16_t varType; // D3D_SHADER_VARIABLE_TYPE uint16_t rows; uint16_t cols; uint16_t numElems; uint16_t numMembers; uint32_t memberOffset; // offset to [numMembers] RDEFCBufferChildTypes that point to the member // types // my own guessing - not in wine structures // looks like these are only present for RD11 shaders uint32_t unknown[4]; uint32_t nameOffset; // offset to type name }; // this isn't a proper chunk, it's the file header before all the chunks. struct FileHeader { uint32_t fourcc; // "DXBC" uint32_t hashValue[4]; // unknown hash function and data uint32_t unknown; uint32_t fileLength; uint32_t numChunks; // uint32 chunkOffsets[numChunks]; follows }; struct ILDNHeader { uint16_t Flags; uint16_t NameLength; char Name[1]; }; struct RDEFHeader { ////////////////////////////////////////////////////// // offsets are relative to this position in the file. // NOT the end of this structure. Note this differs // from the SDBG chunk, but matches the SIGN chunks // note that these two actually come in the opposite order after // this header. So cbuffers offset will be higher than resources // offset CountOffset cbuffers; CountOffset resources; uint16_t targetVersion; // 0x0501 is the latest. uint16_t targetShaderStage; // 0xffff for pixel shaders, 0xfffe for vertex shaders uint32_t flags; uint32_t creatorOffset; // null terminated ascii string uint32_t unknown[8]; // this is only present for targetVersion >= 0x500. In earlier versions, // this is not in the file. }; struct RDEFResource { uint32_t nameOffset; // relative to the same offset base position as others in this chunk - // after FourCC and chunk length. uint32_t type; uint32_t retType; uint32_t dimension; int32_t sampleCount; uint32_t bindPoint; uint32_t bindCount; uint32_t flags; // this is only present for RDEFHeader.targetVersion >= 0x501. uint32_t space; // the ID seems to be a 0-based name fxc generates to refer to the object. // We don't use it, and it's easy enough to re-generate uint32_t ID; }; struct SIGNHeader { ////////////////////////////////////////////////////// // offsets are relative to this position in the file. // NOT the end of this structure. Note this differs // from the SDBG chunk, but matches the RDEF chunk uint32_t numElems; uint32_t unknown; // followed by SIGNElement elements[numElems]; - note that SIGNElement's size depends on the type. // for OSG5 you should use SIGNElement7 }; struct PRIVHeader { uint32_t fourcc; // "PRIV" uint32_t chunkLength; // length of this chunk GUID debugInfoGUID; // GUID/magic number, since PRIV data could be used for something else. // Set to the value of RENDERDOC_ShaderDebugMagicValue from // renderdoc_app.h which can also be used as a GUID to set the path // at runtime via SetPrivateData (see documentation) static const GUID RENDERDOC_ShaderDebugMagicValue; void *data; }; const GUID PRIVHeader::RENDERDOC_ShaderDebugMagicValue = RENDERDOC_ShaderDebugMagicValue_struct; struct SIGNElement { uint32_t nameOffset; // relative to the same offset base position as others in similar chunks - // after FourCC and chunk length. uint32_t semanticIdx; SVSemantic systemType; uint32_t componentType; uint32_t registerNum; byte mask; byte rwMask; uint16_t unused; }; struct SIGNElement7 { uint32_t stream; SIGNElement elem; }; enum MinimumPrecision { PRECISION_DEFAULT, PRECISION_FLOAT16, PRECISION_FLOAT10, PRECISION_UNUSED, PRECISION_SINT16, PRECISION_UINT16, PRECISION_ANY16, PRECISION_ANY10, NUM_PRECISIONS, }; struct SIGNElement1 { uint32_t stream; SIGNElement elem; MinimumPrecision precision; }; static const uint32_t STATSizeDX10 = 29 * 4; // either 29 uint32s static const uint32_t STATSizeDX11 = 37 * 4; // or 37 uint32s static const uint32_t FOURCC_DXBC = MAKE_FOURCC('D', 'X', 'B', 'C'); static const uint32_t FOURCC_RDEF = MAKE_FOURCC('R', 'D', 'E', 'F'); static const uint32_t FOURCC_RD11 = MAKE_FOURCC('R', 'D', '1', '1'); static const uint32_t FOURCC_STAT = MAKE_FOURCC('S', 'T', 'A', 'T'); static const uint32_t FOURCC_SHEX = MAKE_FOURCC('S', 'H', 'E', 'X'); static const uint32_t FOURCC_SHDR = MAKE_FOURCC('S', 'H', 'D', 'R'); static const uint32_t FOURCC_SDBG = MAKE_FOURCC('S', 'D', 'B', 'G'); static const uint32_t FOURCC_SPDB = MAKE_FOURCC('S', 'P', 'D', 'B'); static const uint32_t FOURCC_ISGN = MAKE_FOURCC('I', 'S', 'G', 'N'); static const uint32_t FOURCC_OSGN = MAKE_FOURCC('O', 'S', 'G', 'N'); static const uint32_t FOURCC_ISG1 = MAKE_FOURCC('I', 'S', 'G', '1'); static const uint32_t FOURCC_OSG1 = MAKE_FOURCC('O', 'S', 'G', '1'); static const uint32_t FOURCC_OSG5 = MAKE_FOURCC('O', 'S', 'G', '5'); static const uint32_t FOURCC_PCSG = MAKE_FOURCC('P', 'C', 'S', 'G'); static const uint32_t FOURCC_Aon9 = MAKE_FOURCC('A', 'o', 'n', '9'); static const uint32_t FOURCC_PRIV = MAKE_FOURCC('P', 'R', 'I', 'V'); static const uint32_t FOURCC_DXIL = MAKE_FOURCC('D', 'X', 'I', 'L'); static const uint32_t FOURCC_ILDB = MAKE_FOURCC('I', 'L', 'D', 'B'); static const uint32_t FOURCC_ILDN = MAKE_FOURCC('I', 'L', 'D', 'N'); int TypeByteSize(VariableType t) { switch(t) { case VARTYPE_UINT8: return 1; case VARTYPE_BOOL: case VARTYPE_INT: case VARTYPE_FLOAT: case VARTYPE_UINT: return 4; // we pretend for our purposes that the 'min' formats round up to 4 bytes. For any external // interfaces they are treated as regular types, only using lower precision internally. case VARTYPE_MIN8FLOAT: case VARTYPE_MIN10FLOAT: case VARTYPE_MIN16FLOAT: case VARTYPE_MIN12INT: case VARTYPE_MIN16INT: case VARTYPE_MIN16UINT: return 4; case VARTYPE_DOUBLE: return 8; // 'virtual' type. Just return 1 case VARTYPE_INTERFACE_POINTER: return 1; default: RDCERR("Trying to take size of undefined type %d", t); return 1; } } ShaderBuiltin GetSystemValue(SVSemantic systemValue) { switch(systemValue) { case SVNAME_UNDEFINED: return ShaderBuiltin::Undefined; case SVNAME_POSITION: return ShaderBuiltin::Position; case SVNAME_CLIP_DISTANCE: return ShaderBuiltin::ClipDistance; case SVNAME_CULL_DISTANCE: return ShaderBuiltin::CullDistance; case SVNAME_RENDER_TARGET_ARRAY_INDEX: return ShaderBuiltin::RTIndex; case SVNAME_VIEWPORT_ARRAY_INDEX: return ShaderBuiltin::ViewportIndex; case SVNAME_VERTEX_ID: return ShaderBuiltin::VertexIndex; case SVNAME_PRIMITIVE_ID: return ShaderBuiltin::PrimitiveIndex; case SVNAME_INSTANCE_ID: return ShaderBuiltin::InstanceIndex; case SVNAME_IS_FRONT_FACE: return ShaderBuiltin::IsFrontFace; case SVNAME_SAMPLE_INDEX: return ShaderBuiltin::MSAASampleIndex; case SVNAME_FINAL_QUAD_EDGE_TESSFACTOR0: case SVNAME_FINAL_QUAD_EDGE_TESSFACTOR1: case SVNAME_FINAL_QUAD_EDGE_TESSFACTOR2: case SVNAME_FINAL_QUAD_EDGE_TESSFACTOR3: return ShaderBuiltin::OuterTessFactor; case SVNAME_FINAL_QUAD_INSIDE_TESSFACTOR0: case SVNAME_FINAL_QUAD_INSIDE_TESSFACTOR1: return ShaderBuiltin::InsideTessFactor; case SVNAME_FINAL_TRI_EDGE_TESSFACTOR0: case SVNAME_FINAL_TRI_EDGE_TESSFACTOR1: case SVNAME_FINAL_TRI_EDGE_TESSFACTOR2: return ShaderBuiltin::OuterTessFactor; case SVNAME_FINAL_TRI_INSIDE_TESSFACTOR: return ShaderBuiltin::InsideTessFactor; case SVNAME_FINAL_LINE_DETAIL_TESSFACTOR: return ShaderBuiltin::OuterTessFactor; case SVNAME_FINAL_LINE_DENSITY_TESSFACTOR: return ShaderBuiltin::InsideTessFactor; case SVNAME_TARGET: return ShaderBuiltin::ColorOutput; case SVNAME_DEPTH: return ShaderBuiltin::DepthOutput; case SVNAME_COVERAGE: return ShaderBuiltin::MSAACoverage; case SVNAME_DEPTH_GREATER_EQUAL: return ShaderBuiltin::DepthOutputGreaterEqual; case SVNAME_DEPTH_LESS_EQUAL: return ShaderBuiltin::DepthOutputLessEqual; } return ShaderBuiltin::Undefined; } rdcstr TypeName(CBufferVariableType::Descriptor desc) { rdcstr ret; char *type = ""; switch(desc.type) { case VARTYPE_BOOL: type = "bool"; break; case VARTYPE_INT: type = "int"; break; case VARTYPE_FLOAT: type = "float"; break; case VARTYPE_DOUBLE: type = "double"; break; case VARTYPE_UINT: type = "uint"; break; case VARTYPE_UINT8: type = "ubyte"; break; case VARTYPE_VOID: type = "void"; break; case VARTYPE_INTERFACE_POINTER: type = "interface"; break; case VARTYPE_MIN8FLOAT: type = "min8float"; break; case VARTYPE_MIN10FLOAT: type = "min10float"; break; case VARTYPE_MIN16FLOAT: type = "min16float"; break; case VARTYPE_MIN12INT: type = "min12int"; break; case VARTYPE_MIN16INT: type = "min16int"; break; case VARTYPE_MIN16UINT: type = "min16uint"; break; default: RDCERR("Unexpected type in RDEF variable type %d", type); } if(desc.varClass == CLASS_OBJECT) RDCERR("Unexpected object in RDEF variable type"); else if(desc.varClass == CLASS_INTERFACE_CLASS) RDCERR("Unexpected iface class in RDEF variable type"); else if(desc.varClass == CLASS_INTERFACE_POINTER) ret = type; else if(desc.varClass == CLASS_STRUCT) ret = "<unnamed>"; else { if(desc.rows > 1) { ret = StringFormat::Fmt("%s%dx%d", type, desc.rows, desc.cols); if(desc.varClass == CLASS_MATRIX_ROWS) { ret = "row_major " + ret; } } else if(desc.cols > 1) { ret = StringFormat::Fmt("%s%d", type, desc.cols); } else { ret = type; } } return ret; } CBufferVariableType DXBCContainer::ParseRDEFType(RDEFHeader *h, char *chunkContents, uint32_t typeOffset) { if(m_Variables.find(typeOffset) != m_Variables.end()) return m_Variables[typeOffset]; RDEFCBufferType *type = (RDEFCBufferType *)(chunkContents + typeOffset); CBufferVariableType ret; ret.descriptor.varClass = (VariableClass)type->varClass; ret.descriptor.cols = type->cols; ret.descriptor.elements = type->numElems; ret.descriptor.members = type->numMembers; ret.descriptor.rows = type->rows; ret.descriptor.type = (VariableType)type->varType; ret.descriptor.name = TypeName(ret.descriptor); if(ret.descriptor.name == "interface") { if(h->targetVersion >= 0x500 && type->nameOffset > 0) { ret.descriptor.name += " " + rdcstr(chunkContents + type->nameOffset); } else { ret.descriptor.name += StringFormat::Fmt(" unnamed_iface_0x%08x", typeOffset); } } // rename unnamed structs to have valid identifiers as type name if(ret.descriptor.name.contains("<unnamed>")) { if(h->targetVersion >= 0x500 && type->nameOffset > 0) { ret.descriptor.name = chunkContents + type->nameOffset; } else { ret.descriptor.name = StringFormat::Fmt("unnamed_struct_0x%08x", typeOffset); } } if(type->memberOffset) { RDEFCBufferChildType *members = (RDEFCBufferChildType *)(chunkContents + type->memberOffset); ret.members.reserve(type->numMembers); ret.descriptor.bytesize = 0; for(int32_t j = 0; j < type->numMembers; j++) { CBufferVariable v; v.name = chunkContents + members[j].nameOffset; v.type = ParseRDEFType(h, chunkContents, members[j].typeOffset); v.descriptor.offset = members[j].memberOffset; ret.descriptor.bytesize = v.descriptor.offset + v.type.descriptor.bytesize; // N/A v.descriptor.flags = 0; v.descriptor.startTexture = 0; v.descriptor.numTextures = 0; v.descriptor.startSampler = 0; v.descriptor.numSamplers = 0; v.descriptor.defaultValue.clear(); ret.members.push_back(v); } ret.descriptor.bytesize *= RDCMAX(1U, ret.descriptor.elements); } else { // matrices take up a full vector for each column or row depending which is major, regardless of // the other dimension if(ret.descriptor.varClass == CLASS_MATRIX_COLUMNS) { ret.descriptor.bytesize = TypeByteSize(ret.descriptor.type) * ret.descriptor.cols * 4 * RDCMAX(1U, ret.descriptor.elements); } else if(ret.descriptor.varClass == CLASS_MATRIX_ROWS) { ret.descriptor.bytesize = TypeByteSize(ret.descriptor.type) * ret.descriptor.rows * 4 * RDCMAX(1U, ret.descriptor.elements); } else { // arrays also take up a full vector for each element if(ret.descriptor.elements > 1) ret.descriptor.bytesize = TypeByteSize(ret.descriptor.type) * 4 * RDCMAX(1U, ret.descriptor.elements); else ret.descriptor.bytesize = TypeByteSize(ret.descriptor.type) * ret.descriptor.rows * ret.descriptor.cols; } } m_Variables[typeOffset] = ret; return ret; } D3D_PRIMITIVE_TOPOLOGY DXBCContainer::GetOutputTopology() { if(m_OutputTopology == D3D_PRIMITIVE_TOPOLOGY_UNDEFINED) { m_OutputTopology = D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST; if(m_DXBCByteCode) m_OutputTopology = m_DXBCByteCode->GetOutputTopology(); else if(m_DXILByteCode) m_OutputTopology = m_DXILByteCode->GetOutputTopology(); } return m_OutputTopology; } const rdcstr &DXBCContainer::GetDisassembly() { if(m_Disassembly.empty()) { uint32_t *hash = (uint32_t *)&m_ShaderBlob[4]; // hash is 4 uints, starting after the FOURCC of 'DXBC' m_Disassembly = StringFormat::Fmt("Shader hash %08x-%08x-%08x-%08x\n\n", hash[0], hash[1], hash[2], hash[3]); if(m_DXBCByteCode) m_Disassembly += m_DXBCByteCode->GetDisassembly(); else if(m_DXILByteCode) m_Disassembly += m_DXILByteCode->GetDisassembly(); } return m_Disassembly; } void DXBCContainer::GetHash(uint32_t hash[4], const void *ByteCode, size_t BytecodeLength) { if(BytecodeLength < sizeof(FileHeader)) { memset(hash, 0, sizeof(uint32_t) * 4); return; } FileHeader *header = (FileHeader *)ByteCode; memcpy(hash, header->hashValue, sizeof(header->hashValue)); } bool DXBCContainer::CheckForDebugInfo(const void *ByteCode, size_t ByteCodeLength) { FileHeader *header = (FileHeader *)ByteCode; char *data = (char *)ByteCode; // just for convenience if(header->fourcc != FOURCC_DXBC) return false; if(header->fileLength != (uint32_t)ByteCodeLength) return false; uint32_t *chunkOffsets = (uint32_t *)(header + 1); // right after the header for(uint32_t chunkIdx = 0; chunkIdx < header->numChunks; chunkIdx++) { uint32_t *fourcc = (uint32_t *)(data + chunkOffsets[chunkIdx]); if(*fourcc == FOURCC_SDBG) { return true; } else if(*fourcc == FOURCC_SPDB) { return true; } } return false; } bool DXBCContainer::CheckForShaderCode(const void *ByteCode, size_t ByteCodeLength) { FileHeader *header = (FileHeader *)ByteCode; char *data = (char *)ByteCode; // just for convenience if(header->fourcc != FOURCC_DXBC) return false; if(header->fileLength != (uint32_t)ByteCodeLength) return false; uint32_t *chunkOffsets = (uint32_t *)(header + 1); // right after the header for(uint32_t chunkIdx = 0; chunkIdx < header->numChunks; chunkIdx++) { uint32_t *fourcc = (uint32_t *)(data + chunkOffsets[chunkIdx]); if(*fourcc == FOURCC_SHEX || *fourcc == FOURCC_SHDR) return true; } return false; } rdcstr DXBCContainer::GetDebugBinaryPath(const void *ByteCode, size_t ByteCodeLength) { rdcstr debugPath; FileHeader *header = (FileHeader *)ByteCode; char *data = (char *)ByteCode; // just for convenience if(header->fourcc != FOURCC_DXBC) return debugPath; if(header->fileLength != (uint32_t)ByteCodeLength) return debugPath; uint32_t *chunkOffsets = (uint32_t *)(header + 1); // right after the header for(uint32_t chunkIdx = 0; chunkIdx < header->numChunks; chunkIdx++) { uint32_t *fourcc = (uint32_t *)(data + chunkOffsets[chunkIdx]); if(*fourcc == FOURCC_PRIV) { PRIVHeader *privHeader = (PRIVHeader *)fourcc; if(privHeader->debugInfoGUID == PRIVHeader::RENDERDOC_ShaderDebugMagicValue) { const char *pathData = (char *)&privHeader->data; size_t pathLength = strnlen(pathData, privHeader->chunkLength); if(privHeader->chunkLength == (sizeof(GUID) + pathLength + 1)) { debugPath.append(pathData, pathLength); return debugPath; } } } } return debugPath; } DXBCContainer::DXBCContainer(const void *ByteCode, size_t ByteCodeLength) { RDCASSERT(ByteCodeLength < UINT32_MAX); RDCEraseEl(m_ShaderStats); m_ShaderBlob.resize(ByteCodeLength); memcpy(&m_ShaderBlob[0], ByteCode, m_ShaderBlob.size()); char *data = (char *)&m_ShaderBlob[0]; // just for convenience FileHeader *header = (FileHeader *)&m_ShaderBlob[0]; if(header->fourcc != FOURCC_DXBC) return; if(header->fileLength != (uint32_t)ByteCodeLength) return; // default to vertex shader to support blobs without RDEF chunks (e.g. used with // input layouts if they're super stripped down) m_Type = DXBC::ShaderType::Vertex; uint32_t *chunkOffsets = (uint32_t *)(header + 1); // right after the header for(uint32_t chunkIdx = 0; chunkIdx < header->numChunks; chunkIdx++) { uint32_t *fourcc = (uint32_t *)(data + chunkOffsets[chunkIdx]); uint32_t *chunkSize = (uint32_t *)(fourcc + 1); char *chunkContents = (char *)(chunkSize + 1); if(*fourcc == FOURCC_RDEF) { RDEFHeader *h = (RDEFHeader *)chunkContents; // for target version 0x500, unknown[0] is FOURCC_RD11. // for 0x501 it's "\x13\x13\D%" m_Reflection = new Reflection; if(h->targetShaderStage == 0xffff) m_Type = DXBC::ShaderType::Pixel; else if(h->targetShaderStage == 0xfffe) m_Type = DXBC::ShaderType::Vertex; else if(h->targetShaderStage == 0x4753) // 'GS' m_Type = DXBC::ShaderType::Geometry; else if(h->targetShaderStage == 0x4853) // 'HS' m_Type = DXBC::ShaderType::Hull; else if(h->targetShaderStage == 0x4453) // 'DS' m_Type = DXBC::ShaderType::Domain; else if(h->targetShaderStage == 0x4353) // 'CS' m_Type = DXBC::ShaderType::Compute; m_Reflection->SRVs.reserve(h->resources.count); m_Reflection->UAVs.reserve(h->resources.count); m_Reflection->Samplers.reserve(h->resources.count); struct CBufferBind { uint32_t reg, space, bindCount; }; std::map<rdcstr, CBufferBind> cbufferbinds; uint32_t resourceStride = sizeof(RDEFResource); // versions before 5.1 don't have the space and ID if(h->targetVersion < 0x501) { resourceStride -= sizeof(RDEFResource) - offsetof(RDEFResource, space); } for(int32_t i = 0; i < h->resources.count; i++) { RDEFResource *res = (RDEFResource *)(chunkContents + h->resources.offset + i * resourceStride); ShaderInputBind desc; desc.name = chunkContents + res->nameOffset; desc.type = (ShaderInputBind::InputType)res->type; desc.space = h->targetVersion >= 0x501 ? res->space : 0; desc.reg = res->bindPoint; desc.bindCount = res->bindCount; desc.flags = res->flags; desc.retType = (DXBC::ResourceRetType)res->retType; desc.dimension = (ShaderInputBind::Dimension)res->dimension; desc.numSamples = res->sampleCount; if(desc.numSamples == ~0 && desc.retType != RETURN_TYPE_MIXED && desc.retType != RETURN_TYPE_UNKNOWN && desc.retType != RETURN_TYPE_CONTINUED) { // uint, uint2, uint3, uint4 seem to be in these bits of flags. desc.numSamples = 1 + ((desc.flags & 0xC) >> 2); } // for cbuffers the names can be duplicated, so handle this by assuming // the order will match between binding declaration and cbuffer declaration // and append _s onto each subsequent buffer name if(desc.IsCBuffer()) { rdcstr cname = desc.name; while(cbufferbinds.find(cname) != cbufferbinds.end()) cname += "_"; CBufferBind cb; cb.space = desc.space; cb.reg = desc.reg; cb.bindCount = desc.bindCount; cbufferbinds[cname] = cb; } else if(desc.IsSampler()) { m_Reflection->Samplers.push_back(desc); } else if(desc.IsSRV()) { m_Reflection->SRVs.push_back(desc); } else if(desc.IsUAV()) { m_Reflection->UAVs.push_back(desc); } else { RDCERR("Unexpected type of resource: %u", desc.type); } } // Expand out any array resources. We deliberately place these at the end of the resources // array, so that any non-array resources can be picked up first before any arrays. // // The reason for this is that an array element could refer to an un-used alias in a bind // point, and an individual non-array resoruce will always refer to the used alias (an // un-used individual resource will be omitted entirely from the reflection // // Note we preserve the arrays in SM5.1 if(h->targetVersion < 0x501) { for(rdcarray<ShaderInputBind> *arr : {&m_Reflection->SRVs, &m_Reflection->UAVs, &m_Reflection->Samplers}) { rdcarray<ShaderInputBind> &resArray = *arr; for(size_t i = 0; i < resArray.size();) { if(resArray[i].bindCount > 1) { // remove the item from the array at this location ShaderInputBind desc = resArray.takeAt(i); rdcstr rname = desc.name; uint32_t arraySize = desc.bindCount; desc.bindCount = 1; for(uint32_t a = 0; a < arraySize; a++) { desc.name = StringFormat::Fmt("%s[%u]", rname.c_str(), a); resArray.push_back(desc); desc.reg++; } continue; } // just move on if this item wasn't arrayed i++; } } } std::set<rdcstr> cbuffernames; for(int32_t i = 0; i < h->cbuffers.count; i++) { RDEFCBuffer *cbuf = (RDEFCBuffer *)(chunkContents + h->cbuffers.offset + i * sizeof(RDEFCBuffer)); CBuffer cb; // I have no real justification for this, it seems some cbuffers are included that are // empty and have nameOffset = 0, fxc seems to skip them so I'll do the same. // See github issue #122 if(cbuf->nameOffset == 0) continue; cb.name = chunkContents + cbuf->nameOffset; cb.descriptor.name = chunkContents + cbuf->nameOffset; cb.descriptor.byteSize = cbuf->size; cb.descriptor.type = (CBuffer::Descriptor::Type)cbuf->type; cb.descriptor.flags = cbuf->flags; cb.descriptor.numVars = cbuf->variables.count; cb.variables.reserve(cbuf->variables.count); size_t varStride = sizeof(RDEFCBufferVariable); if(h->targetVersion < 0x500) { size_t extraData = sizeof(RDEFCBufferVariable) - offsetof(RDEFCBufferVariable, unknown); varStride -= extraData; // it seems in rare circumstances, this data is present even for targetVersion < 0x500. // use a heuristic to check if the lower stride would cause invalid-looking data // for variables. See github issue #122 if(cbuf->variables.count > 1) { RDEFCBufferVariable *var = (RDEFCBufferVariable *)(chunkContents + cbuf->variables.offset + varStride); if(var->nameOffset > ByteCodeLength) { varStride += extraData; } } } for(int32_t vi = 0; vi < cbuf->variables.count; vi++) { RDEFCBufferVariable *var = (RDEFCBufferVariable *)(chunkContents + cbuf->variables.offset + vi * varStride); RDCASSERT(var->nameOffset < ByteCodeLength); CBufferVariable v; v.name = chunkContents + var->nameOffset; v.descriptor.defaultValue.resize(var->size); if(var->defaultValueOffset && var->defaultValueOffset != ~0U) { memcpy(&v.descriptor.defaultValue[0], chunkContents + var->defaultValueOffset, var->size); } v.descriptor.name = v.name; // v.descriptor.bytesize = var->size; // size with cbuffer padding v.descriptor.offset = var->startOffset; v.descriptor.flags = var->flags; v.descriptor.startTexture = (uint32_t)-1; v.descriptor.startSampler = (uint32_t)-1; v.descriptor.numSamplers = 0; v.descriptor.numTextures = 0; v.type = ParseRDEFType(h, chunkContents, var->typeOffset); cb.variables.push_back(v); } rdcstr cname = cb.name; while(cbuffernames.find(cname) != cbuffernames.end()) cname += "_"; cbuffernames.insert(cname); cb.space = cbufferbinds[cname].space; cb.reg = cbufferbinds[cname].reg; cb.bindCount = cbufferbinds[cname].bindCount; if(cb.descriptor.type == CBuffer::Descriptor::TYPE_CBUFFER) { m_Reflection->CBuffers.push_back(cb); } else if(cb.descriptor.type == CBuffer::Descriptor::TYPE_RESOURCE_BIND_INFO) { RDCASSERT(cb.variables.size() == 1 && cb.variables[0].name == "$Element"); m_Reflection->ResourceBinds[cb.name] = cb.variables[0].type; } else if(cb.descriptor.type == CBuffer::Descriptor::TYPE_INTERFACE_POINTERS) { m_Reflection->Interfaces = cb; } else { RDCDEBUG("Unused information, buffer %d: %s", cb.descriptor.type, cb.descriptor.name.c_str()); } } } else if(*fourcc == FOURCC_STAT) { if(*chunkSize == STATSizeDX10) { memcpy(&m_ShaderStats, chunkContents, STATSizeDX10); m_ShaderStats.version = ShaderStatistics::STATS_DX10; } else if(*chunkSize == STATSizeDX11) { memcpy(&m_ShaderStats, chunkContents, STATSizeDX11); m_ShaderStats.version = ShaderStatistics::STATS_DX11; } else { RDCERR("Unexpected Unexpected STAT chunk version"); } } else if(*fourcc == FOURCC_SHEX || *fourcc == FOURCC_SHDR) { m_DXBCByteCode = new DXBCBytecode::Program((const byte *)chunkContents, *chunkSize); } else if(*fourcc == FOURCC_ILDN) { ILDNHeader *h = (ILDNHeader *)chunkContents; m_DebugFileName = rdcstr(h->Name, h->NameLength); } } if(m_DXBCByteCode == NULL) { // prefer ILDB if present for(uint32_t chunkIdx = 0; chunkIdx < header->numChunks; chunkIdx++) { uint32_t *fourcc = (uint32_t *)(data + chunkOffsets[chunkIdx]); uint32_t *chunkSize = (uint32_t *)(data + chunkOffsets[chunkIdx] + sizeof(uint32_t)); char *chunkContents = (char *)(data + chunkOffsets[chunkIdx] + sizeof(uint32_t) * 2); if(*fourcc == FOURCC_ILDB) { m_DXILByteCode = new DXIL::Program((const byte *)chunkContents, *chunkSize); } } // if we didn't find it, look for DXIL if(m_DXILByteCode == NULL) { for(uint32_t chunkIdx = 0; chunkIdx < header->numChunks; chunkIdx++) { uint32_t *fourcc = (uint32_t *)(data + chunkOffsets[chunkIdx]); uint32_t *chunkSize = (uint32_t *)(data + chunkOffsets[chunkIdx] + sizeof(uint32_t)); char *chunkContents = (char *)(data + chunkOffsets[chunkIdx] + sizeof(uint32_t) * 2); if(*fourcc == FOURCC_DXIL) { m_DXILByteCode = new DXIL::Program((const byte *)chunkContents, *chunkSize); } } } } // get type/version that's used regularly and cheap to fetch if(m_DXBCByteCode) { m_Type = m_DXBCByteCode->GetShaderType(); m_Version.Major = m_DXBCByteCode->GetMajorVersion(); m_Version.Minor = m_DXBCByteCode->GetMinorVersion(); m_DXBCByteCode->SetReflection(m_Reflection); } else if(m_DXILByteCode) { m_Type = m_DXILByteCode->GetShaderType(); m_Version.Major = m_DXILByteCode->GetMajorVersion(); m_Version.Minor = m_DXILByteCode->GetMinorVersion(); // m_DXILByteCode->SetReflection(m_Reflection); } // if reflection information was stripped, attempt to reverse engineer basic info from // declarations if(m_Reflection == NULL) { // need to disassemble now to guess resources if(m_DXBCByteCode) m_Reflection = m_DXBCByteCode->GuessReflection(); else if(m_DXILByteCode) m_Reflection = m_DXILByteCode->GetReflection(); else m_Reflection = new Reflection; } for(uint32_t chunkIdx = 0; chunkIdx < header->numChunks; chunkIdx++) { uint32_t *fourcc = (uint32_t *)(data + chunkOffsets[chunkIdx]); // uint32_t *chunkSize = (uint32_t *)(fourcc + 1); char *chunkContents = (char *)(fourcc + 2); if(*fourcc == FOURCC_ISGN || *fourcc == FOURCC_OSGN || *fourcc == FOURCC_ISG1 || *fourcc == FOURCC_OSG1 || *fourcc == FOURCC_OSG5 || *fourcc == FOURCC_PCSG) { SIGNHeader *sign = (SIGNHeader *)chunkContents; rdcarray<SigParameter> *sig = NULL; bool input = false; bool output = false; bool patch = false; if(*fourcc == FOURCC_ISGN || *fourcc == FOURCC_ISG1) { sig = &m_Reflection->InputSig; input = true; } if(*fourcc == FOURCC_OSGN || *fourcc == FOURCC_OSG1 || *fourcc == FOURCC_OSG5) { sig = &m_Reflection->OutputSig; output = true; } if(*fourcc == FOURCC_PCSG) { sig = &m_Reflection->PatchConstantSig; patch = true; } RDCASSERT(sig && sig->empty()); SIGNElement *el0 = (SIGNElement *)(sign + 1); SIGNElement7 *el7 = (SIGNElement7 *)el0; SIGNElement1 *el1 = (SIGNElement1 *)el0; for(uint32_t signIdx = 0; signIdx < sign->numElems; signIdx++) { SigParameter desc; const SIGNElement *el = el0; if(*fourcc == FOURCC_ISG1 || *fourcc == FOURCC_OSG1) { desc.stream = el1->stream; // discard el1->precision as we don't use it and don't want to pollute the common API // structures el = &el1->elem; } if(*fourcc == FOURCC_OSG5) { desc.stream = el7->stream; el = &el7->elem; } ComponentType compType = (ComponentType)el->componentType; desc.compType = CompType::Float; if(compType == COMPONENT_TYPE_UINT32) desc.compType = CompType::UInt; else if(compType == COMPONENT_TYPE_SINT32) desc.compType = CompType::SInt; else if(compType != COMPONENT_TYPE_FLOAT32) RDCERR("Unexpected component type in signature"); desc.regChannelMask = (uint8_t)(el->mask & 0xff); desc.channelUsedMask = (uint8_t)(el->rwMask & 0xff); desc.regIndex = el->registerNum; desc.semanticIndex = el->semanticIdx; desc.semanticName = chunkContents + el->nameOffset; desc.systemValue = GetSystemValue(el->systemType); desc.compCount = (desc.regChannelMask & 0x1 ? 1 : 0) + (desc.regChannelMask & 0x2 ? 1 : 0) + (desc.regChannelMask & 0x4 ? 1 : 0) + (desc.regChannelMask & 0x8 ? 1 : 0); RDCASSERT(m_Type != DXBC::ShaderType::Max); // pixel shader outputs with registers are always targets if(m_Type == DXBC::ShaderType::Pixel && output && desc.systemValue == ShaderBuiltin::Undefined && desc.regIndex >= 0 && desc.regIndex <= 16) desc.systemValue = ShaderBuiltin::ColorOutput; // check system value semantics if(desc.systemValue == ShaderBuiltin::Undefined) { if(!_stricmp(desc.semanticName.c_str(), "SV_Position")) desc.systemValue = ShaderBuiltin::Position; if(!_stricmp(desc.semanticName.c_str(), "SV_ClipDistance")) desc.systemValue = ShaderBuiltin::ClipDistance; if(!_stricmp(desc.semanticName.c_str(), "SV_CullDistance")) desc.systemValue = ShaderBuiltin::CullDistance; if(!_stricmp(desc.semanticName.c_str(), "SV_RenderTargetArrayIndex")) desc.systemValue = ShaderBuiltin::RTIndex; if(!_stricmp(desc.semanticName.c_str(), "SV_ViewportArrayIndex")) desc.systemValue = ShaderBuiltin::ViewportIndex; if(!_stricmp(desc.semanticName.c_str(), "SV_VertexID")) desc.systemValue = ShaderBuiltin::VertexIndex; if(!_stricmp(desc.semanticName.c_str(), "SV_PrimitiveID")) desc.systemValue = ShaderBuiltin::PrimitiveIndex; if(!_stricmp(desc.semanticName.c_str(), "SV_InstanceID")) desc.systemValue = ShaderBuiltin::InstanceIndex; if(!_stricmp(desc.semanticName.c_str(), "SV_DispatchThreadID")) desc.systemValue = ShaderBuiltin::DispatchThreadIndex; if(!_stricmp(desc.semanticName.c_str(), "SV_GroupID")) desc.systemValue = ShaderBuiltin::GroupIndex; if(!_stricmp(desc.semanticName.c_str(), "SV_GroupIndex")) desc.systemValue = ShaderBuiltin::GroupFlatIndex; if(!_stricmp(desc.semanticName.c_str(), "SV_GroupThreadID")) desc.systemValue = ShaderBuiltin::GroupThreadIndex; if(!_stricmp(desc.semanticName.c_str(), "SV_GSInstanceID")) desc.systemValue = ShaderBuiltin::GSInstanceIndex; if(!_stricmp(desc.semanticName.c_str(), "SV_OutputControlPointID")) desc.systemValue = ShaderBuiltin::OutputControlPointIndex; if(!_stricmp(desc.semanticName.c_str(), "SV_DomainLocation")) desc.systemValue = ShaderBuiltin::DomainLocation; if(!_stricmp(desc.semanticName.c_str(), "SV_IsFrontFace")) desc.systemValue = ShaderBuiltin::IsFrontFace; if(!_stricmp(desc.semanticName.c_str(), "SV_SampleIndex")) desc.systemValue = ShaderBuiltin::MSAASampleIndex; if(!_stricmp(desc.semanticName.c_str(), "SV_TessFactor")) desc.systemValue = ShaderBuiltin::OuterTessFactor; if(!_stricmp(desc.semanticName.c_str(), "SV_InsideTessFactor")) desc.systemValue = ShaderBuiltin::InsideTessFactor; if(!_stricmp(desc.semanticName.c_str(), "SV_Target")) desc.systemValue = ShaderBuiltin::ColorOutput; if(!_stricmp(desc.semanticName.c_str(), "SV_Depth")) desc.systemValue = ShaderBuiltin::DepthOutput; if(!_stricmp(desc.semanticName.c_str(), "SV_Coverage")) desc.systemValue = ShaderBuiltin::MSAACoverage; if(!_stricmp(desc.semanticName.c_str(), "SV_DepthGreaterEqual")) desc.systemValue = ShaderBuiltin::DepthOutputGreaterEqual; if(!_stricmp(desc.semanticName.c_str(), "SV_DepthLessEqual")) desc.systemValue = ShaderBuiltin::DepthOutputLessEqual; } RDCASSERT(desc.systemValue != ShaderBuiltin::Undefined || desc.regIndex >= 0); sig->push_back(desc); el0++; el1++; el7++; } for(uint32_t i = 0; i < sign->numElems; i++) { SigParameter &a = (*sig)[i]; for(uint32_t j = 0; j < sign->numElems; j++) { SigParameter &b = (*sig)[j]; if(i != j && a.semanticName == b.semanticName) { a.needSemanticIndex = true; break; } } rdcstr semanticIdxName = a.semanticName; if(a.needSemanticIndex) semanticIdxName += ToStr(a.semanticIndex); a.semanticIdxName = semanticIdxName; } } else if(*fourcc == FOURCC_Aon9) // 10Level9 most likely { char *c = (char *)fourcc; RDCWARN("Unknown chunk: %c%c%c%c", c[0], c[1], c[2], c[3]); } } // make sure to fetch the dispatch threads dimension from disassembly if(m_Type == DXBC::ShaderType::Compute) { if(m_DXBCByteCode) m_DXBCByteCode->FetchComputeProperties(m_Reflection); else if(m_DXILByteCode) m_DXILByteCode->FetchComputeProperties(m_Reflection); } // initialise debug chunks last for(uint32_t chunkIdx = 0; chunkIdx < header->numChunks; chunkIdx++) { uint32_t *fourcc = (uint32_t *)(data + chunkOffsets[chunkIdx]); if(*fourcc == FOURCC_SDBG) { m_DebugInfo = MakeSDBGChunk(fourcc); } else if(*fourcc == FOURCC_SPDB) { m_DebugInfo = MakeSPDBChunk(m_Reflection, fourcc); } } // we do a mini-preprocess of the files from the debug info to handle #line directives. // This means that any lines that our source file declares to be in another filename via a #line // get put in the right place for what the debug information hopefully matches. // We also concatenate duplicate lines and display them all, to handle edge cases where #lines // declare duplicates. if(m_DebugInfo) { m_DXBCByteCode->SetDebugInfo(m_DebugInfo); rdcarray<rdcarray<rdcstr>> fileLines; rdcarray<rdcstr> fileNames; fileLines.resize(m_DebugInfo->Files.size()); fileNames.resize(m_DebugInfo->Files.size()); for(size_t i = 0; i < m_DebugInfo->Files.size(); i++) fileNames[i] = m_DebugInfo->Files[i].first; for(size_t i = 0; i < m_DebugInfo->Files.size(); i++) { rdcarray<rdcstr> srclines; rdcarray<rdcstr> *dstFile = &fileLines[i]; // start off writing to the corresponding output file. size_t dstLine = 0; split(m_DebugInfo->Files[i].second, srclines, '\n'); srclines.push_back(""); // handle #line directives by inserting empty lines or erasing as necessary for(size_t srcLine = 0; srcLine < srclines.size(); srcLine++) { if(srclines[srcLine].empty()) { dstLine++; continue; } char *c = &srclines[srcLine][0]; char *end = c + srclines[srcLine].size(); while(*c == '\t' || *c == ' ' || *c == '\r') c++; if(c == end) { // blank line, just advance line counter dstLine++; continue; } if(c + 5 > end || strncmp(c, "#line", 5)) { // resize up to account for the current line, if necessary dstFile->resize(RDCMAX(dstLine + 1, dstFile->size())); // if non-empty, append this line (to allow multiple lines on the same line // number to be concatenated). To avoid screwing up line numbers we have to append with a // comment and not a newline. if((*dstFile)[dstLine].empty()) (*dstFile)[dstLine] = srclines[srcLine]; else (*dstFile)[dstLine] += " /* multiple #lines overlapping */ " + srclines[srcLine]; // advance line counter dstLine++; continue; } // we have a #line directive c += 5; if(c >= end) { // invalid #line, just advance line counter dstLine++; continue; } while(*c == '\t' || *c == ' ') c++; if(c >= end) { // invalid #line, just advance line counter dstLine++; continue; } // invalid #line, no line number. Skip/ignore and just advance line counter if(*c < '0' || *c > '9') { dstLine++; continue; } size_t newLineNum = 0; while(*c >= '0' && *c <= '9') { newLineNum *= 10; newLineNum += int((*c) - '0'); c++; } // convert to 0-indexed line number if(newLineNum > 0) newLineNum--; while(*c == '\t' || *c == ' ') c++; // no filename if(*c == 0) { // set the next line number, and continue processing dstLine = newLineNum; continue; } else if(*c == '"') { c++; char *filename = c; // parse out filename while(*c != '"' && *c != 0) { if(*c == '\\') { // skip escaped characters c += 2; } else { c++; } } // parsed filename successfully if(*c == '"') { *c = 0; // find the new destination file bool found = false; size_t dstFileIdx = 0; for(size_t f = 0; f < fileNames.size(); f++) { if(fileNames[f] == filename) { found = true; dstFileIdx = f; break; } } if(found) { dstFile = &fileLines[dstFileIdx]; } else { RDCWARN("Couldn't find filename '%s' in #line directive in debug info", filename); // make a dummy file to write into that won't be used. fileNames.push_back(filename); fileLines.push_back(rdcarray<rdcstr>()); dstFile = &fileLines.back(); } // set the next line number, and continue processing dstLine = newLineNum; continue; } else { // invalid #line, ignore continue; } } else { // invalid #line, ignore continue; } } } for(size_t i = 0; i < m_DebugInfo->Files.size(); i++) { if(m_DebugInfo->Files[i].second.empty()) { merge(fileLines[i], m_DebugInfo->Files[i].second, '\n'); } } } // if we had bytecode in this container, ensure we had reflection. If it's a blob with only an // input signature then we can do without reflection. if(m_DXBCByteCode || m_DXILByteCode) { RDCASSERT(m_Reflection); } } DXBCContainer::~DXBCContainer() { SAFE_DELETE(m_DebugInfo); SAFE_DELETE(m_DXBCByteCode); SAFE_DELETE(m_DXILByteCode); SAFE_DELETE(m_Reflection); } struct FxcArg { uint32_t bit; const char *arg; } fxc_flags[] = { {D3DCOMPILE_DEBUG, " /Zi "}, {D3DCOMPILE_SKIP_VALIDATION, " /Vd "}, {D3DCOMPILE_SKIP_OPTIMIZATION, " /Od "}, {D3DCOMPILE_PACK_MATRIX_ROW_MAJOR, " /Zpr "}, {D3DCOMPILE_PACK_MATRIX_COLUMN_MAJOR, " /Zpc "}, {D3DCOMPILE_PARTIAL_PRECISION, " /Gpp "}, //{D3DCOMPILE_FORCE_VS_SOFTWARE_NO_OPT, " /XX "}, //{D3DCOMPILE_FORCE_PS_SOFTWARE_NO_OPT, " /XX "}, {D3DCOMPILE_NO_PRESHADER, " /Op "}, {D3DCOMPILE_AVOID_FLOW_CONTROL, " /Gfa "}, {D3DCOMPILE_PREFER_FLOW_CONTROL, " /Gfp "}, {D3DCOMPILE_ENABLE_STRICTNESS, " /Ges "}, {D3DCOMPILE_ENABLE_BACKWARDS_COMPATIBILITY, " /Gec "}, {D3DCOMPILE_IEEE_STRICTNESS, " /Gis "}, {D3DCOMPILE_WARNINGS_ARE_ERRORS, " /WX "}, {D3DCOMPILE_RESOURCES_MAY_ALIAS, " /res_may_alias "}, {D3DCOMPILE_ENABLE_UNBOUNDED_DESCRIPTOR_TABLES, " /enable_unbounded_descriptor_tables "}, {D3DCOMPILE_ALL_RESOURCES_BOUND, " /all_resources_bound "}, {D3DCOMPILE_DEBUG_NAME_FOR_SOURCE, " /Zss "}, {D3DCOMPILE_DEBUG_NAME_FOR_BINARY, " /Zsb "}, }; uint32_t DecodeFlags(const ShaderCompileFlags &compileFlags) { uint32_t ret = 0; for(const ShaderCompileFlag flag : compileFlags.flags) { if(flag.name == "@cmdline") { rdcstr cmdline = flag.value; // ensure cmdline is surrounded by spaces and all whitespace is spaces. This means we can // search for our flags surrounded by space and ensure we get exact matches. for(char &c : cmdline) if(isspace(c)) c = ' '; cmdline = " " + cmdline + " "; for(const FxcArg &arg : fxc_flags) { if(strstr(cmdline.c_str(), arg.arg)) ret |= arg.bit; } // check optimisation special case if(strstr(cmdline.c_str(), " /O0 ")) ret |= D3DCOMPILE_OPTIMIZATION_LEVEL0; else if(strstr(cmdline.c_str(), " /O1 ")) ret |= D3DCOMPILE_OPTIMIZATION_LEVEL1; else if(strstr(cmdline.c_str(), " /O2 ")) ret |= D3DCOMPILE_OPTIMIZATION_LEVEL2; else if(strstr(cmdline.c_str(), " /O3 ")) ret |= D3DCOMPILE_OPTIMIZATION_LEVEL3; // ignore any other flags we might not understand break; } } return ret; } ShaderCompileFlags EncodeFlags(const uint32_t flags) { ShaderCompileFlags ret; rdcstr cmdline; for(const FxcArg &arg : fxc_flags) { if(flags & arg.bit) cmdline += arg.arg; } // optimization flags are a special case. // // D3DCOMPILE_OPTIMIZATION_LEVEL0 = (1 << 14) // D3DCOMPILE_OPTIMIZATION_LEVEL1 = 0 // D3DCOMPILE_OPTIMIZATION_LEVEL2 = ((1 << 14) | (1 << 15)) // D3DCOMPILE_OPTIMIZATION_LEVEL3 = (1 << 15) uint32_t opt = (flags & D3DCOMPILE_OPTIMIZATION_LEVEL2); if(opt == D3DCOMPILE_OPTIMIZATION_LEVEL0) cmdline += " /O0"; else if(opt == D3DCOMPILE_OPTIMIZATION_LEVEL1) cmdline += " /O1"; else if(opt == D3DCOMPILE_OPTIMIZATION_LEVEL2) cmdline += " /O2"; else if(opt == D3DCOMPILE_OPTIMIZATION_LEVEL3) cmdline += " /O3"; ret.flags = {{"@cmdline", cmdline}}; // If D3DCOMPILE_SKIP_OPTIMIZATION is set, then prefer source-level debugging as it should be // accurate enough to work with. if(flags & D3DCOMPILE_SKIP_OPTIMIZATION) ret.flags.push_back({"preferSourceDebug", "1"}); return ret; } ShaderCompileFlags EncodeFlags(const IDebugInfo *dbg) { return EncodeFlags(dbg ? dbg->GetShaderCompileFlags() : 0); } }; // namespace DXBC #if ENABLED(ENABLE_UNIT_TESTS) #include "3rdparty/catch/catch.hpp" #if 0 TEST_CASE("DO NOT COMMIT - convenience test", "[dxbc]") { // this test loads a file from disk and passes it through DXBC::DXBCContainer. Useful for when you // are iterating on a shader and don't want to have to load a whole capture. bytebuf buf; FileIO::ReadAll("/path/to/container_file.dxbc", buf); DXBC::DXBCContainer container(buf.data(), buf.size()); // the only thing fetched lazily is the disassembly, so grab that here rdcstr disasm = container.GetDisassembly(); RDCLOG("%s", disasm.c_str()); } #endif TEST_CASE("Check DXBC flags are non-overlapping", "[dxbc]") { for(const DXBC::FxcArg &a : DXBC::fxc_flags) { for(const DXBC::FxcArg &b : DXBC::fxc_flags) { if(a.arg == b.arg) continue; // no argument should be a subset of another argument rdcstr arga = a.arg; rdcstr argb = b.arg; arga.trim(); argb.trim(); INFO("a: '" << arga << "' b: '" << argb << "'"); CHECK(strstr(arga.c_str(), argb.c_str()) == NULL); CHECK(strstr(argb.c_str(), arga.c_str()) == NULL); } } } TEST_CASE("Check DXBC flag encoding/decoding", "[dxbc]") { SECTION("encode/decode identity") { uint32_t flags = D3DCOMPILE_PARTIAL_PRECISION | D3DCOMPILE_SKIP_OPTIMIZATION | D3DCOMPILE_ALL_RESOURCES_BOUND | D3DCOMPILE_OPTIMIZATION_LEVEL2; uint32_t flags2 = DXBC::DecodeFlags(DXBC::EncodeFlags(flags)); CHECK(flags == flags2); flags = 0; flags2 = DXBC::DecodeFlags(DXBC::EncodeFlags(flags)); CHECK(flags == flags2); flags = D3DCOMPILE_OPTIMIZATION_LEVEL3 | D3DCOMPILE_DEBUG; flags2 = DXBC::DecodeFlags(DXBC::EncodeFlags(flags)); CHECK(flags == flags2); }; SECTION("encode/decode discards unrecognised parameters") { uint32_t flags = D3DCOMPILE_PARTIAL_PRECISION | (1 << 30); uint32_t flags2 = DXBC::DecodeFlags(DXBC::EncodeFlags(flags)); CHECK(flags2 == D3DCOMPILE_PARTIAL_PRECISION); ShaderCompileFlags compileflags; compileflags.flags = { {"@cmdline", "/Zi /Z8 /JJ /WX /K other words embed/Odparam /DFoo=\"bar\""}}; flags2 = DXBC::DecodeFlags(compileflags); CHECK(flags2 == (D3DCOMPILE_DEBUG | D3DCOMPILE_WARNINGS_ARE_ERRORS)); flags = ~0U; flags2 = DXBC::DecodeFlags(DXBC::EncodeFlags(flags)); uint32_t allflags = 0; for(const DXBC::FxcArg &a : DXBC::fxc_flags) allflags |= a.bit; allflags |= D3DCOMPILE_OPTIMIZATION_LEVEL2; CHECK(flags2 == allflags); }; SECTION("optimisation flags are properly decoded and encoded") { uint32_t flags = D3DCOMPILE_DEBUG | D3DCOMPILE_OPTIMIZATION_LEVEL0; uint32_t flags2 = DXBC::DecodeFlags(DXBC::EncodeFlags(flags)); CHECK(flags == flags2); flags = D3DCOMPILE_DEBUG | D3DCOMPILE_OPTIMIZATION_LEVEL1; flags2 = DXBC::DecodeFlags(DXBC::EncodeFlags(flags)); CHECK(flags == flags2); flags = D3DCOMPILE_DEBUG | D3DCOMPILE_OPTIMIZATION_LEVEL2; flags2 = DXBC::DecodeFlags(DXBC::EncodeFlags(flags)); CHECK(flags == flags2); flags = D3DCOMPILE_DEBUG | D3DCOMPILE_OPTIMIZATION_LEVEL3; flags2 = DXBC::DecodeFlags(DXBC::EncodeFlags(flags)); CHECK(flags == flags2); }; } #endif
[ "minh0722@yahoo.com" ]
minh0722@yahoo.com
a6ca31d1d24d0a7fec586eed27a7a0a1670a768e
e40db7db03ab0e7052c85b5643a677449acc9cbe
/others/bishi_huawei.cpp
f2e17df0b108c66cd60eba97cc104aada2bf4746
[]
no_license
zqianl/algorithm
61da02760f6567c39123722b98003b5d01d92bb5
da31ac1a65bb0d40ac4a727c6a563f53be667380
refs/heads/master
2021-01-01T04:03:02.005116
2017-09-28T15:37:11
2017-09-28T15:37:11
97,109,702
0
0
null
null
null
null
GB18030
C++
false
false
4,246
cpp
//两个字符串,将两个字符串中共同出现的字符换成 '_' #include <iostream> #include<vector> #include<string> #include<set> #include <cstdio> using namespace std; int main(int argc, char **argv) { string string1, string2; cin >> string1; cin >> string2; vector<int> vecMap(256,0); set<int>commonChar; for (auto i = string1.begin(); i != string1.end(); ++i) { vecMap[*i]++; } for (auto i = string2.begin(); i != string2.end(); ++i) { if (vecMap[*i] != 0) commonChar.insert(*i); } for (auto i = string1.begin(); i != string1.end(); ++i) { if (commonChar.find(*i) != commonChar.end()) *i = '_'; } for (auto i = string2.begin(); i != string2.end(); ++i) { if (commonChar.find(*i) != commonChar.end()) *i = '_'; } cout << string1 << endl; cout << string2 << endl; system("pause"); return 0; } //ISBN号:给出1-234-56789型的11个字符组成的字符串,分别将九个数组乘以1-9, //然后mod 11,假设a来表示。如果a等于10就输出1-234-56789-X,否则输出1-234-56789-a #include <iostream> #include<vector> #include<string> using namespace std; int main(int argc, char **argv) { string str; cin >> str; if (str.size() != 11) cout << "ERROR" << endl; else { if (str[1] != '-' || str[5] != '-') cout << "ERROR" << endl; else { int j = -1; bool flag = true; for (auto i = str.begin(); i != str.end(); ++i) { j++; if (j != 1 && j != 5) { if (*i > '9' || *i < '0') { flag = false; break; } } } if (flag == false) cout << "ERROR" << endl; else { int sum = 0; sum += (str[0] - '0') + (str[2] - '0') * 2 + (str[3] - '0') * 3 + (str[4] - '0') * 4 + (str[6] - '0') * 5 + (str[7] - '0') * 6 + (str[8] - '0') * 7 + (str[9] - '0') * 8 + (str[10] - '0') * 9; int last = sum % 11; if (last == 10) last = 'X'; else last = last + '0'; str.push_back('-'); str.push_back(last); cout << str << endl; } } } system("pause"); return 0; } //域名排序,形如qwe.ert|asd.xcv.sdf|ert.tyu.dfg的输入,根据最后一个.之后的字符串字典序进行排序 //若相等则再比较前一个该域名的前一个字符串,如果某一个域名没有前一个,则将其排在另一个前面 #include<iostream> #include<vector> #include<string> using namespace std; bool JudgeSwap(string str1, string str2) { bool flag = false; vector<string>vecStr1; vector<string>vecStr2; auto k = str1.begin(); for (auto i = str1.begin(); i != str1.end(); ++i) { if (*i == '.') { string midString1(k, i); vecStr1.push_back(midString1); k = i + 1; } } string midString1(k, str1.end()); vecStr1.push_back(midString1); k = str2.begin(); for (auto i = str2.begin(); i != str2.end(); ++i) { if (*i == '.') { string midString2(k, i); vecStr2.push_back(midString2); k = i + 1; } } string midString2(k, str2.end()); vecStr2.push_back(midString2); auto i = vecStr1.end() - 1; auto j = vecStr2.end() - 1; bool midFlag = false; for (; i != vecStr1.begin() && j != vecStr2.begin(); i--, j--) { if (*i > *j) { flag = true; midFlag = true; break; } else if(*i < *j) { midFlag = true; break; } } if (midFlag == false) { if (*i > *j) { flag = true; } else { if (j == vecStr2.begin()) { flag = true; } } } return flag; } void Swap(string &str1, string &str2) { string midStr = str1; str1 = str2; str2 = midStr; } int main(int argc, char **argv) { string str; cin >> str; vector<string>vecComStr; auto j = str.begin(); for (auto i = str.begin(); i != str.end(); ++i) { if (*i == '|') { string midString(j,i); vecComStr.push_back(midString); j = i + 1; } } string midString(j, str.end()); vecComStr.push_back(midString); for (unsigned int i = 0; i < vecComStr.size(); ++i) { for (unsigned int j = 0; j < vecComStr.size() - i - 1; ++j) { bool flag = JudgeSwap(vecComStr[j], vecComStr[j+1]); if (flag == true) Swap(vecComStr[j], vecComStr[j+1]); } } for (auto i = vecComStr.begin(); i != vecComStr.end(); ++i) { cout << *i; if (i != vecComStr.end() - 1) cout << '|'; } system("pause"); return 0; }
[ "1229170125@qq.com" ]
1229170125@qq.com
154433bfd1a24ca48d259c9902066be229eae22d
953d8b31f59c412f1930e8a6ad7c969cfcf5cfd8
/3.smartCampus/otherHub/commSocket.cpp
c2473215550ab70f61bde49b14fc56aa85c16c4e
[]
no_license
nadavMiz/school-projects
181dacd0e1de9112d31d4a9f10cf4d454efaaa30
6ad7522243386f5dbabbbea2c4040b154614d1c2
refs/heads/master
2021-01-25T10:35:25.652041
2018-10-13T21:26:13
2018-10-13T21:26:13
123,361,951
0
0
null
null
null
null
UTF-8
C++
false
false
1,463
cpp
#include <cstring> /* strerror */ #include <unistd.h> /* close */ #include <stdio.h> /* perror */ #include <stdexcept> /* exceptions */ #include <sys/types.h> /* ssize_t */ #include <sys/socket.h> /* sockets */ #include <errno.h> /* errno */ #include "commSocket.h" #include "netExceptions.h" namespace netcpp { static const int flags[] = {0, MSG_DONTWAIT}; std::vector<int> CommSocket::m_flags(flags, flags + sizeof(flags)/sizeof(flags[0])); CommSocket::~CommSocket() { close(m_socket); } void CommSocket::Disconnect() { if(close(m_socket) < 0) { throw std::runtime_error(strerror(errno)); } } void CommSocket::MsgErrorHandler() { switch(errno) { case EAGAIN: throw std::underflow_error(strerror(errno)); case EPIPE: throw BrokenPipe_error("connection closed"); default: throw ReadWrite_error(strerror(errno)); } } std::size_t CommSocket::Send(void* _data, std::size_t _size, MsgFlag _flag) { std::size_t result; result = send(m_socket, _data, _size, GetFlag(_flag) | MSG_NOSIGNAL); if(result < 0) { MsgErrorHandler(); } return result; } std::size_t CommSocket::Recv(void* _data, std::size_t _size, MsgFlag _flag) { ssize_t result; result = recv(m_socket, _data, _size, GetFlag(_flag)); if(0 == result) { throw BrokenPipe_error("connection closed"); } else if(result < 0) { MsgErrorHandler(); } return result; } int CommSocket::GetFlag(MsgFlag _flag) const { return m_flags.at(_flag); } }
[ "nadav.mizrahi16@gmail.com" ]
nadav.mizrahi16@gmail.com
dfc32c68eae72eca0429623ac6402e993a173b59
59b0f1cabb69d42118e74d223b05bca656b4761a
/src/includes/Node.h
3e221e966f22602393357df4559b835c3dba4afe
[]
no_license
hanburger97/MDPE
8dc1b1daa4147c7bdca77694630e12f9dcb99076
51e62d985e6d99b32b6c8fd85b44d28a572b6c71
refs/heads/master
2020-04-01T03:36:25.607118
2018-10-13T02:44:15
2018-10-13T02:44:15
152,828,483
0
1
null
null
null
null
UTF-8
C++
false
false
7,319
h
// // Created by Han Xiao on 2018-03-15. // #include <libibc/IB.h> #ifndef MDPE_NODE_H #define MDPE_NODE_H enum STATE{ RUNNING, SLEEPING, SHUTDOWN, ERROR }; class Node : public IB_Client { protected: Node(std::string host, EWrapper * ew); virtual ~Node(); STATE currentState; // For our current host std::string host; // For our IB Host std::string ibhost; int ibport; // For Kafka Brokerage Host std::string khost; int kport; private: virtual void errorExit() =0; virtual void softExit() const = 0; virtual void handleDisconnection() = 0; public: virtual void start() = 0; virtual void shutDown() const = 0; virtual STATE getState() const = 0; // For IB host std::string getIBHost() const; int getIBPort() const; void setIBHost(std::string host="", int port =0); // For Kafka Host std::string getKHost() const; int getKPort() const; void setKHost(std::string host="", int port =0); //================== Client Methods ================== // ================= Virtuals from EWrapper =========== virtual void tickPrice( TickerId tickerId, TickType field, double price, int canAutoExecute) = 0; virtual void tickSize( TickerId tickerId, TickType field, int size) = 0; virtual void tickOptionComputation( TickerId tickerId, TickType tickType, double impliedVol, double delta, double optPrice, double pvDividend, double gamma, double vega, double theta, double undPrice) = 0; virtual void tickGeneric(TickerId tickerId, TickType tickType, double value) = 0; virtual void tickString(TickerId tickerId, TickType tickType, const std::string& value) = 0; virtual void tickEFP(TickerId tickerId, TickType tickType, double basisPoints, const std::string& formattedBasisPoints, double totalDividends, int holdDays, const std::string& futureLastTradeDate, double dividendImpact, double dividendsToLastTradeDate) = 0; virtual void orderStatus( OrderId orderId, const std::string& status, double filled, double remaining, double avgFillPrice, int permId, int parentId, double lastFillPrice, int clientId, const std::string& whyHeld) = 0; virtual void openOrder( OrderId orderId, const Contract&, const Order&, const OrderState&) = 0; virtual void openOrderEnd() = 0; virtual void winError( const std::string& str, int lastError) = 0; virtual void connectionClosed() = 0; virtual void updateAccountValue(const std::string& key, const std::string& val, const std::string& currency, const std::string& accountName) = 0; virtual void updatePortfolio( const Contract& contract, double position, double marketPrice, double marketValue, double averageCost, double unrealizedPNL, double realizedPNL, const std::string& accountName) = 0; virtual void updateAccountTime(const std::string& timeStamp) = 0; virtual void accountDownloadEnd(const std::string& accountName) = 0; virtual void nextValidId( OrderId orderId) = 0; virtual void contractDetails( int reqId, const ContractDetails& contractDetails) = 0; virtual void bondContractDetails( int reqId, const ContractDetails& contractDetails) = 0; virtual void contractDetailsEnd( int reqId) = 0; virtual void execDetails( int reqId, const Contract& contract, const Execution& execution) =0; virtual void execDetailsEnd( int reqId) =0; virtual void error(const int id, const int errorCode, const std::string errorString) = 0; virtual void updateMktDepth(TickerId id, int position, int operation, int side, double price, int size) = 0; virtual void updateMktDepthL2(TickerId id, int position, std::string marketMaker, int operation, int side, double price, int size) = 0; virtual void updateNewsBulletin(int msgId, int msgType, const std::string& newsMessage, const std::string& originExch) = 0; virtual void managedAccounts( const std::string& accountsList) = 0; virtual void receiveFA(faDataType pFaDataType, const std::string& cxml) = 0; virtual void historicalData(TickerId reqId, const std::string& date, double open, double high, double low, double close, int volume, int barCount, double WAP, int hasGaps) = 0; virtual void scannerParameters(const std::string& xml) = 0; virtual void scannerData(int reqId, int rank, const ContractDetails& contractDetails, const std::string& distance, const std::string& benchmark, const std::string& projection, const std::string& legsStr) = 0; virtual void scannerDataEnd(int reqId) = 0; virtual void realtimeBar(TickerId reqId, long time, double open, double high, double low, double close, long volume, double wap, int count) = 0; virtual void currentTime(long time) = 0; virtual void fundamentalData(TickerId reqId, const std::string& data) = 0; virtual void deltaNeutralValidation(int reqId, const UnderComp& underComp) = 0; virtual void tickSnapshotEnd( int reqId) = 0; virtual void marketDataType( TickerId reqId, int marketDataType) = 0; virtual void commissionReport( const CommissionReport& commissionReport) = 0; virtual void position( const std::string& account, const Contract& contract, double position, double avgCost) = 0; virtual void positionEnd() = 0; virtual void accountSummary( int reqId, const std::string& account, const std::string& tag, const std::string& value, const std::string& curency) = 0; virtual void accountSummaryEnd( int reqId) = 0; virtual void verifyMessageAPI( const std::string& apiData) = 0; virtual void verifyCompleted( bool isSuccessful, const std::string& errorText) = 0; virtual void displayGroupList( int reqId, const std::string& groups) = 0; virtual void displayGroupUpdated( int reqId, const std::string& contractInfo) = 0; virtual void verifyAndAuthMessageAPI( const std::string& apiData, const std::string& xyzChallange) = 0; virtual void verifyAndAuthCompleted( bool isSuccessful, const std::string& errorText) = 0; virtual void connectAck() = 0; virtual void positionMulti( int reqId, const std::string& account,const std::string& modelCode, const Contract& contract, double pos, double avgCost) = 0; virtual void positionMultiEnd( int reqId) = 0; virtual void accountUpdateMulti( int reqId, const std::string& account, const std::string& modelCode, const std::string& key, const std::string& value, const std::string& currency) = 0; virtual void accountUpdateMultiEnd( int reqId) = 0; virtual void securityDefinitionOptionalParameter(int reqId, const std::string& exchange, int underlyingConId, const std::string& tradingClass, const std::string& multiplier, std::set<std::string> expirations, std::set<double> strikes) = 0; virtual void securityDefinitionOptionalParameterEnd(int reqId) = 0; virtual void softDollarTiers(int reqId, const std::vector<SoftDollarTier> &tiers) = 0; }; #endif //MDPE_NODE_H
[ "han@hanxbox.com" ]
han@hanxbox.com
98173ffd17af01b5e6cd0d155ec4589727e35dab
c35dafa94e567ed16ebd40596efb500900b4ceea
/netsim_py/resources/hil/APEL_code/Castalia-3.2/src/node/application/ticTocLike/TicTocLike.cc
e98b644b622b2013396e9ecaeea092bb196dd502
[]
no_license
vsamtuc/netsim
1cfc63b3047e9305faf1f3e29f1a60df780a1328
c6f838c03e48ae4b836af3b7377aeebe1ec53d00
refs/heads/master
2021-04-06T20:22:25.894643
2017-10-15T13:51:12
2017-10-15T13:51:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,372
cc
/**************************************************************************** * Copyright: National ICT Australia, 2007 - 2011 * * Developed at the ATP lab, Networked Systems research theme * * Author(s): Athanassios Boulis, Yuriy Tselishchev * * This file is distributed under the terms in the attached LICENSE file. * * If you do not find this file, copies can be found by writing to: * * * * NICTA, Locked Bag 9013, Alexandria, NSW 1435, Australia * * Attention: License Inquiry. * * * ****************************************************************************/ #include "TicTocLike.h" Define_Module(TicTocLike); void TicTocLike::startup() { packet_rate = par("packet_rate"); recipientAddress = par("nextRecipient").stringValue(); startupDelay = par("startupDelay"); packet_spacing = packet_rate > 0 ? 1 / float (packet_rate) : -1; dataSN = 0; if (packet_spacing > 0 && recipientAddress.compare(SELF_NETWORK_ADDRESS) != 0) setTimer(SEND_PACKET, packet_spacing + startupDelay); else trace() << "Not sending packets"; declareOutput("Packets received per node"); } void TicTocLike::fromNetworkLayer(ApplicationPacket * rcvPacket, const char *source, double rssi, double lqi) { int sequenceNumber = rcvPacket->getSequenceNumber(); //--trace() << " Packet Destination " << rcvPacket->getAppNetInfoExchange().destination.c_str(); string dest = rcvPacket->getAppNetInfoExchange().destination.c_str(); if( dest.compare(SELF_NETWORK_ADDRESS) == 0 ){ trace() << "Received packet #" << sequenceNumber << " from node " << source; collectOutput("Packets received per node", atoi(source)); } if (recipientAddress.compare(SELF_NETWORK_ADDRESS) == 0) { //--trace() << "Received packet #" << sequenceNumber << " from node " << source; //--collectOutput("Packets received per node", atoi(source)); // Send Back an answer ... trace() << "Sending packet #" << dataSN; toNetworkLayer(createGenericDataPacket(0, dataSN), source); dataSN++; // Packet has to be forwarded to the next hop recipient } //--else { //-- ApplicationPacket* fwdPacket = rcvPacket->dup(); // Reset the size of the packet, otherwise the app overhead will keep adding on //-- fwdPacket->setByteLength(0); //-- toNetworkLayer(fwdPacket, recipientAddress.c_str()); //--} } void TicTocLike::timerFiredCallback(int index) { switch (index) { case SEND_PACKET:{ trace() << "Sending packet #" << dataSN; toNetworkLayer(createGenericDataPacket(0, dataSN), par("nextRecipient")); dataSN++; setTimer(SEND_PACKET, packet_spacing); break; } } } // This method processes a received carrier sense interupt. Used only for demo purposes // in some simulations. Feel free to comment out the trace command. void TicTocLike::handleRadioControlMessage(RadioControlMessage *radioMsg) { switch (radioMsg->getRadioControlMessageKind()) { case CARRIER_SENSE_INTERRUPT: trace() << "CS Interrupt received! current RSSI value is: " << radioModule->readRSSI(); break; } }
[ "vsam@softnet.tuc.gr" ]
vsam@softnet.tuc.gr
2bcfdd1a870639530883ce74dc05f8ad8b7e7d17
eedd904304046caceb3e982dec1d829c529da653
/clanlib/ClanLib-2.2.8/Examples/Game/SpritesRTS/Sources/program.cpp
cc5c42a727f588cd7873412b5f062f3eab8c1659
[]
no_license
PaulFSherwood/cplusplus
b550a9a573e9bca5b828b10849663e40fd614ff0
999c4d18d2dd4d0dd855e1547d2d2ad5eddc6938
refs/heads/master
2023-06-07T09:00:20.421362
2023-05-21T03:36:50
2023-05-21T03:36:50
12,607,904
4
0
null
null
null
null
UTF-8
C++
false
false
2,373
cpp
/* ** ClanLib SDK ** Copyright (c) 1997-2011 The ClanLib Team ** ** This software is provided 'as-is', without any express or implied ** warranty. In no event will the authors be held liable for any damages ** arising from the use of this software. ** ** Permission is granted to anyone to use this software for any purpose, ** including commercial applications, and to alter it and redistribute it ** freely, subject to the following restrictions: ** ** 1. The origin of this software must not be misrepresented; you must not ** claim that you wrote the original software. If you use this software ** in a product, an acknowledgment in the product documentation would be ** appreciated but is not required. ** 2. Altered source versions must be plainly marked as such, and must not be ** misrepresented as being the original software. ** 3. This notice may not be removed or altered from any source distribution. ** ** Note: Some of the libraries ClanLib may link to may have additional ** requirements or restrictions. ** ** File Author(s): ** ** Mark Page */ #include "precomp.h" #include "program.h" #include "app.h" // Choose the target renderer //#define USE_OPENGL_2 //#define USE_OPENGL_1 #define USE_SOFTWARE_RENDERER #ifdef USE_SOFTWARE_RENDERER #include <ClanLib/swrender.h> #endif #ifdef USE_OPENGL_1 #include <ClanLib/gl1.h> #endif #ifdef USE_OPENGL_2 #include <ClanLib/gl.h> #endif int Program::main(const std::vector<CL_String> &args) { try { // Initialize ClanLib base components CL_SetupCore setup_core; // Initialize the ClanLib display component CL_SetupDisplay setup_display; #ifdef USE_SOFTWARE_RENDERER CL_SetupSWRender setup_swrender; #endif #ifdef USE_OPENGL_1 CL_SetupGL1 setup_gl1; #endif #ifdef USE_OPENGL_2 CL_SetupGL setup_gl; #endif CL_SetupSound setup_sound; // Start the Application Application app; int retval = app.main(args); return retval; } catch(CL_Exception &exception) { // Create a console window for text-output if not available CL_ConsoleWindow console("Console", 80, 160); CL_Console::write_line("Exception caught: " + exception.get_message_and_stack_trace()); console.display_close_message(); return -1; } } // Instantiate CL_ClanApplication, informing it where the Program is located CL_ClanApplication app(&Program::main);
[ "paulfsherwood@gmail.com" ]
paulfsherwood@gmail.com
a975d96e9e5439de99d44bb85b04fe8b9c0b3d11
747d61e0af8906209798d29e4cb5b15dfeff04de
/firmware/AD5274_test/AD5274_test.ino
c9895eb78d59609bcc29c0ab84c68fdd1fe30a96
[]
no_license
dBarmpxkos/SCCM4P_FUN
70d13a3de1d40f3244e304b709cf27409d9739f4
524450e380635fae17f104b58f230e824104f4c5
refs/heads/master
2021-06-17T16:48:23.061596
2020-05-05T10:02:40
2020-05-05T10:02:40
212,282,753
0
1
null
null
null
null
UTF-8
C++
false
false
1,349
ino
#include <Systronix_AD5274.h> Systronix_AD5274 AD5274(AD5274_BASE_ADDR_FLOAT); int16_t read_from_ad5274 = 0; uint16_t data_16_to_write = 0; int8_t status = 0; void setup() { Serial.begin(115200); AD5274.begin(); } void loop() { // unlock RDAC status = AD5274.command_write(AD5274_CONTROL_WRITE, AD5274_RDAC_WIPER_WRITE_ENABLE); read_from_ad5274 = AD5274.command_read(AD5274_CONTROL_READ, 0x00); if (read_from_ad5274 & AD5274_RDAC_WIPER_WRITE_ENABLE){ Serial.print("RDAC unlock successful: "); Serial.println(read_from_ad5274); } else { Serial.print("RDAC unlock failed: "); Serial.println(read_from_ad5274); } // write and then read RDAC register data_16_to_write = 0x000; status += write_and_read_rdac (data_16_to_write); delay(2000); while (true) { data_16_to_write += 4; Serial.println(data_16_to_write); status += write_and_read_rdac (data_16_to_write); delay(100); if (status > 0) { Serial.print(" RDAC read/write errors: "); Serial.println(status); } } } /* RDAC register for resistance setting */ int8_t write_and_read_rdac (uint16_t data_16_to_write){ int8_t status = 0; status += AD5274.command_write(AD5274_RDAC_WRITE, data_16_to_write); read_from_ad5274 = AD5274.command_read(AD5274_RDAC_READ, 0x00); return status; } /* RDAC register for resistance setting */
[ "dbarmpakos@outlook.com" ]
dbarmpakos@outlook.com
92a83cb204ab8652a9f91cffb378f48fe7d3919d
47b755444e700332877d8bb432e5739045ba2c8b
/wxWidgets/demos/forty/canvas.cpp
066e94c52937c46d87eb6a43d4ee38a231b7548b
[ "MIT" ]
permissive
andr3wmac/Torque6Editor
5b30e103f0b3a81ae7a189725e25d807093bf131
0f8536ce90064adb9918f004a45aaf8165b2a343
refs/heads/master
2021-01-15T15:32:54.537291
2016-06-09T20:45:49
2016-06-09T20:45:49
39,276,153
25
14
null
null
null
null
UTF-8
C++
false
false
6,639
cpp
///////////////////////////////////////////////////////////////////////////// // Name: canvas.cpp // Purpose: Forty Thieves patience game // Author: Chris Breeze // Modified by: // Created: 21/07/97 // Copyright: (c) 1993-1998 Chris Breeze // Licence: wxWindows licence //--------------------------------------------------------------------------- // Last modified: 22nd July 1998 - ported to wxWidgets 2.0 ///////////////////////////////////////////////////////////////////////////// // For compilers that support precompilation, includes "wx/wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #ifndef WX_PRECOMP #include "wx/wx.h" #endif #include "forty.h" #include "card.h" #include "game.h" #include "scorefil.h" #include "playerdg.h" #include "canvas.h" wxBEGIN_EVENT_TABLE(FortyCanvas, wxScrolledWindow) EVT_MOUSE_EVENTS(FortyCanvas::OnMouseEvent) wxEND_EVENT_TABLE() FortyCanvas::FortyCanvas(wxWindow* parent, const wxPoint& pos, const wxSize& size) : wxScrolledWindow(parent, wxID_ANY, pos, size, 0), m_helpingHand(true), m_rightBtnUndo(true), m_playerDialog(0), m_leftBtnDown(false) { SetScrollbars(0, 0, 0, 0); #ifdef __WXGTK__ m_font = wxTheFontList->FindOrCreateFont(12, wxROMAN, wxNORMAL, wxNORMAL); #else m_font = wxTheFontList->FindOrCreateFont(10, wxSWISS, wxNORMAL, wxNORMAL); #endif SetBackgroundColour(FortyApp::BackgroundColour()); m_handCursor = new wxCursor(wxCURSOR_HAND); m_arrowCursor = new wxCursor(wxCURSOR_ARROW); wxString name = wxTheApp->GetAppName(); if ( name.empty() ) name = wxT("forty"); m_scoreFile = new ScoreFile(name); m_game = new Game(0, 0, 0); m_game->Deal(); } FortyCanvas::~FortyCanvas() { UpdateScores(); delete m_game; delete m_scoreFile; delete m_handCursor; delete m_arrowCursor; } /* Write the current player's score back to the score file */ void FortyCanvas::UpdateScores() { if (!m_player.empty() && m_scoreFile && m_game) { m_scoreFile->WritePlayersScore( m_player, m_game->GetNumWins(), m_game->GetNumGames(), m_game->GetScore() ); } } void FortyCanvas::OnDraw(wxDC& dc) { dc.SetFont(* m_font); m_game->Redraw(dc); #if 0 // if player name not set (and selection dialog is not displayed) // then ask the player for their name if (m_player.empty() && !m_playerDialog) { m_playerDialog = new PlayerSelectionDialog(this, m_scoreFile); m_playerDialog->ShowModal(); m_player = m_playerDialog->GetPlayersName(); if ( !m_player.empty() ) { // user entered a name - lookup their score int wins, games, score; m_scoreFile->ReadPlayersScore(m_player, wins, games, score); m_game->NewPlayer(wins, games, score); m_game->DisplayScore(dc); m_playerDialog->Destroy(); m_playerDialog = 0; Refresh(false); } else { // user cancelled the dialog - exit the app ((wxFrame*)GetParent())->Close(true); } } #endif } void FortyCanvas::ShowPlayerDialog() { // if player name not set (and selection dialog is not displayed) // then ask the player for their name if (m_player.empty() && !m_playerDialog) { m_playerDialog = new PlayerSelectionDialog(this, m_scoreFile); m_playerDialog->ShowModal(); m_player = m_playerDialog->GetPlayersName(); if ( !m_player.empty() ) { // user entered a name - lookup their score int wins, games, score; m_scoreFile->ReadPlayersScore(m_player, wins, games, score); m_game->NewPlayer(wins, games, score); wxClientDC dc(this); dc.SetFont(* m_font); m_game->DisplayScore(dc); m_playerDialog->Destroy(); m_playerDialog = 0; Refresh(false); } else { // user cancelled the dialog - exit the app ((wxFrame*)GetParent())->Close(true); } } } /* Called when the main frame is closed */ bool FortyCanvas::OnCloseCanvas() { if (m_game->InPlay() && wxMessageBox(wxT("Are you sure you want to\nabandon the current game?"), wxT("Warning"), wxYES_NO | wxICON_QUESTION) == wxNO) { return false; } return true; } void FortyCanvas::OnMouseEvent(wxMouseEvent& event) { int mouseX = (int)event.GetX(); int mouseY = (int)event.GetY(); wxClientDC dc(this); PrepareDC(dc); dc.SetFont(* m_font); if (event.LeftDClick()) { if (m_leftBtnDown) { m_leftBtnDown = false; ReleaseMouse(); m_game->LButtonUp(dc, mouseX, mouseY); } m_game->LButtonDblClk(dc, mouseX, mouseY); } else if (event.LeftDown()) { if (!m_leftBtnDown) { m_leftBtnDown = true; CaptureMouse(); m_game->LButtonDown(dc, mouseX, mouseY); } } else if (event.LeftUp()) { if (m_leftBtnDown) { m_leftBtnDown = false; ReleaseMouse(); m_game->LButtonUp(dc, mouseX, mouseY); } } else if (event.RightDown() && !event.LeftIsDown()) { // only allow right button undo if m_rightBtnUndo is true if (m_rightBtnUndo) { if (event.ControlDown() || event.ShiftDown()) { m_game->Redo(dc); } else { m_game->Undo(dc); } } } else if (event.Dragging()) { m_game->MouseMove(dc, mouseX, mouseY); } if (!event.LeftIsDown()) { SetCursorStyle(mouseX, mouseY); } } void FortyCanvas::SetCursorStyle(int x, int y) { // Only set cursor to a hand if 'helping hand' is enabled and // the card under the cursor can go somewhere if (m_game->CanYouGo(x, y) && m_helpingHand) { SetCursor(* m_handCursor); } else { SetCursor(* m_arrowCursor); } } void FortyCanvas::NewGame() { m_game->Deal(); Refresh(); } void FortyCanvas::Undo() { wxClientDC dc(this); PrepareDC(dc); dc.SetFont(* m_font); m_game->Undo(dc); } void FortyCanvas::Redo() { wxClientDC dc(this); PrepareDC(dc); dc.SetFont(* m_font); m_game->Redo(dc); } void FortyCanvas::LayoutGame() { m_game->Layout(); }
[ "andrewmac@gmail.com" ]
andrewmac@gmail.com
091e5791d98f0a24e54fea434e4ba9d911b538ab
4d053f1c51458d7e67b34793ca0a12220c1a7a97
/HandWritting/HandWritting/stdafx.cpp
bb9c75ab36dcbdbe5661a6a935e723012315d6a2
[]
no_license
ShortLegsZ/HandWritting
87c6d022eb0c5e1c2b27de35b6fca96cffe29af3
2148bedc3b52f9422803ef5f11127239c0096c73
refs/heads/master
2022-06-08T20:02:11.470494
2020-04-30T10:20:41
2020-04-30T10:20:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
173
cpp
 // stdafx.cpp : 只包括标准包含文件的源文件 // HandWritting.pch 将作为预编译标头 // stdafx.obj 将包含预编译类型信息 #include "stdafx.h"
[ "zch9426@qq.com" ]
zch9426@qq.com
9190f44be816ebca767f3a6a683668f911ea92bc
c3a0f82e6d0fb3e8fb49afc042560e5787e42141
/codeforces/1353/A.cpp
27aa654a0fb35d7c7d97cf9141faeacd0102a02e
[]
no_license
SahajGupta11/Codeforces-submissions
04abcd8b0632e7cdd2748d8b475eed152d00ed1b
632f87705ebe421f954a59d99428e7009d021db1
refs/heads/master
2023-02-05T08:06:53.500395
2019-09-18T16:16:00
2020-12-22T14:32:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,227
cpp
#include <bits/stdc++.h> #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0) // #define int long long using namespace std; #define e "\n" #define endl "\n" #define Tp template<class T> #define Tp2 template<class T1, class T2> #define Tps template<class T, class... Ts> #define Tps2 template<class T1, class T2, class... Ts> #define ff first #define ss second #define rev(Aa) reverse(Aa.begin(),Aa.end()) #define all(Aa) Aa.begin(),Aa.end() #define lb lower_bound #define ub upper_bound #define rsz resize #define ins insert #define mp make_pair #define pb emplace_back #define pf push_front #define popb pop_back #define popf pop_front #define sz(Xx) (int)(Xx).size() typedef long long ll; typedef long double ld; typedef double db; using pii = pair<int, int>; const int MOD = 1000000007; //1e9 + 7 const int INF = 2000000000; //2e9 const ll DESPACITO = 1000000000000000000; //1e18 namespace minmax { Tp T max(T&& A) { return A; } Tp T min(T&& A) { return A; } Tp T max(T&& A, T&& B) { return A>B?A:B; } Tp T chmin2(T&& A, T&& B) { return A<B?A:B; } Tps T max(T&& A, Ts&&... ts) { T B = max(ts...); return A>B?A:B; } Tps T min(T&& A, Ts&&... ts) { T B = min(ts...); return A<B?A:B; } Tps T chmax(T&& A, Ts&&... ts) { A = max(A, ts...); return A; } Tps T chmin(T&& A, Ts&&... ts) { A = min(A, ts...); return A; } Tp2 void chmin2(T1&& A, T2&& Aa, T1&& B, T2&& Bb) { if(B < A) A = B, Aa = Bb; } Tp2 void chmax2(T1&& A, T2&& Aa, T1&& B, T2&& Bb) { if(B > A) A = B, Aa = Bb; } } namespace input { Tp void re(T&& Xx) { cin >> Xx; } Tp2 void re(pair<T1,T2>& Pp) { re(Pp.first); re(Pp.second); } Tp void re(vector<T>& Aa) { for(int i = 0; i < sz(Aa); i++) re(Aa[i]); } Tp2 void rea(T1&& Aa, T2 t) { for(int i = 0; i < t; i++) re(Aa[i]); } Tps2 void rea(T1&& Aa, T2 t, Ts&&... ts) { rea(Aa, t); rea(ts...); } Tp2 void rea1(T1&& Aa, T2 t) { for(int i = 1; i <= t; i++) re(Aa[i]); } Tps2 void rea1(T1&& Aa, T2 t, Ts&... ts) { rea1(Aa, t); rea1(ts...); } Tps void re(T&& t, Ts&... ts) { re(t); re(ts...); } } namespace output { void pr(int32_t Xx) { cout << Xx; } // void pr(num Xx) { cout << Xx; } void pr(bool Xx) { cout << Xx; } void pr(long long Xx) { cout << Xx; } void pr(long long unsigned Xx) { cout << Xx; } void pr(double Xx) { cout << Xx; } void pr(char Xx) { cout << Xx; } void pr(const string& Xx) { cout << Xx; } void pr(const char* Xx) { cout << Xx; } void pr(const char* Xx, size_t len) { cout << string(Xx, len); } void ps() { cout << endl; } void pn() { /*do nothing*/ } void pw() { pr(" "); } void pc() { pr("]"); ps(); } Tp2 void pr(const pair<T1,T2>& Xx) { pr(Xx.first); pw(); pr(Xx.second);} Tp void pr(const T&); bool parse(const char* t) { if(t == e) return true; return false;} Tp bool parse(T&& t) { return false;} Tp2 bool parsepair(const pair<T1,T2>& Xx) { return true; } Tp bool parsepair(T&& t) { return false;} Tp2 void psa(T1&& Aa, T2 t) { for(int i = 0; i < t; i++) pr(Aa[i]), pw(); ps(); } Tp2 void pna(T1&& Aa, T2 t) { for(int i = 0; i < t; i++) pr(Aa[i]), ps(); } Tp2 void psa2(T1&& Aa, T2 t1, T2 t2) { for(int i = 0; i < t1; i++) {for(int j = 0; j < t2; j++) pr(Aa[i][j]), pw(); ps();} } Tp void pr(const T& Xx) { if(!sz(Xx)) return; bool fst = 1; bool op = 0; if (parsepair(*Xx.begin())) op = 1; for (const auto& Aa: Xx) {if(!fst) pw(); if(op) pr("{"); pr(Aa), fst = 0; if(op) pr("}"); } } Tps void pr(const T& t, const Ts&... ts) { pr(t); pr(ts...); } Tps void ps(const T& t, const Ts&... ts) { pr(t); if (sizeof...(ts)) {if (!parse(t)) pw(); } ps(ts...); } Tp void pn(const T& t) { for (const auto& Aa: t) ps(Aa); } Tps void pw(const T& t, const Ts&... ts) { pr(t); if (sizeof...(ts)) pw(); pw(ts...); } Tps void pc(const T& t, const Ts&... ts) { bool op = 0; if (parsepair(t)) op = 1; if(op) pr("{"); pr(t); if(op) pr("}"); if (sizeof...(ts)) pr(", "); pc(ts...); } namespace trace { #define tr(Xx...) pr("[",#Xx,"] = ["), pc(Xx); #define tra(Xx, y...) __f0(#Xx, Xx, y) #define tran(Xx, n) __fn(n, #Xx, Xx) // TO DO~ variadic multidimensional Tp2 void __f(const char* name, const T1& Xx, const T2& y){ pr("[",y,"] = "); ps(Xx); } Tps2 void __f(const char* name, const T1& Xx, const T2& y, const Ts&... rest){ const char *open = strchr(name, '['); pr("[",y,"]"); __f(open+1, Xx, rest...); } Tps2 void __f0(const char* name, const T1& Xx, const T2& y, const Ts&... rest){ const char *open = strchr(name, '['); pr(name, size_t(open-name)); __f(name, Xx, y, rest...); } Tp void __fn(int n, const char* name, const T& Xx) { for(int i = 0; i < n; i++) pr(name), __f(name, Xx[i], i); } } } using namespace minmax; using namespace input; using namespace output; using namespace output::trace; //mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); const int N = 2e5 + 5; int solve () { int i, n, m, ans = 0; re(n, m); if(n == 1) ans = 0; else if(n == 2) ans = m; else ans = 2*m; ps(ans); return 0; } int32_t main() { IOS; int Q; for(cin >> Q; Q; Q--) solve(); return 0; }
[ "ghriday.bits@gmail.com" ]
ghriday.bits@gmail.com
f9c78b50d51df1a765999cdc90c0eea5a485bf42
f39dc798ff7e2be9bc60fcce54d71508a960d7aa
/meta-xilinx/meta-xilinx-bsp/conf/machine/include/machine-xilinx-default.inc
2ffd5b21f56a9e729971cd655127d700f39b9fac
[ "MIT" ]
permissive
BenPai99/openbmc-1
8696ca54eebf66b76cccc0d4373dc83af416d974
f7478caa32aa01fe42cea470a6a757ab4a542dbc
refs/heads/master
2021-02-14T21:47:47.486523
2020-03-04T07:44:34
2020-03-04T07:44:34
244,837,431
0
0
NOASSERTION
2020-03-04T07:41:19
2020-03-04T07:41:19
null
UTF-8
C++
false
false
2,679
inc
# Default Xilinx BSP Machine settings MACHINE_FEATURES_BACKFILL_CONSIDERED += "rtc" # File System Configuration IMAGE_FSTYPES ?= "tar.gz cpio cpio.gz.u-boot" # Kernel Configuration XILINX_DEFAULT_KERNEL := "linux-xlnx" XILINX_DEFAULT_KERNEL_microblaze := "linux-yocto" XILINX_DEFAULT_KERNEL_zynqmp := "linux-yocto" PREFERRED_PROVIDER_virtual/kernel ??= "${XILINX_DEFAULT_KERNEL}" # U-Boot Configuration XILINX_DEFAULT_UBOOT := "u-boot-xlnx" XILINX_DEFAULT_UBOOT_zynqmp := "u-boot" PREFERRED_PROVIDER_virtual/bootloader ??= "${XILINX_DEFAULT_UBOOT}" PREFERRED_PROVIDER_virtual/boot-bin ??= "${PREFERRED_PROVIDER_virtual/bootloader}" UBOOT_SUFFIX ?= "img" UBOOT_SUFFIX_zynqmp ?= "bin" UBOOT_SUFFIX_microblaze ?= "bin" UBOOT_BINARY ?= "u-boot.${UBOOT_SUFFIX}" UBOOT_ELF ?= "u-boot" UBOOT_ELF_zynq ?= "u-boot.elf" UBOOT_ELF_aarch64 ?= "u-boot.elf" #Hardware accelaration PREFERRED_PROVIDER_virtual/libgles1_mali400 = "libmali-xlnx" PREFERRED_PROVIDER_virtual/libgles2_mali400 = "libmali-xlnx" PREFERRED_PROVIDER_virtual/egl_mali400 = "libmali-xlnx" PREFERRED_PROVIDER_virtual/libgl_mali400 = "mesa-gl" PREFERRED_PROVIDER_virtual/mesa_mali400 = "mesa-gl" # microblaze does not get on with pie for reasons not looked into as yet GCCPIE_microblaze = "" GLIBCPIE_microblaze = "" SECURITY_CFLAGS_microblaze = "" SECURITY_LDFLAGS_microblaze = "" XSERVER ?= " \ xserver-xorg \ xf86-input-evdev \ xf86-input-mouse \ xf86-input-keyboard \ xf86-video-fbdev \ ${XSERVER_EXT} \ " IMAGE_BOOT_FILES ?= "${@get_default_image_boot_files(d)}" def get_default_image_boot_files(d): files = [] # kernel images kerneltypes = set((d.getVar("KERNEL_IMAGETYPE") or "").split()) kerneltypes |= set((d.getVar("KERNEL_IMAGETYPES") or "").split()) for i in kerneltypes: files.append(i) # u-boot image if d.getVar("UBOOT_BINARY"): files.append(d.getVar("UBOOT_BINARY")) # device trees (device-tree only), these are first as they are likely desired over the kernel ones if "device-tree" in (d.getVar("MACHINE_ESSENTIAL_EXTRA_RDEPENDS") or ""): files.append("devicetree/*.dtb") # device trees (kernel only) if d.getVar("KERNEL_DEVICETREE"): dtbs = d.getVar("KERNEL_DEVICETREE").split(" ") dtbs = [os.path.basename(d) for d in dtbs] for dtb in dtbs: files.append(dtb) return " ".join(files) XSERVER_EXT ?= "" XSERVER_EXT_zynqmp ?= "xf86-video-armsoc" # For MicroBlaze default all microblaze machines to use GDB 7.7.1 (for gdbserver/gdb) PREFERRED_VERSION_gdb_microblaze = "7.7.1" FPGA_MNGR_RECONFIG_ENABLE ?= "${@bb.utils.contains('IMAGE_FEATURES', 'fpga-manager', '1', '0', d)}"
[ "bradleyb@fuzziesquirrel.com" ]
bradleyb@fuzziesquirrel.com
deeab6bfd6a42b5914710123c7ccac6c1afac9e7
5c6ccc082d9d0d42a69e22cfd9a419a5b87ff6cd
/coursera/cppYandex/white/week4/rational_map.cpp
63c164833169624693b4404b8d353a4e7f0c9284
[]
no_license
kersky98/stud
191c809bacc982c715d9610be282884a504d456d
d395a372e72aeb17dfad5c72d46e84dc59454410
refs/heads/master
2023-03-09T20:47:25.082673
2023-03-01T08:28:32
2023-03-01T08:28:32
42,979,807
0
0
null
null
null
null
UTF-8
C++
false
false
3,956
cpp
#include <iostream> #include <map> #include <set> #include <vector> using namespace std; class Rational { public: Rational(int numerator = 0, int denominator = 1) { if(numerator != 0) { int a = max(abs(numerator), abs(denominator)); int b = min(abs(numerator), abs(denominator)); int nod; while(a % b != 0) { int tmp = b; b = a % b; a = tmp; } nod = b; //cout << nod << endl; p = numerator/nod; q = denominator/nod; if (q < 0){ p = -p; q = -q; } }else { p = 0; q = 1; } } int Numerator() const { return p; } int Denominator() const { return q; } void SetNumerator(int numerator){ p = numerator; } void SetDenominator(int denominator){ q = denominator; } private: int p, q; }; // Реализуйте для класса Rational операторы ==, + и - bool operator==(const Rational& lhs, const Rational& rhs) { return lhs.Numerator() == rhs.Numerator() && lhs.Denominator() == rhs.Denominator(); } Rational operator+(const Rational& lhs, const Rational& rhs) { int num = lhs.Numerator()*rhs.Denominator() + rhs.Numerator()*lhs.Denominator(); int denom = lhs.Denominator()*rhs.Denominator(); Rational result(num, denom); return result; } Rational operator-(const Rational& lhs, const Rational& rhs) { int num = lhs.Numerator()*rhs.Denominator() - rhs.Numerator()*lhs.Denominator(); int denom = lhs.Denominator()*rhs.Denominator(); Rational result(num, denom); return result; } Rational operator*(const Rational& lhs, const Rational& rhs) { int num = lhs.Numerator() * rhs.Numerator(); int denom = lhs.Denominator()*rhs.Denominator(); Rational result(num, denom); return result; } Rational operator/(const Rational& lhs, const Rational& rhs) { int num = lhs.Numerator() * rhs.Denominator(); int denom = lhs.Denominator() * rhs.Numerator(); Rational result(num, denom); return result; } // Реализуйте для класса Rational операторы << и >> ostream& operator<<(ostream& stream, const Rational& r) { stream << r.Numerator() << "/" << r.Denominator(); return stream; } istream& operator>>(istream& stream, Rational& r) { int p = r.Numerator(), q = r.Denominator(); if(!stream.eof()){ stream >> p; if(!stream.eof()) stream.ignore(1); if(!stream.eof()){ stream >> q; } Rational tmp(p, q); r = tmp; } return stream; } // Реализуйте для класса Rational оператор(ы), необходимые для использования его // в качестве ключа map'а и элемента set'а bool operator<(const Rational& lhs, const Rational& rhs) { bool result = lhs.Numerator() * rhs.Denominator() < lhs.Denominator() * rhs.Numerator(); return result; } int main() { { const set<Rational> rs = {{1, 2}, {1, 25}, {3, 4}, {3, 4}, {1, 2}}; if (rs.size() != 3) { cout << "Wrong amount of items in the set" << endl; return 1; } vector<Rational> v; for (auto x : rs) { v.push_back(x); } if (v != vector<Rational>{{1, 25}, {1, 2}, {3, 4}}) { cout << "Rationals comparison works incorrectly" << endl; return 2; } } { map<Rational, int> count; ++count[{1, 2}]; ++count[{1, 2}]; ++count[{2, 3}]; if (count.size() != 2) { cout << "Wrong amount of items in the map" << endl; return 3; } } cout << "OK" << endl; return 0; }
[ "kerskiy-ev@pao.local" ]
kerskiy-ev@pao.local
65be8bde52f672872ebbcb5c70c10351af88a47b
0eb139bba66190871668da5af40ba81e5d02b9a1
/Lam o nha/So_Phuc/So_Phuc/sophuc.h
1dc18e3d3131d4710ca12be300a9ac2c0d6b36a0
[]
no_license
tronghao/LapTrinhHuongDoiTuong
8c3a86ba026e6a56017b4aad2ac89dcfaf046284
58bc6d5f2e2d21e1e60ea24c38a5190f74d4a58f
refs/heads/master
2020-05-16T04:44:06.879585
2019-06-16T07:28:29
2019-06-16T07:28:29
182,788,710
1
1
null
null
null
null
UTF-8
C++
false
false
716
h
#include <iostream> using namespace std; class SOPHUC{ private: float thuc, ao; public: SOPHUC(); void nhapSP(); void xuatSP(); SOPHUC tinhTong(SOPHUC sp); SOPHUC tinhHieu(SOPHUC sp); ~SOPHUC(); }; SOPHUC::SOPHUC() { thuc = ao = 0; } void SOPHUC::nhapSP() { cout << "Nhap lan luot phan thuc va ao: "; cin >> thuc >> ao; } void SOPHUC::xuatSP() { cout << thuc; if (ao < 0) cout << " - " << ao*-1 << "i"; else cout << " + " << ao << "i"; } SOPHUC SOPHUC::tinhTong(SOPHUC sp) { SOPHUC tong; tong.thuc = sp.thuc + thuc; tong.ao = sp.ao + ao; return tong; } SOPHUC SOPHUC::tinhHieu(SOPHUC sp) { SOPHUC hieu; hieu.thuc = thuc - sp.thuc; hieu.ao = ao - sp.ao; return hieu; } SOPHUC::~SOPHUC(){}
[ "tronghaomaico@gmail.com" ]
tronghaomaico@gmail.com
c7341ab3fc395bd8d629b9aeaa0aa9fd0ae95e2d
95f80c4a941fe50958b5179a9537436d8bdb8c69
/flat/0.2/wallShearStress
fe3ffa7710ff02eab9bb7495a16f6b5ea43b32a1
[]
no_license
thunde47/biofilm_modeling
9545fc1a9f277a7deee6a6c34b7deace1d325cb2
bf818989a5f1c2a476599495b1291822972afbcb
refs/heads/master
2022-12-19T08:12:52.518452
2020-09-13T05:12:07
2020-09-13T05:12:07
281,104,789
2
1
null
null
null
null
UTF-8
C++
false
false
4,028
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: 5.x | | \\ / A nd | Web: www.OpenFOAM.org | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volVectorField; location "0.2"; object wallShearStress; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 2 -2 0 0 0 0]; internalField uniform (0 0 0); boundaryField { movingWall { type calculated; value nonuniform List<vector> 50 ( (0.184675 -6.43606e-11 0) (0.184675 -5.56961e-11 0) (0.184675 -2.509e-11 0) (0.184675 -1.29577e-11 0) (0.184675 -7.18046e-12 0) (0.184675 -3.67587e-12 0) (0.184675 -1.77686e-12 0) (0.184675 -8.51718e-13 0) (0.184675 -4.26405e-13 0) (0.184675 -2.24361e-13 0) (0.184675 -1.29676e-13 0) (0.184675 -8.15181e-14 0) (0.184675 -5.58456e-14 0) (0.184675 -3.94193e-14 0) (0.184675 -2.87204e-14 0) (0.184675 -2.05211e-14 0) (0.184675 -1.42952e-14 0) (0.184675 -9.694e-15 0) (0.184675 -6.27527e-15 0) (0.184675 -3.61615e-15 0) (0.184675 -1.92884e-15 0) (0.184675 -1.91922e-16 0) (0.184675 8.31349e-16 0) (0.184675 1.104e-15 0) (0.184675 1.14031e-15 0) (0.184675 1.69821e-15 0) (0.184675 2.33729e-15 0) (0.184675 2.37583e-15 0) (0.184675 2.79576e-15 0) (0.184675 3.35762e-15 0) (0.184675 4.51101e-15 0) (0.184675 5.57787e-15 0) (0.184675 6.82054e-15 0) (0.184675 9.0402e-15 0) (0.184675 1.19129e-14 0) (0.184675 1.55622e-14 0) (0.184675 2.19435e-14 0) (0.184675 3.14061e-14 0) (0.184675 4.8516e-14 0) (0.184675 8.08684e-14 0) (0.184675 1.44605e-13 0) (0.184675 2.76727e-13 0) (0.184675 5.52542e-13 0) (0.184675 1.13607e-12 0) (0.184675 2.36277e-12 0) (0.184675 4.80356e-12 0) (0.184675 9.12084e-12 0) (0.184675 1.71639e-11 0) (0.184675 4.11474e-11 0) (0.184675 5.23709e-11 0) ) ; } Inlet { type calculated; value uniform (0 0 0); } Outlet { type calculated; value uniform (0 0 0); } Bottom { type calculated; value nonuniform List<vector> 50 ( (-0.184675 6.5968e-11 0) (-0.184675 5.42097e-11 0) (-0.184675 2.46493e-11 0) (-0.184675 1.31236e-11 0) (-0.184675 7.19856e-12 0) (-0.184675 3.66662e-12 0) (-0.184675 1.77433e-12 0) (-0.184675 8.39068e-13 0) (-0.184675 3.95549e-13 0) (-0.184675 1.86691e-13 0) (-0.184675 9.18616e-14 0) (-0.184675 4.93234e-14 0) (-0.184675 3.06145e-14 0) (-0.184675 2.19096e-14 0) (-0.184675 1.72099e-14 0) (-0.184675 1.421e-14 0) (-0.184675 1.20165e-14 0) (-0.184675 1.00958e-14 0) (-0.184675 8.39697e-15 0) (-0.184675 7.10493e-15 0) (-0.184675 5.93049e-15 0) (-0.184675 4.97488e-15 0) (-0.184675 4.12966e-15 0) (-0.184675 3.42125e-15 0) (-0.184675 2.95958e-15 0) (-0.184675 2.5491e-15 0) (-0.184675 2.05531e-15 0) (-0.184675 1.66541e-15 0) (-0.184675 1.22266e-15 0) (-0.184675 5.30946e-16 0) (-0.184675 -2.08688e-16 0) (-0.184675 -1.26794e-15 0) (-0.184675 -2.85723e-15 0) (-0.184675 -4.79548e-15 0) (-0.184675 -7.8501e-15 0) (-0.184675 -1.2387e-14 0) (-0.184675 -1.82257e-14 0) (-0.184675 -2.73388e-14 0) (-0.184675 -4.20732e-14 0) (-0.184675 -6.92942e-14 0) (-0.184675 -1.23521e-13 0) (-0.184675 -2.3897e-13 0) (-0.184675 -4.88558e-13 0) (-0.184675 -1.04897e-12 0) (-0.184675 -2.27586e-12 0) (-0.184675 -4.72569e-12 0) (-0.184675 -8.93198e-12 0) (-0.184675 -1.74893e-11 0) (-0.184675 -4.29385e-11 0) (-0.184675 -5.1896e-11 0) ) ; } frontAndBack { type empty; } } // ************************************************************************* //
[ "adwaith1990@gmail.com" ]
adwaith1990@gmail.com
22003f09eccb78abc1ae1b6013e8293826dbcb95
5087a17f8c08a4f89f20841c8529fa2e5914a1fb
/Frame/Contrib/BusPlugin/AFBusPlugin.cpp
28a1c4e555213d8682a7fc588ab44a54ab5d3b65
[ "Apache-2.0" ]
permissive
denfrost/ARK
673f8184ed9b962e17ef39f916c0b37a7560e786
68c80d2f595b12eab00a8bfa21dd121c4f401837
refs/heads/master
2020-03-25T18:34:52.808860
2018-07-24T08:57:08
2018-07-24T08:57:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,432
cpp
/* * This source file is part of ArkGameFrame * For the latest info, see https://github.com/ArkGame * * Copyright (c) 2013-2018 ArkGame authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include "AFBusPlugin.h" #include "AFCBusModule.h" #include "AFCProcModule.h" #ifdef ARK_DYNAMIC_PLUGIN ARK_DLL_PLUGIN_ENTRY(AFBusPlugin) ARK_DLL_PLUGIN_EXIT(AFBusPlugin) #endif ////////////////////////////////////////////////////////////////////////// int AFBusPlugin::GetPluginVersion() { return 0; } const std::string AFBusPlugin::GetPluginName() { return GET_CLASS_NAME(AFBusPlugin) } void AFBusPlugin::Install() { REGISTER_MODULE(pPluginManager, AFIBusModule, AFCBusModule) REGISTER_MODULE(pPluginManager, AFIProcModule, AFCProcModule) } void AFBusPlugin::Uninstall() { UNREGISTER_MODULE(pPluginManager, AFIProcModule, AFCProcModule) UNREGISTER_MODULE(pPluginManager, AFIBusModule, AFCBusModule) }
[ "362148418@qq.com" ]
362148418@qq.com
50e9b8f4e4da908c82f10854307aa873418ab8d5
de21cf6e87cfcdc47fd16d1ae976a75c4732ef1b
/BankSolution/Person.h
93db220fb71fb182ab0e10f3e5a78713ff66edb4
[]
no_license
Aimireal/1718-BankSolution
0797a6a0508b1947f9b3affd65d43e42b43ffaac
cb9153b9c17d3ce20f3598d9ed3260c6b957d8c1
refs/heads/master
2023-04-29T06:51:40.519019
2021-05-22T11:39:45
2021-05-22T11:39:45
369,655,165
0
0
null
null
null
null
UTF-8
C++
false
false
459
h
#pragma once #include "stdafx.h" #include "Account.h" using namespace std; class Person { public: Person(string); void addAccount(Account &); bool closeAccount(int *); void printAllAccounts(); bool creditMoney(int *, double *); bool debitMoney(int *, double *); virtual ~Person(); Person(const Date & dOB); //Test void printDateOfBirth() const; //Test private: const string name; vector<Account> accounts; const Date dateOfBirth; //Test };
[ "dylanhudson1998@gmail.com" ]
dylanhudson1998@gmail.com
122c8ec02fac795516c2440267d9e624ac047ba8
b02b9e18fb7fe8ed497c7c5d3d5a4619aa8904c9
/VigenereCipher/stdafx.cpp
d7fec22b1d06656c84dffdab85cd30851af4ea40
[]
no_license
RalucaPostolache/VigenereCipher
08de1e1a6a773924a6c09a6de646b98d0305d001
919c4c393d30a3f8974b154a8be82dec9f5b6d67
refs/heads/master
2020-04-07T02:32:44.601531
2018-11-17T12:04:51
2018-11-17T12:04:51
157,980,634
0
0
null
null
null
null
UTF-8
C++
false
false
293
cpp
// stdafx.cpp : source file that includes just the standard includes // VigenereCipher.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file
[ "raluca.mpostolache@yahoo.com" ]
raluca.mpostolache@yahoo.com
6e138d9d0ef6e990fd4dc8ed629a79ca189d5a1b
f986498285c5f235166f9d7847e4834ba75eb115
/Entidades/Ministro.cpp
5094f7ea4faca0fcdb90e363a6efc82aaa9dee2e
[]
no_license
camilaf/Conculandia
d3b85f733fab2ceec20589882dc90735aee7a6b4
c97e863652186e5110c9638f77184c714a62e7e6
refs/heads/master
2020-03-14T16:03:55.966113
2018-05-02T18:12:07
2018-05-02T18:12:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,520
cpp
#include "Ministro.h" Ministro :: Ministro() { } Ministro :: ~Ministro() { } /* Se ocupa de abrir el fifo de lectura sobre el cual el Ministro de Seguridad recibira las alertas para agregar o eliminar algun rasgo del listado de Personas de Riesgo. */ void Ministro :: esperarAlertas() { SIGINT_Handler sigint_handler; SignalHandler :: getInstance()->registrarHandler(SIGINT, &sigint_handler); Logger :: getInstance()->registrar("El Ministro de Seguridad se prepara para recibir alertas"); FifoLectura fifoAlertas(ARCHIVO_ALERTAS); fifoAlertas.abrir(); while (sigint_handler.getGracefulQuit() == 0) { char buffer[BUFFSIZE]; // Lee la siguiente alerta ssize_t bytesLeidos = fifoAlertas.leer(static_cast<void *> (buffer), BUFFSIZE); if (bytesLeidos <= 0) { if ((errno == EINTR) || (bytesLeidos == 0)) { break; } cerr << "Error al leer del fifo: " << strerror(errno) << endl; } string comando = string(strtok(buffer, "-")); string rasgo = string(strtok(NULL, "-")); Logger :: getInstance()->registrar("El Ministro de Seguridad lee el comando: " + comando + " rasgo: " + rasgo); if (comando == "Agregar") { this->agregarRasgo(rasgo); } else { this->quitarRasgo(rasgo); } memset(buffer, 0, BUFFSIZE); } Logger :: getInstance()->registrar("El Ministro de Seguridad cierra el fifo de alertas"); fifoAlertas.cerrar(); } /* Metodo que se ocupa de crear el listado de rasgos que los empleados iran consultando. Devuelve -1 en caso de error, y 0 en caso contrario. */ int Ministro :: crearListado() { fstream listado(ARCHIVO_PERSONAS_RIESGO); Logger :: getInstance()->registrar("Se crea el listado de Personas de Riesgo"); listado.open(ARCHIVO_PERSONAS_RIESGO, fstream :: in | fstream :: out |fstream :: trunc); if (listado.fail() && (errno != 0)) { cerr << "Error al crear el listado Personas de Riesgo: " << strerror(errno) << endl; return -1; } listado.close(); return 0; } /* Se encarga de consultar el listado de Personas de Riesgo, devolviendo un vector con los rasgos que se encuentran en la misma. Para el acceso al recurso compartido se usa un lock sobre el file. */ vector<string> Ministro:: consultarListado() { LockFile lock(ARCHIVO_PERSONAS_RIESGO); if (lock.tomarLock() < 0) { if (errno == EINTR) { exit(0); } cerr << "Error al tomar el lock: " << strerror(errno) << endl; } Logger :: getInstance()->registrar("Se consulta el listado de Personas de Riesgo"); ifstream listadoRasgos(ARCHIVO_PERSONAS_RIESGO); string rasgo; vector<string> vectorRasgos; string listado = ""; // Obtengo los rasgos del listado while (getline(listadoRasgos, rasgo)) { listado += rasgo + " - "; vectorRasgos.push_back(rasgo); } Logger :: getInstance()->registrar("Lee listado: '" + listado + "'"); listadoRasgos.close(); if (lock.liberarLock() < 0) { if (errno == EINTR) { exit(0); } cerr << "Error al liberar el lock: " << strerror(errno) << endl; } return vectorRasgos; } /* Se encarga de agregar un rasgo en el listado de Personas de Riesgo. */ void Ministro :: agregarRasgo(string rasgo) { LockFile lock(ARCHIVO_PERSONAS_RIESGO); if (lock.tomarLock() < 0) { if (errno == EINTR) { exit(0); } cerr << "Error al tomar el lock: " << strerror(errno) << endl; } Logger :: getInstance()->registrar("Se agrega el rasgo '" + string(rasgo) + "' al listado"); ofstream listadoRasgos(ARCHIVO_PERSONAS_RIESGO, ios :: out | ios :: trunc); // Agrego el rasgo al vector y escribo los rasgos this->listadoActual.push_back(rasgo); for (size_t i = 0; i < listadoActual.size(); i++) { listadoRasgos << listadoActual[i] << endl; } listadoRasgos.close(); string nuevoListado = this->imprimirListado(); Logger :: getInstance()->registrar("Nuevo listado '" + nuevoListado + "'"); if (lock.liberarLock() < 0) { if (errno == EINTR) { exit(0); } cerr << "Error al liberar el lock: " << strerror(errno) << endl; } } /* Se encarga de eliminar un rasgo en el listado de Personas de Riesgo. */ void Ministro :: quitarRasgo(string rasgo) { LockFile lock(ARCHIVO_PERSONAS_RIESGO); if (lock.tomarLock() < 0) { if (errno == EINTR) { exit(0); } cerr << "Error al tomar el lock: " << strerror(errno) << endl; } Logger :: getInstance()->registrar("Se quita el rasgo '" + string(rasgo) + "' al listado en la memoria compartida"); ofstream listadoRasgos(ARCHIVO_PERSONAS_RIESGO, ios :: out | ios :: trunc); // Elimino el rasgo del vector y escribo los rasgos restantes vector<string> :: iterator it = find(this->listadoActual.begin(), this->listadoActual.end(), rasgo); if (it != this->listadoActual.end()) { this->listadoActual.erase(it); } for (size_t i = 0; i < listadoActual.size(); i++) { listadoRasgos << listadoActual[i] << endl; } listadoRasgos.close(); string nuevoListado = this->imprimirListado(); Logger :: getInstance()->registrar("Nuevo listado '" + nuevoListado + "'"); if (lock.liberarLock() < 0) { if (errno == EINTR) { exit(0); } cerr << "Error al liberar el lock: " << strerror(errno) << endl; } } string Ministro :: imprimirListado() { if (this->listadoActual.size() == 0) { return ""; } string listado = this->listadoActual[0]; for (size_t i = 1; i < this->listadoActual.size(); i++) { listado += " - " + this->listadoActual[i]; } return listado; }
[ "cdetrincheria@hotmail.com" ]
cdetrincheria@hotmail.com
d5320f7a1eb1000239740b99a59dc9a626a3b498
47d9583df227a22a9e05bafdcf05db2421f1f532
/src/NullLightController.h
7880d204d429ecc5730322e1a74866fe17d5bbfa
[]
no_license
lmeijvogel/model_lights
6b286ae233d7b5dfb3058a7edb70e0494844fd71
d153085af264391825b8cc1eb4395e214b2eb360
refs/heads/master
2020-04-27T09:35:31.497093
2019-06-22T20:45:36
2019-06-22T20:45:36
174,221,313
0
0
null
null
null
null
UTF-8
C++
false
false
556
h
#ifndef NULL_LIGHT_CONTROLLER_H #define NULL_LIGHT_CONTROLLER_H #include "AbstractLightController.h" class NullLightController : public AbstractLightController { public: virtual void setOn(); virtual void setOff(); virtual void setAnimating(); virtual void gradualOn(unsigned long currentTimeMs, unsigned long transitionTimeMs); virtual void gradualOff(unsigned long currentTimeMs, unsigned long transitionTimeMs); virtual void cycle(int); virtual void changeDelay(double); virtual void clockTick(unsigned long currentTimeMs); }; #endif
[ "l.meijvogel@yahoo.co.uk" ]
l.meijvogel@yahoo.co.uk
86285f4714769abf8855965f02bbc54a1aaad1a8
1b57e986d63f659c751679cc105d8d688ce21d52
/src/util/sha1.cpp
1ebdf166cc78f7fbf26b618bee42644e2dbac17d
[]
no_license
skyformat99/cos-cpp-sdk-v5
14c87d19ea8bddee785e9732f1a0b6df0e6440b9
b4e33b61df3f7f0a327854c00dc060bdbe210fbe
refs/heads/master
2021-01-22T01:48:01.709028
2017-09-01T07:14:00
2017-09-01T07:14:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,539
cpp
#include "util/sha1.h" #include <string.h> #include <iostream> #include <sstream> #include "util/string_util.h" namespace qcloud_cos { Sha1::Sha1() { ShaInit(&m_sha); } Sha1::~Sha1() { } void Sha1::Append(const char* data, unsigned int size) { ShaUpdate(&m_sha, (SHA_BYTE*)data, size); } std::string Sha1::Final() { char key[SHA_DIGESTSIZE] = {0}; ShaFinal((unsigned char *)key, &m_sha); char out[64] = {0}; ShaOutput((unsigned char *)key, (unsigned char*)out); return out; } /* UNRAVEL should be fastest & biggest */ /* UNROLL_LOOPS should be just as big, but slightly slower */ /* both undefined should be smallest and slowest */ #define UNRAVEL /* #define UNROLL_LOOPS */ /* SHA f()-functions */ #define f1(x,y,z) ((x & y) | (~x & z)) #define f2(x,y,z) (x ^ y ^ z) #define f3(x,y,z) ((x & y) | (x & z) | (y & z)) #define f4(x,y,z) (x ^ y ^ z) /* SHA constants */ #define CONST1 0x5a827999L #define CONST2 0x6ed9eba1L #define CONST3 0x8f1bbcdcL #define CONST4 0xca62c1d6L /* truncate to 32 bits -- should be a null op on 32-bit machines */ #define T32(x) ((x) & 0xffffffffL) /* 32-bit rotate */ #define R32(x,n) T32(((x << n) | (x >> (32 - n)))) /* the generic case, for when the overall rotation is not unraveled */ #define FG(n) \ T = T32(R32(A,5) + f##n(B,C,D) + E + *WP++ + CONST##n); \ E = D; D = C; C = R32(B,30); B = A; A = T /* specific cases, for when the overall rotation is unraveled */ #define FA(n) \ T = T32(R32(A,5) + f##n(B,C,D) + E + *WP++ + CONST##n); B = R32(B,30) #define FB(n) \ E = T32(R32(T,5) + f##n(A,B,C) + D + *WP++ + CONST##n); A = R32(A,30) #define FC(n) \ D = T32(R32(E,5) + f##n(T,A,B) + C + *WP++ + CONST##n); T = R32(T,30) #define FD(n) \ C = T32(R32(D,5) + f##n(E,T,A) + B + *WP++ + CONST##n); E = R32(E,30) #define FE(n) \ B = T32(R32(C,5) + f##n(D,E,T) + A + *WP++ + CONST##n); D = R32(D,30) #define FT(n) \ A = T32(R32(B,5) + f##n(C,D,E) + T + *WP++ + CONST##n); C = R32(C,30) /* do SHA transformation */ static void ShaTransform(SHA_INFO *sha_info) { int i; SHA_BYTE *dp; SHA_LONG T, A, B, C, D, E, W[80], *WP; dp = sha_info->data; /* the following makes sure that at least one code block below is traversed or an error is reported, without the necessity for nested preprocessor if/else/endif blocks, which are a great pain in the nether regions of the anatomy... */ #undef SWAP_DONE #if (SHA_BYTE_ORDER == 1234) #define SWAP_DONE for (i = 0; i < 16; ++i) { T = *((SHA_LONG *) dp); dp += 4; W[i] = ((T << 24) & 0xff000000) | ((T << 8) & 0x00ff0000) | ((T >> 8) & 0x0000ff00) | ((T >> 24) & 0x000000ff); } #endif /* SHA_BYTE_ORDER == 1234 */ #if (SHA_BYTE_ORDER == 4321) #define SWAP_DONE for (i = 0; i < 16; ++i) { T = *((SHA_LONG *) dp); dp += 4; W[i] = T32(T); } #endif /* SHA_BYTE_ORDER == 4321 */ #if (SHA_BYTE_ORDER == 12345678) #define SWAP_DONE for (i = 0; i < 16; i += 2) { T = *((SHA_LONG *) dp); dp += 8; W[i] = ((T << 24) & 0xff000000) | ((T << 8) & 0x00ff0000) | ((T >> 8) & 0x0000ff00) | ((T >> 24) & 0x000000ff); T >>= 32; W[i+1] = ((T << 24) & 0xff000000) | ((T << 8) & 0x00ff0000) | ((T >> 8) & 0x0000ff00) | ((T >> 24) & 0x000000ff); } #endif /* SHA_BYTE_ORDER == 12345678 */ #if (SHA_BYTE_ORDER == 87654321) #define SWAP_DONE for (i = 0; i < 16; i += 2) { T = *((SHA_LONG *) dp); dp += 8; W[i] = T32(T >> 32); W[i+1] = T32(T); } #endif /* SHA_BYTE_ORDER == 87654321 */ #ifndef SWAP_DONE #error Unknown byte order -- you need to add code here #endif /* SWAP_DONE */ for (i = 16; i < 80; ++i) { W[i] = W[i-3] ^ W[i-8] ^ W[i-14] ^ W[i-16]; #if (SHA_VERSION == 1) W[i] = R32(W[i], 1); #endif /* SHA_VERSION */ } A = sha_info->digest[0]; B = sha_info->digest[1]; C = sha_info->digest[2]; D = sha_info->digest[3]; E = sha_info->digest[4]; WP = W; #ifdef UNRAVEL FA(1); FB(1); FC(1); FD(1); FE(1); FT(1); FA(1); FB(1); FC(1); FD(1); FE(1); FT(1); FA(1); FB(1); FC(1); FD(1); FE(1); FT(1); FA(1); FB(1); FC(2); FD(2); FE(2); FT(2); FA(2); FB(2); FC(2); FD(2); FE(2); FT(2); FA(2); FB(2); FC(2); FD(2); FE(2); FT(2); FA(2); FB(2); FC(2); FD(2); FE(3); FT(3); FA(3); FB(3); FC(3); FD(3); FE(3); FT(3); FA(3); FB(3); FC(3); FD(3); FE(3); FT(3); FA(3); FB(3); FC(3); FD(3); FE(3); FT(3); FA(4); FB(4); FC(4); FD(4); FE(4); FT(4); FA(4); FB(4); FC(4); FD(4); FE(4); FT(4); FA(4); FB(4); FC(4); FD(4); FE(4); FT(4); FA(4); FB(4); sha_info->digest[0] = T32(sha_info->digest[0] + E); sha_info->digest[1] = T32(sha_info->digest[1] + T); sha_info->digest[2] = T32(sha_info->digest[2] + A); sha_info->digest[3] = T32(sha_info->digest[3] + B); sha_info->digest[4] = T32(sha_info->digest[4] + C); #else /* !UNRAVEL */ #ifdef UNROLL_LOOPS FG(1); FG(1); FG(1); FG(1); FG(1); FG(1); FG(1); FG(1); FG(1); FG(1); FG(1); FG(1); FG(1); FG(1); FG(1); FG(1); FG(1); FG(1); FG(1); FG(1); FG(2); FG(2); FG(2); FG(2); FG(2); FG(2); FG(2); FG(2); FG(2); FG(2); FG(2); FG(2); FG(2); FG(2); FG(2); FG(2); FG(2); FG(2); FG(2); FG(2); FG(3); FG(3); FG(3); FG(3); FG(3); FG(3); FG(3); FG(3); FG(3); FG(3); FG(3); FG(3); FG(3); FG(3); FG(3); FG(3); FG(3); FG(3); FG(3); FG(3); FG(4); FG(4); FG(4); FG(4); FG(4); FG(4); FG(4); FG(4); FG(4); FG(4); FG(4); FG(4); FG(4); FG(4); FG(4); FG(4); FG(4); FG(4); FG(4); FG(4); #else /* !UNROLL_LOOPS */ for (i = 0; i < 20; ++i) { FG(1); } for (i = 20; i < 40; ++i) { FG(2); } for (i = 40; i < 60; ++i) { FG(3); } for (i = 60; i < 80; ++i) { FG(4); } #endif /* !UNROLL_LOOPS */ sha_info->digest[0] = T32(sha_info->digest[0] + A); sha_info->digest[1] = T32(sha_info->digest[1] + B); sha_info->digest[2] = T32(sha_info->digest[2] + C); sha_info->digest[3] = T32(sha_info->digest[3] + D); sha_info->digest[4] = T32(sha_info->digest[4] + E); #endif /* !UNRAVEL */ } void ShaInit(SHA_INFO* sha_info) { sha_info->digest[0] = 0x67452301L; sha_info->digest[1] = 0xefcdab89L; sha_info->digest[2] = 0x98badcfeL; sha_info->digest[3] = 0x10325476L; sha_info->digest[4] = 0xc3d2e1f0L; sha_info->count_lo = 0L; sha_info->count_hi = 0L; sha_info->local = 0; } /* update the SHA digest */ void ShaUpdate(SHA_INFO* sha_info, SHA_BYTE* buffer, int count) { int i; SHA_LONG clo; clo = T32(sha_info->count_lo + ((SHA_LONG) count << 3)); if (clo < sha_info->count_lo) { ++sha_info->count_hi; } sha_info->count_lo = clo; sha_info->count_hi += (SHA_LONG) count >> 29; if (sha_info->local) { i = SHA_BLOCKSIZE - sha_info->local; if (i > count) { i = count; } memcpy(((SHA_BYTE *) sha_info->data) + sha_info->local, buffer, i); count -= i; buffer += i; sha_info->local += i; if (sha_info->local == SHA_BLOCKSIZE) { ShaTransform(sha_info); } else { return; } } while (count >= SHA_BLOCKSIZE) { memcpy(sha_info->data, buffer, SHA_BLOCKSIZE); buffer += SHA_BLOCKSIZE; count -= SHA_BLOCKSIZE; ShaTransform(sha_info); } memcpy(sha_info->data, buffer, count); sha_info->local = count; } /* finish computing the SHA digest */ void ShaFinal(unsigned char digest[20], SHA_INFO* sha_info) { int count; SHA_LONG lo_bit_count, hi_bit_count; lo_bit_count = sha_info->count_lo; hi_bit_count = sha_info->count_hi; count = (int) ((lo_bit_count >> 3) & 0x3f); ((SHA_BYTE *) sha_info->data)[count++] = 0x80; if (count > SHA_BLOCKSIZE - 8) { memset(((SHA_BYTE *) sha_info->data) + count, 0, SHA_BLOCKSIZE - count); ShaTransform(sha_info); memset((SHA_BYTE *) sha_info->data, 0, SHA_BLOCKSIZE - 8); } else { memset(((SHA_BYTE *) sha_info->data) + count, 0, SHA_BLOCKSIZE - 8 - count); } sha_info->data[56] = (unsigned char) ((hi_bit_count >> 24) & 0xff); sha_info->data[57] = (unsigned char) ((hi_bit_count >> 16) & 0xff); sha_info->data[58] = (unsigned char) ((hi_bit_count >> 8) & 0xff); sha_info->data[59] = (unsigned char) ((hi_bit_count >> 0) & 0xff); sha_info->data[60] = (unsigned char) ((lo_bit_count >> 24) & 0xff); sha_info->data[61] = (unsigned char) ((lo_bit_count >> 16) & 0xff); sha_info->data[62] = (unsigned char) ((lo_bit_count >> 8) & 0xff); sha_info->data[63] = (unsigned char) ((lo_bit_count >> 0) & 0xff); ShaTransform(sha_info); digest[ 0] = (unsigned char) ((sha_info->digest[0] >> 24) & 0xff); digest[ 1] = (unsigned char) ((sha_info->digest[0] >> 16) & 0xff); digest[ 2] = (unsigned char) ((sha_info->digest[0] >> 8) & 0xff); digest[ 3] = (unsigned char) ((sha_info->digest[0] ) & 0xff); digest[ 4] = (unsigned char) ((sha_info->digest[1] >> 24) & 0xff); digest[ 5] = (unsigned char) ((sha_info->digest[1] >> 16) & 0xff); digest[ 6] = (unsigned char) ((sha_info->digest[1] >> 8) & 0xff); digest[ 7] = (unsigned char) ((sha_info->digest[1] ) & 0xff); digest[ 8] = (unsigned char) ((sha_info->digest[2] >> 24) & 0xff); digest[ 9] = (unsigned char) ((sha_info->digest[2] >> 16) & 0xff); digest[10] = (unsigned char) ((sha_info->digest[2] >> 8) & 0xff); digest[11] = (unsigned char) ((sha_info->digest[2] ) & 0xff); digest[12] = (unsigned char) ((sha_info->digest[3] >> 24) & 0xff); digest[13] = (unsigned char) ((sha_info->digest[3] >> 16) & 0xff); digest[14] = (unsigned char) ((sha_info->digest[3] >> 8) & 0xff); digest[15] = (unsigned char) ((sha_info->digest[3] ) & 0xff); digest[16] = (unsigned char) ((sha_info->digest[4] >> 24) & 0xff); digest[17] = (unsigned char) ((sha_info->digest[4] >> 16) & 0xff); digest[18] = (unsigned char) ((sha_info->digest[4] >> 8) & 0xff); digest[19] = (unsigned char) ((sha_info->digest[4] ) & 0xff); } /* compute the SHA digest of a FILE stream */ void ShaOutput(unsigned char digest[20], unsigned char output[40]) { int i = 0; for(i = 0; i < 20; ++i) { sprintf((char *)(output + i * 2), "%02x", digest[i]); } } const char* ShaVersion(void) { #if(SHA_VERSION == 1) return "SHA-1"; #else return "SHA"; #endif } }
[ "sevenyou@tencent.com" ]
sevenyou@tencent.com
f5e28862a44276f83a6baabcfc51065e1813fcac
56fdc11a59fc43b28551a0f1350dad9d7361d60f
/tc/865-not.cpp
a0051ee42b89b726b977588d59c6fed9c0c49765
[]
no_license
glory2013/personal
1be2ac60e56384d961ea4b632428011c8d5e2297
1b9281cf02e345a1e33d65a4fbccda7e08f6f087
refs/heads/master
2016-09-05T23:06:48.382661
2013-06-29T10:54:40
2013-06-29T10:54:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,897
cpp
/* * ===================================================================================== * * Filename: srm570-250.cpp * Description: * Version: 1.0 * Created: 04/05/2013 06:37:14 PM * ===================================================================================== */ #include <iostream> #include <vector> using namespace std; class RobotHerb{ public: long long getdist(int times, vector<int> &steps){ long long dx = 0; long long dy = 0; int dir_one = 0; vector<pair<int, int> > dirs; dirs.push_back(pair<int, int>(0, 1)); dirs.push_back(pair<int, int>(1, 0)); dirs.push_back(pair<int, int>(0, -1)); dirs.push_back(pair<int, int>(-1, 0)); for (vector<int>::const_iterator it = steps.begin(); it != steps.end(); ++it){ dx += dirs[dir_one].first * *it; dy += dirs[dir_one].second * *it; dir_one = (dir_one + *it) % 4; } long long rx = 0; long long ry = 0; int srcdir = 0; // for (vector<pair<int, int> >::iterator it = dirs.begin(); it != dirs.end(); ++it){ int onedir = 0; for (; onedir < 4; ++onedir){ if ((dx % 2) == dirs[onedir].first && (dy % 2) == dirs[onedir].second){ break; } } for (int n = 0; n < times; ++n){ rx += dirs[(srcdir+onedir)&3].first * dx; ry += dirs[(srcdir+onedir)&3].second * dy; srcdir = (srcdir + dir_one) % 4; } return abs(rx) + abs(ry); } }; int main(){ RobotHerb r; vector<int> v; v.push_back(1); v.push_back(2); v.push_back(3); cout << r.getdist(1, v) << endl; return 0; }
[ "fengguangxi01@baidu.com" ]
fengguangxi01@baidu.com
290c784667d76e88197fd02a04c813df517ed276
c18f309136b2297f19433ed6f6c556a19b11efba
/Grid.hpp
b66ea68903f97c1ebb007ea0701a5390d4429e0a
[]
no_license
bpoore/game_of_life
89f812251db3f7eef35f1d51b239a8d38eaa0e32
6147e462c4a380d5fa63717697833eabd71ae58b
refs/heads/master
2021-01-01T04:12:48.921678
2016-04-29T02:20:29
2016-04-29T02:20:29
57,348,100
0
0
null
null
null
null
UTF-8
C++
false
false
830
hpp
/********************************************************************* ** Author: Elizabeth Poore ** Date: April 6, 2015 ** Description: Grid.hpp is the Grid class specification file *********************************************************************/ #ifndef GRID_HPP #define GRID_HPP #include "Point.hpp" // Grid class declaration const int HEIGHT = 40; // Size includes 10 ghost rows above and below the printed output const int WIDTH = 60; // Size includes 10 ghost columns to the left and right of the printed output const int OFFSET = 10; // Offset to account for ghost rows and columns class Grid { private: bool grid[HEIGHT][WIDTH]; public: Grid(); void fixed(Point point); void glider(Point point); void gliderGun(); void userDefined(int x, int y); void next(); void print(); void clear(); }; #endif
[ "beth.poore@gmail.com" ]
beth.poore@gmail.com
3bbd2d4c243e5f065df8f956a67dc5413a65fd67
d691acf949af6418d23bc57443fcac04a61664d4
/Source/NetworkShooter/GameObjects/WeaponSpawner.h
e455bfc9a534914f4985f9a0e808b93b66a17148
[]
no_license
NoCodeBugsFree/NetworkShooter
39a6284b3fc49501bc5e3ab210a807b4ad8becbd
225d07ed40cadebd46e3fce10a739951ccc60a6c
refs/heads/master
2021-07-08T10:03:06.377480
2020-07-19T03:24:47
2020-07-19T03:24:47
156,737,601
1
0
null
null
null
null
UTF-8
C++
false
false
1,577
h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "GameFramework/Actor.h" #include "WeaponSpawner.generated.h" UCLASS() class NETWORKSHOOTER_API AWeaponSpawner : public AActor { GENERATED_BODY() /* scene component */ UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Components", meta = (AllowPrivateAccess = "true")) class USceneComponent* Root; /** static mesh component */ UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Components", meta = (AllowPrivateAccess = "true")) class UStaticMeshComponent* ConeMesh; /* sphere collision */ UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Components", meta = (AllowPrivateAccess = "true")) class USphereComponent* SphereComponent; public: AWeaponSpawner(); virtual void NotifyActorBeginOverlap(AActor* OtherActor) override; protected: virtual void BeginPlay() override; private: /** called to spawn a weapon */ UFUNCTION(BlueprintCallable, Category = "AAA") void SpawnWeapon(); /** weapon class to spawn */ UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Config", meta = (AllowPrivateAccess = "true")) TSubclassOf<class AWeapon> WeaponClass; /** weapon respawn delay */ UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Config", meta = (AllowPrivateAccess = "true")) float RespawnDelay = 5.f; /** current (spawned) weapon reference */ UPROPERTY(BlueprintReadOnly, Category = "Config", meta = (AllowPrivateAccess = "true")) class AWeapon* CurrentWeapon; };
[ "NoCodeBugsFree@NOCODEBUGSFREE_" ]
NoCodeBugsFree@NOCODEBUGSFREE_
c09942350ac0a52d779c918dd8c867ec2771e1da
43a9f64427158c5bec8e9ce60233ba91b8c55f3e
/samples/TaskDialog/src/main.cpp
80d128fb9117d4984055daf48d365423cfa42b96
[]
no_license
CCCCCCCCZ/Win32xx
7e8647b74eaca47ef80cadd76d68dc036dabe709
2ef27b55e05931ebabf931f133387bc046f888dc
refs/heads/master
2020-06-07T13:29:41.006512
2019-06-22T07:33:53
2019-06-22T07:33:53
193,032,614
0
1
null
null
null
null
UTF-8
C++
false
false
470
cpp
#include "stdafx.h" #include "TaskDialogApp.h" int APIENTRY WinMain(HINSTANCE, HINSTANCE, LPSTR, int) { try { // Start Win32++ CTaskDialogApp theApp; // Run the application return theApp.Run(); } // catch all unhandled CException types catch (const CException &e) { // Display the exception and quit MessageBox(NULL, e.GetText(), AtoT(e.what()), MB_ICONERROR); return -1; } }
[ "czx_1991@qq.com" ]
czx_1991@qq.com
7dba9bae1315a6da343cebe20ed881791ec27d17
d0be9a869d4631c58d09ad538b0908554d204e1c
/utf8/lib/client/kernelengine/include/CGAL3.2.1/include/CGAL/Arr_point_location/Trapezoidal_decomposition_2.h
7eee283fe3f354cd2e08a34df08453101b54da6e
[]
no_license
World3D/pap
19ec5610393e429995f9e9b9eb8628fa597be80b
de797075062ba53037c1f68cd80ee6ab3ed55cbe
refs/heads/master
2021-05-27T08:53:38.964500
2014-07-24T08:10:40
2014-07-24T08:10:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
97,639
h
// Copyright (c) 1997 Tel-Aviv University (Israel). // All rights reserved. // // This file is part of CGAL (www.cgal.org); you may redistribute it under // the terms of the Q Public License version 1.0. // See the file LICENSE.QPL distributed with CGAL. // // 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/CGAL-3.2-branch/Arrangement_2/include/CGAL/Arr_point_location/Trapezoidal_decomposition_2.h $ // $Id: Trapezoidal_decomposition_2.h 31700 2006-06-20 08:42:35Z efif $ // // // Author(s) : Oren Nechushtan <theoren@math.tau.ac.il> // Iddo Hanniel <hanniel@math.tau.ac.il> #ifndef CGAL_TRAPEZOIDAL_DECOMPOSITION_2_H #define CGAL_TRAPEZOIDAL_DECOMPOSITION_2_H #include <CGAL/basic.h> #include <CGAL/Arr_point_location/Td_predicates.h> #include <CGAL/Arr_point_location/Trapezoidal_decomposition_2_misc.h> #include <cstdlib> #include <cstring> #include <iostream> #include <cmath> #include <ctime> #include <list> #include <vector> #include <map> CGAL_BEGIN_NAMESPACE #define CGAL_POINT_IS_LEFT_LOW(p,q) (traits->compare_xy_2_object()((p),(q))==SMALLER) #define CGAL_POINT_IS_RIGHT_TOP(p,q) (traits->compare_xy_2_object()((p),(q))==LARGER) /* ////////////////////////////////////////////////////////////////////////// class Trapezoidal_decomposition_2 parameters Traits,X_curve Description Implementation for a planar trapezoidal map also known as trapezoidal decomposition and vertical decomposition. For requirements on Traits and X_curve classes see Trapezoidal_decomposition_2 documentation. ////////////////////////////////////////////////////////////////////////// */ template < class Td_traits> class Trapezoidal_decomposition_2 { public: enum Locate_type {POINT=0,CURVE,TRAPEZOID,UNBOUNDED_TRAPEZOID=8} ; class Base_trapezoid_iterator; class In_face_iterator; friend class In_face_iterator; class Around_point_circulator; struct Unbounded {}; typedef Td_traits Traits; typedef const Traits& const_Traits_ref; typedef const Traits* const_Traits_ptr; typedef Trapezoidal_decomposition_2<Traits> Self; typedef const Self& const_Self_ref; typedef const Self* const_Self_ptr; typedef typename Traits::Point Point; typedef typename Traits::X_curve X_curve; typedef typename Traits::X_curve_ptr curve_pointer; typedef typename Traits::X_curve_ref curve_ref; typedef typename Traits::X_curve_const_ref curve_const_ref; typedef typename Traits::X_trapezoid X_trapezoid; typedef typename Traits::X_trapezoid_ptr pointer; typedef typename Traits::X_trapezoid_ref reference; typedef typename Traits::X_trapezoid_const_ref const_ref; typedef std::list<X_trapezoid> list_container; typedef std::vector<X_trapezoid> vector_container; typedef std::vector<X_curve> X_curve_container; typedef In_face_iterator Iterator; typedef class Base_trapezoid_iterator Base_trapezoid_circulator; // friend class Td_traits::X_trapezoid; typedef Td_active_trapezoid<X_trapezoid> Td_active_trapezoid; typedef Td_active_non_degenerate_trapezoid<X_trapezoid,Traits> Td_active_non_degenerate_trapezoid; typedef Td_active_right_degenerate_curve_trapezoid<X_trapezoid,Traits> Td_active_right_degenerate_curve_trapezoid; typedef Td_dag< X_trapezoid> Data_structure; typedef std::map<int,Data_structure> map_nodes; // typedef std::hash_map<const X_trapezoid*, X_trapezoid*> hash_map_tr_ptr; typedef Trapezoid_handle_less<const X_trapezoid* const> Trapezoid_ptr_less; typedef std::map<const X_trapezoid*, X_trapezoid*, Trapezoid_ptr_less> hash_map_tr_ptr; /* * class Base_trapezoid_iterator * member of Trapezoidal_decomposition_2<Traits> * Description Implements a basic Trapezoid iterator */ class Base_trapezoid_iterator { public: Base_trapezoid_iterator() : traits(0),curr(0) {}; Base_trapezoid_iterator(const_Traits_ptr traits_,pointer currt=0): traits(traits_),curr(currt) {} Base_trapezoid_iterator(const Base_trapezoid_iterator &it): traits(it.traits),curr(it.curr){;} Base_trapezoid_iterator & operator=(const Base_trapezoid_iterator &it) { traits=it.traits; curr=it.curr; return *this; } bool operator==(const Base_trapezoid_iterator &it) const { return (curr==it.curr ); } bool operator!=(const Base_trapezoid_iterator &it) const { return !operator==(it); } reference operator*() const { CGAL_precondition(curr); return *curr; } pointer operator->() const { return curr; } bool operator!() const { return curr==0; } protected: const_Traits_ptr traits; pointer curr; }; /* ********************************************************************* class In_face_iterator member of Trapezoidal_decomposition_2<Traits> Description Implements a Trapezoid iterator along a X_curve ********************************************************************* */ class In_face_iterator : public Base_trapezoid_iterator { #ifndef CGAL_CFG_USING_BASE_MEMBER_BUG_2 using Base_trapezoid_iterator::curr; using Base_trapezoid_iterator::traits; #endif protected: const X_curve& sep; public: In_face_iterator(const_Traits_ptr traits_,const X_curve& sepc,pointer currt=0) : Base_trapezoid_iterator(traits_,currt),sep(sepc){} In_face_iterator(const In_face_iterator &it) : Base_trapezoid_iterator((Base_trapezoid_iterator&)it),sep(it.sep){} bool operator==(const In_face_iterator &it) const { return ( Base_trapezoid_iterator::operator==(it) && traits->equal_2_object()(sep,it.sep) ); } /* destription: advances curr to one of the right neighbours according to the relation between the seperating X_curve and the right() trapezoid point. precoditions: sep doesn't intersect no existing edges except possibly on common end points. postconditions: if the rightest trapezoid was traversed curr is set to NULL. remark: if the seperator is vertical, using the precondition assumptions it follows that there is exactly one trapezoid to travel. */ In_face_iterator& operator++() { if (!curr) return *this;// end reached, do nothing! #ifndef CGAL_TD_DEBUG CGAL_warning(traits); #else CGAL_assertion(traits); #endif Point right(curr->right()); #ifdef CGAL_TD_DEBUG CGAL_assertion(curr->is_active()); CGAL_assertion(!traits->is_degenerate_point(*curr)); #endif if (!traits->is_degenerate(*curr)) { #ifndef NDEBUG #ifndef CGAL_TD_DEBUG CGAL_warning_code(Data_structure* tt=curr->get_node();) CGAL_warning(!tt->is_inner_node()); #else CGAL_assertion_code(Data_structure* tt=curr->get_node();) CGAL_assertion(tt); CGAL_assertion(!tt->is_inner_node()); #endif #endif // handle degeneracies if (!CGAL_POINT_IS_LEFT_LOW(curr->left(), traits->construct_max_vertex_2_object()(sep))) curr=0; else { switch(traits->compare_y_at_x_2_object()(right, sep)) { case SMALLER: curr = curr->right_top_neighbour(); break; case LARGER: curr = curr->right_bottom_neighbour(); break; case EQUAL: // end reached curr=0; break; default: curr=0; break; } } } else // pass along degenerate X_curve. { #ifndef NDEBUG #ifndef CGAL_TD_DEBUG CGAL_warning_code(Data_structure* tt=curr->get_node();) CGAL_warning(tt); CGAL_warning(tt->is_inner_node()); #else CGAL_assertion_code(Data_structure* tt=curr->get_node();) CGAL_assertion(tt); CGAL_assertion(tt->is_inner_node()); #endif #endif curr=curr->right_bottom_neighbour(); if (curr) { while(traits->is_degenerate_point(*curr)) curr=curr->get_node()->left().operator->(); #ifndef CGAL_TD_DEBUG CGAL_warning(traits->is_degenerate_curve(*curr)); #else CGAL_precondition(traits->is_degenerate_curve(*curr)); #endif } } return *this; } In_face_iterator operator++(int) { In_face_iterator tmp = *this; ++*this; return tmp; } const X_curve& seperator() { return sep; } }; /* * class Around_point_circulator * member of Trapezoidal_decomposition_2<Traits> * Description Implements a Trapezoid circulator around a point */ class Around_point_circulator : public Base_trapezoid_circulator { #ifndef CGAL_CFG_USING_BASE_MEMBER_BUG_2 using Base_trapezoid_circulator::curr; using Base_trapezoid_circulator::traits; #endif protected: const Point& fixed; public: #ifndef CGAL_CFG_USING_BASE_MEMBER_BUG_2 using Base_trapezoid_circulator::operator!; #endif Around_point_circulator(const_Traits_ptr traits_, const Point & fixedp, pointer currt) : Base_trapezoid_iterator(traits_,currt),fixed(fixedp) {}; Around_point_circulator(const Around_point_circulator &it) : Base_trapezoid_iterator(it),fixed(it.fixed){}; Around_point_circulator &operator++() { if (operator!()) return *this; #ifndef CGAL_TD_DEBUG CGAL_warning(!curr->is_left_unbounded() && traits->equal_2_object()(fixed,curr->left()) || !curr->is_right_unbounded() && traits->equal_2_object()(fixed,curr->right())); #else CGAL_precondition(!curr->is_left_unbounded() && traits->equal_2_object()(fixed,curr->left()) || !curr->is_right_unbounded() && traits->equal_2_object()(fixed,curr->right())); #endif curr=operator->(); return *this; } Around_point_circulator operator++(int) { Around_point_circulator tmp = *this; ++*this; return tmp; } pointer operator[](int i) const { Around_point_circulator c=*this; while(i-->0) c++; return c.curr; } /* returns reference to the next trapezoid on a clockwise orientation rotation with centre taken as the fixed point preconditions: ciruclator is not empty*/ reference operator*() const { CGAL_precondition(!operator!()); return *operator->(); } /* returns pointer to the next trapezoid on a clockwise orientation rotation with centre taken as the fixed point */ pointer operator->() const { pointer cand; if (operator!()) return curr; cand=is_right_rotation() ? curr->right_top_neighbour() : curr->left_bottom_neighbour(); if (traits->is_degenerate_curve(*cand)) return cand; // cand was splited by a point while(traits->is_degenerate_point(*cand)) cand=CGAL_POINT_IS_LEFT_LOW(cand->left(),fixed)? // move right using data structure cand->get_node()->right().operator->(): // move left using data structure cand->get_node()->left().operator->(); return cand; } bool is_valid() const { if ((!curr)|| (!curr->is_left_unbounded() && traits->equal_2_object()(fixed,curr->left())) || (!curr->is_right_unbounded() && traits->equal_2_object()(fixed,curr->right()))) { return true; } else { #ifdef CGAL_TD_DEBUG std::cerr << "\nthis="; write(std::cerr,*curr,*traits,false) << std::flush; std::cerr << "\nfixed=" << fixed << std::flush; CGAL_warning(!(curr && curr->is_left_unbounded() && curr->is_right_unbounded())); #endif return false; } } /* description: inserts the input trapezoid between the current trapezoid and the next trapezoid on a clockwise orientation rotation with centre taken as the fixed point. preconditions: current trapezoid exist input trapezoid is adjacent to fixed point */ void insert(reference tr) { #ifndef CGAL_TD_DEBUG CGAL_precondition(curr); CGAL_warning(!tr.is_left_unbounded() && traits->equal_2_object()(tr.left(), fixed) || !tr.is_right_unbounded()&& traits->equal_2_object()(tr.right(), fixed)); #else CGAL_precondition(curr); CGAL_precondition(!tr.is_left_unbounded() && traits->equal_2_object()(tr.left(),fixed) || !tr.is_right_unbounded() && traits->equal_2_object()(tr.right(),fixed)); #endif if (!tr.is_left_unbounded()&&traits->equal_2_object()(tr.left(),fixed)) tr.set_lb(operator->()); else tr.set_rt(operator->()); if (is_right_rotation()) curr->set_rt(&tr); else curr->set_lb(&tr); } /* precondition: curr!=NULL */ void remove() { #ifndef CGAL_TD_DEBUG CGAL_precondition(curr); CGAL_warning(!curr->is_left_unbounded() && traits->equal_2_object()(curr->left(), fixed) || !curr->is_right_unbounded() && traits->equal_2_object()(curr->right(), fixed)); #else CGAL_precondition(curr); CGAL_warning(!curr->is_left_unbounded() && traits->equal_2_object()(curr->left(),fixed) || !curr->is_right_unbounded() && traits->equal_2_object()(curr->right(),fixed)); #endif Around_point_circulator old=*this; old++; pointer next=old.operator->(); // handle 1-cycle and 2-cycles seperately if (curr!=next) { } // 2-cycle else if (*this!=old) { next=curr; } // 1-cycle else { if (is_right_rotation()) curr->set_rt(0); else curr->set_lb(0); curr=0; return; } if (is_right_rotation()) curr->set_rt(next); else curr->set_lb(next); if (old.is_right_rotation()) old[0]->set_rt(0); else old[0]->set_lb(0); } void replace(reference tr) { #ifndef CGAL_TD_DEBUG CGAL_precondition(curr); CGAL_warning(!curr->is_left_unbounded() && traits->equal_2_object()(curr->left(),fixed) || !curr->is_right_unbounded() && traits->equal_2_object()(curr->right(),fixed)); #else CGAL_precondition(curr); CGAL_precondition(!curr->is_left_unbounded() && traits->equal_2_object()(curr->left(),fixed) || !curr->is_right_unbounded() && traits->equal_2_object()(curr->right(),fixed)); #endif Around_point_circulator old=*this; old++; pointer next=old.operator->(); // handle 1-cycle and 2-cycles seperately if (curr!=next) { } // 2-cycle else if (*this!=old) { next=curr; } // 1-cycle else { curr=&tr; if (is_right_rotation()) curr->set_rt(curr); else curr->set_lb(curr); return; } if (!tr.is_right_unbounded()&&traits->equal_2_object()(tr.right(),fixed)) tr.set_rt(next); else tr.set_lb(next); if (is_right_rotation()) curr->set_rt(&tr); else curr->set_lb(&tr); } bool is_right_rotation() const { return !curr->is_right_unbounded() && traits->equal_2_object()(curr->right(),fixed); } const Point& fixed_point() const { return fixed; } }; ////////////////////////////////////////////// //Trapezoidal_decomposition_2 member functions: ////////////////////////////////////////////// #ifndef CGAL_TD_DEBUG protected: #else public: #endif /* input: X_curve, two Trapezoidal maps that corespond the the X_curve's source degenerate trapezoid and the X_curve's target degenerate trapezoid output: trapezoid iterator Description: the output (trapezoid iterator) is initialized with the leftmost and rightmost (non degenerate) trapezoids in the trapezoid interval that corresponds to the input from either the top side or the bottom side, depending on the up flag. preconditions: There exist non degenerate trapezoids between the roots of the input DS's */ In_face_iterator follow_curve(const Data_structure& left_end_point, const X_curve& cv, Comparison_result up) const { #ifndef CGAL_TD_DEBUG CGAL_warning(traits); CGAL_warning(traits->is_degenerate_point(*left_end_point)); if (!(traits->equal_2_object() (traits->construct_min_vertex_2_object()(cv), left_end_point->left()))) { CGAL_warning(traits->equal_2_object() (traits->construct_min_vertex_2_object()(cv), left_end_point->left())); } #else CGAL_assertion(traits); CGAL_precondition(traits->is_degenerate_point(*left_end_point)); CGAL_precondition(traits->equal_2_object() (traits->construct_min_vertex_2_object()(cv), left_end_point->left())); #endif const Point& p1=left_end_point->left(); Data_structure left=left_end_point.right(); search_using_data_structure(left,traits,p1,&cv,up); return In_face_iterator(traits,cv,left.operator->()); } /* input: X_trapezoid reference X_trapezoid pointer output: bool preconditions: the referenced trapezoid is to the right of the pointered trapezoid description: if the two input Trapezoids can be merged they are , with one copy destroyed(the right one). postconfition: The reference points to the right trapezoid The returned value is true iff merging took place. */ bool merge_if_possible(pointer left,pointer right) { if (left && right && traits->trapezoid_top_curve_equal(*left,*right) && traits->trapezoid_bottom_curve_equal(*left,*right) && traits->equal_2_object()(left->right(),right->left())) { left->merge_trapezoid(*right); #ifdef CGAL_TD_DEBUG CGAL_assertion(left->is_right_unbounded()==right->is_right_unbounded()); #endif return true; } return false; } /* Description: splits the trapezoid with vertical line through p */ /* Precondition: The trapezoid is active and contains p in its closure */ Data_structure& split_trapezoid_by_point( Data_structure& tt, const Point& p, const X_curve& cv_bottom_ray_shoot, const X_curve& cv_top_ray_shoot ) { #ifndef CGAL_TD_DEBUG CGAL_warning(!!tt); if (!tt) return tt; #else CGAL_precondition(!!tt); #endif reference curr=*tt; pointer lb=curr.left_bottom_neighbour(), lt=curr.left_top_neighbour(), rb=curr.right_bottom_neighbour(), rt=curr.right_top_neighbour(); #ifndef CGAL_TD_DEBUG CGAL_warning(curr.is_active()); CGAL_warning(traits->is_in_closure(curr,p)); #else CGAL_precondition(curr.is_active()); if (!traits->is_in_closure(curr,p)) { std::cout << "\ncurr="; write(std::cout,curr,*traits) << "\tp=" << p; } CGAL_precondition(traits->is_in_closure(curr,p)); #endif // left and right are set to the point itself, // bottom and top are set to the ray shooting resulting curves at this // stage. X_trapezoid sep(p,p,cv_bottom_ray_shoot,cv_top_ray_shoot); Data_structure leftDS = Data_structure(X_trapezoid(curr.left(), p, curr.bottom(), curr.top(), curr.boundedness() & (CGAL_TRAPEZOIDAL_DECOMPOSITION_2_LEFT_UNBOUNDED | CGAL_TRAPEZOIDAL_DECOMPOSITION_2_BOTTOM_UNBOUNDED | CGAL_TRAPEZOIDAL_DECOMPOSITION_2_TOP_UNBOUNDED) )); Data_structure rightDS=Data_structure(X_trapezoid(p, curr.right(), curr.bottom(),curr.top(), curr.boundedness()&(CGAL_TRAPEZOIDAL_DECOMPOSITION_2_RIGHT_UNBOUNDED | CGAL_TRAPEZOIDAL_DECOMPOSITION_2_BOTTOM_UNBOUNDED | CGAL_TRAPEZOIDAL_DECOMPOSITION_2_TOP_UNBOUNDED) )); reference left = *leftDS; reference right = *rightDS; #ifndef CGAL_TD_DEBUG CGAL_warning(traits->trapezoid_top_curve_equal(left,right)); CGAL_warning(traits->trapezoid_bottom_curve_equal(left,right)); CGAL_warning(left.is_left_unbounded()==curr.is_left_unbounded()); CGAL_warning(right.is_right_unbounded()==curr.is_right_unbounded()); #else CGAL_warning(traits->trapezoid_top_curve_equal(left,right)); CGAL_warning(traits->trapezoid_bottom_curve_equal(left,right)); CGAL_assertion(left.is_left_unbounded()==curr.is_left_unbounded()); CGAL_assertion(right.is_right_unbounded()==curr.is_right_unbounded()); #endif if (!traits->is_degenerate_curve(curr)) { left.init_neighbours(lb,lt,&right,&right); right.init_neighbours(&left,&left,rb,rt); if (lb) lb->set_rb(&left); if (lt) lt->set_rt(&left); if (rb) rb->set_lb(&right); if (rt) rt->set_lt(&right); } else { left.set_bottom(cv_bottom_ray_shoot); left.set_top(cv_bottom_ray_shoot); right.set_bottom(cv_top_ray_shoot); right.set_top(cv_top_ray_shoot); left.set_rt(&right); left.set_lb(lb); left.set_rb(0); right.set_lb(&left); right.set_rt(rt); right.set_rb(rb); } tt.replace(sep,leftDS,rightDS); const Data_structure *leftPtr=&tt.left(), *rightPtr=&tt.right(); (*leftPtr)->set_node((Data_structure*)leftPtr); (*rightPtr)->set_node((Data_structure*)rightPtr); #ifdef CGAL_TD_DEBUG CGAL_assertion(&left==leftDS.operator->()); CGAL_assertion(&right==rightDS.operator->()); CGAL_assertion(left==*leftDS); CGAL_assertion(right==*rightDS); CGAL_assertion(left==*tt.left()); CGAL_assertion(right==*tt.right()); /* CGAL_assertion(left.get_node()==&tt.left()); CGAL_assertion(right.get_node()==&tt.right()); */ CGAL_assertion(**left.get_node()==left); CGAL_assertion(**right.get_node()==right); #endif return tt; } /* Description: the opposite operation for spliting the trapezoid with vertical line through p */ /* Precondition: The root trapezoid is degenerate point (p) and is active */ void remove_split_trapezoid_by_point( Data_structure& tt, const Point& p) { #ifndef CGAL_TD_DEBUG if (!tt|| !tt->is_active()|| !traits->is_degenerate_point(*tt)|| !traits->equal_2_object()(tt->left(),p) ) { CGAL_warning(!!tt); CGAL_warning(tt->is_active()); CGAL_warning(traits->is_degenerate_point(*tt)); CGAL_warning(traits->equal_2_object()(tt->left(),p)); return; } #else CGAL_precondition(!!tt); CGAL_precondition(tt->is_active()); CGAL_precondition(traits->is_degenerate_point(*tt)); CGAL_precondition(traits->equal_2_object()(tt->left(),p)); #endif Data_structure tt_left=tt.left(), tt_right=tt.right(); search_using_data_structure(tt_left,traits,p,0); search_using_data_structure(tt_right,traits,p,0); #ifndef CGAL_TD_DEBUG merge_if_possible(&*tt_left,&*tt_right); CGAL_warning(!tt_left.is_inner_node()); CGAL_warning(!tt_right.is_inner_node()); CGAL_warning(tt_left->is_right_unbounded() == tt_right->is_right_unbounded()); #else std::cout << "\nremove_split_trapezoid_by_point(){"; std::cout << "\ntt_left="; write(std::cout,*tt_left,*traits); std::cout << "\ntt_right="; write(std::cout,*tt_right,*traits) << "}" << std::endl; bool merge_if_poss_left_right = merge_if_possible(&*tt_left,&*tt_right); std::cout << "\n->"; write(std::cout,*tt_left,*traits) << std::endl; CGAL_postcondition(merge_if_poss_left_right); CGAL_assertion(!tt_left.is_inner_node()); CGAL_assertion(!tt_right.is_inner_node()); CGAL_assertion(tt_left->is_right_unbounded() == tt_right->is_right_unbounded()); CGAL_assertion(**tt_left->get_node()==*tt_left); #endif tt_right->remove(&tt_left); // mark root as deleted tt->remove(); } /* Description: splits the trapezoid that corresponds to the root of the trapezoidal tree with an input edge cv*/ /* Precondition: The root trapezoid is active cv is non degenerate The root trapezoid is devided by cv or is equal to it and is vertical. */ Data_structure& split_trapezoid_by_curve( Data_structure& tt, pointer& prev, pointer& prev_bottom, pointer& prev_top, const X_curve& cv) { #ifndef CGAL_TD_DEBUG CGAL_warning(traits); #else CGAL_assertion(traits); #endif reference currt=*tt; //Point p[2]; //int i= CGAL_POINT_IS_LEFT_LOW( // p[0]=traits->curve_source(cv), // p[1]=traits->curve_target(cv) // ) ? 0 : 1; // //// sets left and right accoring to curves source's and target's positions //// sets bottom and top to X_curve itself //X_trapezoid sep(p[i],p[1-i],cv,cv); //IDIT: change this according to the new traits, we already know which //point is left and which is right X_trapezoid sep(traits->construct_min_vertex_2_object()(cv), traits->construct_max_vertex_2_object()(cv), cv, cv); /* creates a one-way path for all the X_curve-degenerate trapezoids that represent the X_curve. right_bottom_neighbour() is used to retrieve the next on path information */ Data_structure topBT = Data_structure(X_trapezoid(currt.left(), currt.right(), cv, currt.top(), currt.boundedness() & (CGAL_TRAPEZOIDAL_DECOMPOSITION_2_LEFT_UNBOUNDED | CGAL_TRAPEZOIDAL_DECOMPOSITION_2_RIGHT_UNBOUNDED| CGAL_TRAPEZOIDAL_DECOMPOSITION_2_TOP_UNBOUNDED))), bottomBT = Data_structure(X_trapezoid(currt.left(),currt.right(), currt.bottom(), cv, currt.boundedness() & (CGAL_TRAPEZOIDAL_DECOMPOSITION_2_LEFT_UNBOUNDED| CGAL_TRAPEZOIDAL_DECOMPOSITION_2_RIGHT_UNBOUNDED| CGAL_TRAPEZOIDAL_DECOMPOSITION_2_BOTTOM_UNBOUNDED))); reference bottom=*bottomBT; reference top=*topBT; top.init_neighbours(prev_top, currt.left_top_neighbour(), 0, currt.right_top_neighbour()); bottom.init_neighbours(currt.left_bottom_neighbour(), prev_bottom,currt.right_bottom_neighbour(),0); if (prev_bottom) prev_bottom->set_rt(&bottom); if (prev_top) prev_top->set_rb(&top); if (currt.left_bottom_neighbour()) currt.left_bottom_neighbour()->set_rb(&bottom); if (currt.left_top_neighbour()) currt.left_top_neighbour()->set_rt(&top); if (currt.right_bottom_neighbour()) currt.right_bottom_neighbour()->set_lb(&bottom); if (currt.right_top_neighbour()) currt.right_top_neighbour()->set_lt(&top); tt.replace(sep,bottomBT,topBT); const Data_structure *bottomPtr=&tt.left(), *topPtr=&tt.right(); (*bottomPtr)->set_node((Data_structure*)bottomPtr); (*topPtr)->set_node((Data_structure*)topPtr); if (prev) prev->set_rb(tt.operator->()); prev_bottom=(*bottomPtr).operator->(); prev_top=(*topPtr).operator->(); prev=tt.operator->(); return tt; } /* replace X_curve-point adjacency in the data structure with a new one precondition: the X_curve represented by t is top-right relative to the point represented by sep if and only if top=true */ void replace_curve_at_point_using_geometry(reference t, reference sep, bool cv_top_right=true) { Point p(sep.left()); X_curve cv(t.top()); Around_point_circulator circ(traits,p,cv_top_right ? sep.right_top_neighbour() : sep.left_bottom_neighbour()); if (circ.operator->()) { if (cv_top_right) while(traits->compare_cw_around_point_2_object () (circ->top(), cv, p) != EQUAL) circ++; else while(traits->compare_cw_around_point_2_object() (circ->bottom(), cv, p, false) != EQUAL) circ++; circ.replace(t); } } void insert_curve_at_point_using_geometry(reference sep, reference end_point) { #ifndef CGAL_TD_DEBUG CGAL_warning(traits); CGAL_warning(traits->is_degenerate_point(end_point)); CGAL_warning(traits->is_degenerate_curve(sep)); CGAL_warning(traits->equal_2_object()(end_point.left(),sep.right()) || traits->equal_2_object()(end_point.left(),sep.left())); #else CGAL_assertion(traits); CGAL_precondition(traits->is_degenerate_point(end_point)); CGAL_precondition(traits->is_degenerate_curve(sep)); CGAL_precondition(traits->equal_2_object()(end_point.left(),sep.right()) || traits->equal_2_object()(end_point.left(),sep.left())); #endif /* update (in this order) end_point.left_bottom_neighbour() if no curves adjacent to the point eminating toward up or right exist returns null, otherwise return the first X_curve sweeped using a counter clockwise sweep starting from up direction not including. end_point.right_top_neighbour() if no curves adjacent to the point eminating toward bottom or left exist returns null, otherwise return the first X_curve sweeped using a counter clockwise sweep starting from bottom direction not including. sep.right_top_neighbour() next clockwise degenerate_curve around rightmost end_point (possibly himself) sep.left_bottom_neighbour() next clockwise degenerate_curve around leftmost end_point (possibly himself) */ const X_curve& cv=sep.top(); const Point& p=end_point.left(); pointer rt = end_point.right_top_neighbour(), lb = end_point.left_bottom_neighbour(); if(!traits->equal_2_object()(end_point.left(),sep.right())) { if (!rt && !lb) // empty circulator { end_point.set_rt(&sep); sep.set_lb(&sep); } else { /* set circ[0] to first X_curve on a counter clockwise sweep starting at cv */ Around_point_circulator circ(traits,p,rt ? rt : lb),stopper=circ; // if !rt set circ to lb // otherwise advance as required #ifdef CGAL_TD_DEBUG Around_point_circulator first_circ(circ); #endif while (traits->compare_cw_around_point_2_object () (circ->top(), cv, p) == SMALLER) { circ++; if (circ==stopper) break; #ifdef CGAL_TD_DEBUG CGAL_assertion(first_circ!=circ); CGAL_assertion(circ->is_active()); #endif } #ifdef CGAL_TD_DEBUG CGAL_assertion(traits->compare_cw_around_point_2_object() (circ->top(), cv, p) != EQUAL); #endif circ.insert(sep); // set end_point.left_bottom_neighbour() // set end_point.right_top_neighbour(); if (lb) { Around_point_circulator lb_circ(traits,p,lb); if (!rt) end_point.set_rt(lb); if (lb_circ.operator->()==&sep) end_point.set_lb(&sep); } else { if (traits->compare_cw_around_point_2_object() (rt->top(), cv, p, false) == SMALLER) end_point.set_rt(&sep); } } } else { if (!rt && !lb) // empty circulator { end_point.set_lb(&sep); sep.set_rt(&sep); } else { /* set circ[0] to first X_curve on a counter clockwise sweep starting at cv */ Around_point_circulator circ(traits,p,lb ? lb : rt),stopper=circ; // if !lb set circ to rt // otherwise advance as required while (traits->compare_cw_around_point_2_object() (circ->top(), cv, p, false) == SMALLER) { circ++; if (circ==stopper) break; } #ifdef CGAL_TD_DEBUG CGAL_assertion(traits->compare_cw_around_point_2_object() (circ->top(), cv, p, false) != EQUAL); #endif circ.insert(sep); if (rt) // set end_point.left_bottom_neighbour() { Around_point_circulator rt_circ(traits,p,rt); if (!lb) end_point.set_lb(rt); if (rt_circ.operator->()==&sep) end_point.set_rt(&sep); } else { // set end_point.right_top_neighbour(); if(traits->compare_cw_around_point_2_object() (lb->top(), cv, p) ==SMALLER) end_point.set_lb(&sep); } } } } /* description: Update top(),bottom() for trapezoid Update rt,lb remarks: The point degenerate trapezoid representing a point p holds as its top and bottom curves the output for a vertical ray shoot quiries immidiately below the point toward up and immediately above the point toward down respectively. optimization: Each degenerate X_curve trapezoid eminating from the point p holds a pointer to the next trapezoid in a clockwise sweep around p(possibly to itself). This pointer is stored in rt or lb depending on the trapezoid is top right or bottom left of p. For the trapezoid representing p rt and lb hold the previous X_curve degenerate trapezoid in a clockwise sweep to the first top right and bottom left respectively. */ void remove_curve_at_point_using_geometry(const_ref sep,reference end_point) { #ifndef CGAL_TD_DEBUG CGAL_warning(traits); CGAL_warning(traits->is_degenerate_point(end_point)); CGAL_warning(traits->is_degenerate_curve(sep)); CGAL_warning(traits->equal_2_object()(end_point.left(),sep.right()) || traits->equal_2_object()(end_point.left(),sep.left())); CGAL_warning(end_point.is_active()); CGAL_warning(sep.is_active()); #else CGAL_assertion(traits); CGAL_precondition(traits->is_degenerate_point(end_point)); CGAL_precondition(traits->is_degenerate_curve(sep)); CGAL_precondition(traits->equal_2_object()(end_point.left(),sep.right()) || traits->equal_2_object()(end_point.left(),sep.left())); CGAL_precondition(end_point.is_active()); CGAL_precondition(sep.is_active()); #endif /* update (in this order) end_point.left_bottom_neighbour() if no curves adjacent to the point eminating toward up or right exist returns null, otherwise return the first X_curve sweeped using a counter clockwise sweep starting from up direction not including. end_point.right_top_neighbour() if no curves adjacent to the point eminating toward bottom or left exist returns null, otherwise return the first X_curve sweeped using a counter clockwise sweep starting from bottom direction not including. sep.right_top_neighbour() next clockwise degenerate_curve around rightmost end_point (possibly himself) sep.left_bottom_neighbour() next clockwise degenerate_curve around leftmost end_point (possibly himself) */ const X_curve& cv=sep.top(); const Point& p=end_point.left(); Around_point_circulator prev_top(traits,p,end_point.right_top_neighbour()), prev_bottom(traits,p,end_point.left_bottom_neighbour()); // update bottom if(traits->equal_2_object()(cv,end_point.bottom())) { Around_point_circulator bottom=(!!prev_bottom) ? prev_bottom : prev_top; bottom++; #ifdef CGAL_TD_DEBUG CGAL_assertion(!!bottom); #endif if (!bottom->is_bottom_unbounded()) end_point.set_bottom(bottom->bottom()); else end_point.set_bottom_unbounded(); } // update top if(traits->equal_2_object()(cv,end_point.top())) { Around_point_circulator top=(!!prev_top) ? prev_top : prev_bottom; top++; #ifdef CGAL_TD_DEBUG CGAL_assertion(!!top); #endif if (!top->is_top_unbounded()) end_point.set_top(top->top()); else end_point.set_top_unbounded(); } //update right top neighbour and left bottom neighbour bool b=CGAL_POINT_IS_LEFT_LOW(p,sep.right()); Around_point_circulator circ(traits,p,b ? end_point.right_top_neighbour() : end_point.left_bottom_neighbour()); #ifdef CGAL_TD_DEBUG CGAL_precondition(!!circ); #endif while(*circ!=sep)circ++; pointer removed=circ.operator->(); circ.remove(); if(!!circ) { pointer effective_curr=circ[0]; if (end_point.right_top_neighbour()==removed) end_point.set_rt(effective_curr); if (end_point.left_bottom_neighbour()==removed) end_point.set_lb(effective_curr); Around_point_circulator rt_circ(traits, p, end_point.right_top_neighbour()); if (!!rt_circ) { rt_circ++; if (rt_circ.is_right_rotation()) end_point.set_rt(0); } Around_point_circulator lb_circ(traits, p, end_point.left_bottom_neighbour()); if (!!lb_circ) { lb_circ++; if (!lb_circ.is_right_rotation()) end_point.set_lb(0); } } else { end_point.set_rt(0); end_point.set_lb(0); } } /*update tr.bottom() vertical_ray_shoot downward from tr tr.top() vertical_ray_shoot upward from tr */ reference insert_curve_at_point_using_geometry(const X_curve & cv, const Point& p, pointer & tr, const Locate_type & lt) { CGAL_assertion(traits); CGAL_precondition(lt==POINT); if (traits->compare_cw_around_point_2_object() (cv, tr->top(), p) == SMALLER) tr->set_top(cv); if (traits->compare_cw_around_point_2_object() (cv, tr->bottom(), p, false) == SMALLER) tr->set_bottom(cv); return *tr; } reference insert_curve_at_point_using_data_structure(const X_curve & cv, const Point & p, pointer & tr, const Locate_type & lt) { CGAL_precondition(lt==TRAPEZOID || lt==UNBOUNDED_TRAPEZOID); Data_structure *tt=tr->get_node(); #ifdef CGAL_TD_DEBUG CGAL_assertion(tr->get_node()); #endif return *split_trapezoid_by_point(*tt,p,cv,cv); //return *tr; } void replace_curve_at_point_using_geometry(const X_curve& old_cv, const X_curve& new_cv,reference sep) { #ifdef CGAL_TD_DEBUG CGAL_precondition(traits->is_degenerate_point(sep)); #endif if (!sep.is_top_unbounded() && traits->equal_2_object()(sep.top(), old_cv)) sep.set_top(new_cv); if (!sep.is_bottom_unbounded() && traits->equal_2_object()(sep.bottom(), old_cv)) sep.set_bottom(new_cv); } /* update geometric boundary(top and bottom) for trapezoids traveled along an iterator till end reached precondition: end==0 or end is on the path of the iterator postcondition: end is pointer to the last trapezoid encountered,if any */ void replace_curve_using_geometry(In_face_iterator & it, const X_curve & old_cv, const X_curve & new_cv,pointer & end) { pointer last=0; while (it.operator->()!=end) { if (!it->is_top_unbounded() && traits->equal_2_object()(it->top(),old_cv)) it->set_top(new_cv); if (!it->is_bottom_unbounded() && traits->equal_2_object()(it->bottom(),old_cv)) it->set_bottom(new_cv); last=it.operator->(); ++it; } end=last; } /* description: advances input Data structure using data structure,input point p and possibly X_curve cv till p is found(if cv hadn't been given) cv is found(if cv was given) or leaf node reached postcondition: output is the closest active trapezoid to p/cv remark: use this function with care! */ /*static */ Locate_type search_using_data_structure(Data_structure& curr,const_Traits_ptr traits, const Point& p,const X_curve* cv, Comparison_result up = EQUAL) const { const Point* pp; const X_curve* pc; #ifdef CGAL_TD_DEBUG pointer old = NULL; #endif while(true) { #ifdef CGAL_TD_DEBUG // unbounded loop CGAL_assertion(curr.operator->() != old); old = curr.operator->(); #endif if (traits->is_degenerate_point(*curr)) // point node conditional (separation) { // extract point from trapezoid pp = &curr->left(); if (CGAL_POINT_IS_LEFT_LOW(p, *pp)) { curr = curr.left(); continue; } else if (CGAL_POINT_IS_LEFT_LOW(*pp, p)) { curr = curr.right(); continue; } else if (traits->equal_2_object()(*pp, p)) { if (!cv) { if ( up == EQUAL ) { // point found! if (curr->is_active()) return POINT; curr = curr.left(); } else if ( up == LARGER ) { // vertical ray shut up curr = curr.right(); } else /*if ( up == SMALLER ) */ { curr = curr.left(); // vertical ray shut down } continue; } else { #ifndef CGAL_TD_DEBUG CGAL_warning( traits->equal_2_object() (traits->construct_min_vertex_2_object()(*cv), p) || traits->equal_2_object() (traits->construct_max_vertex_2_object()(*cv), p)); #else CGAL_assertion( traits->equal_2_object() (traits->construct_min_vertex_2_object()(*cv), p) || traits->equal_2_object() (traits->construct_max_vertex_2_object()(*cv), p)); #endif curr = traits->equal_2_object() (traits->construct_min_vertex_2_object()(*cv), p) ? curr.right() : curr.left(); // (Oren 14/4/02) ?? continue; } } else { #ifndef CGAL_TD_DEBUG CGAL_warning(CGAL_POINT_IS_LEFT_LOW(p,*pp) || CGAL_POINT_IS_LEFT_LOW(*pp,p) || traits->equal_2_object()(*pp,p)); #else CGAL_assertion(CGAL_POINT_IS_LEFT_LOW(p,*pp) || CGAL_POINT_IS_LEFT_LOW(*pp,p) || traits->equal_2_object()(*pp,p)); #endif return Locate_type(); } } if (traits->is_degenerate_curve(*curr)) { // CURVE SEPRATION pc = &curr->top(); Comparison_result cres = traits->compare_y_at_x_2_object()(p, *pc); if (cres == SMALLER) { curr = curr.left(); continue; } else if (cres == LARGER) { curr = curr.right(); continue; } else { // p on CURVE #ifndef CGAL_TD_DEBUG CGAL_warning(cres == EQUAL && ! (traits->compare_x_2_object()(p, traits->construct_max_vertex_2_object()(*pc)) == LARGER )&& ! ( traits->compare_x_2_object()(p, traits->construct_min_vertex_2_object()(*pc)) == SMALLER )); #else CGAL_postcondition(cres == EQUAL && ! (traits->compare_x_2_object()(p, traits->construct_max_vertex_2_object()(*pc)) == LARGER )&& ! (traits->compare_x_2_object()(p, traits->construct_min_vertex_2_object()(*pc)) == SMALLER ) ); #endif if (!cv) { // For a vertical curve, we always visit it after visiting // one of its endpoints. if ((up == EQUAL) || traits->is_vertical(*curr)) { //std::cout << "EQUAL or VERTICAL" << std::endl; if (curr->is_active()) return CURVE; curr = curr.left(); } else if (up == LARGER) { curr = curr.right(); } else /* if (up==SMALLER) */ { curr = curr.left(); } continue; } else { #ifndef CGAL_TD_DEBUG CGAL_warning(traits->equal_2_object() (traits->construct_min_vertex_2_object()(*cv), traits->construct_min_vertex_2_object()(*pc)) || traits->equal_2_object() (traits->construct_max_vertex_2_object()(*cv), traits->construct_max_vertex_2_object()(*pc))); #else if (!(traits->equal_2_object() (traits->construct_min_vertex_2_object()(*cv), traits->construct_min_vertex_2_object()(*pc))|| traits->equal_2_object() (traits->construct_max_vertex_2_object()(*cv), traits->construct_max_vertex_2_object()(*pc)))) { std::cerr << "\npc " << *pc; std::cerr << "\ncv " << *cv << std::endl; CGAL_assertion(traits->equal_2_object() (traits->construct_min_vertex_2_object()(*cv), traits->construct_min_vertex_2_object()(*pc)) || traits->equal_2_object() (traits->construct_max_vertex_2_object()(*cv), traits->construct_max_vertex_2_object()(*pc))); } #endif Comparison_result res = traits->equal_2_object() (traits->construct_min_vertex_2_object()(*cv), traits->construct_min_vertex_2_object()(*pc)) ? traits->compare_cw_around_point_2_object() (*pc, *cv, p) : traits->compare_cw_around_point_2_object() (*cv, *pc, p ,false); switch(res) { case LARGER: curr = curr.right(); break; case SMALLER: curr = curr.left(); break; case EQUAL: switch(up) { case LARGER: curr = curr.right(); break; case SMALLER: curr = curr.left(); break; case EQUAL: if (curr->is_active()) return CURVE; curr = curr.left(); break; #ifdef CGAL_TD_DEBUG default: CGAL_assertion(up==LARGER||up==SMALLER||up==EQUAL); return Locate_type(); #endif } break; #ifdef CGAL_TD_DEBUG default: CGAL_assertion(res == LARGER || res == SMALLER || res == EQUAL); return Locate_type(); #endif } } } } else { // !is_degenerate() if (curr->is_active()) return curr->is_unbounded() ? UNBOUNDED_TRAPEZOID : TRAPEZOID; curr = curr.left(); continue; } } } Data_structure container2data_structure(map_nodes& ar, int left, int right) const { #ifndef CGAL_TD_DEBUG CGAL_warning(traits); #else CGAL_assertion(traits); #endif if (right>left) { int d=(int)CGAL_CLIB_STD::floor((double(right+left))/2); // Replacing operator [] of map with find to please MSVC 7 Point p = (ar.find(d)->second)->right(); //Point p=ar[d]->right(); Data_structure curr= Data_structure( X_trapezoid(&p,&p,0,0), container2data_structure(ar,left,d), container2data_structure(ar,d+1,right) ); curr.left()->set_node((Data_structure*)&curr.left()); curr.right()->set_node((Data_structure*)&curr.right()); curr->set_node(&curr);// fake temporary node curr->remove(); // mark as deleted curr->set_node(0); return curr; } else // Replacing operator [] of map with find to please MSVC 7 return ar.find(left)->second; //return ar[left]; } /*============================================== Trapezoidal_decomposition_2 public member functions ==============================================*/ public: Trapezoidal_decomposition_2(bool rebuild=true) : depth_threshold(CGAL_TD_DEFAULT_DEPTH_THRESHOLD), size_threshold(CGAL_TD_DEFAULT_SIZE_THRESHOLD) {init();set_needs_update(rebuild);} Trapezoidal_decomposition_2(const double& depth_th,const double& size_th) : depth_threshold(depth_th),size_threshold(size_th) {init();set_needs_update(rebuild);} Trapezoidal_decomposition_2(const_Self_ref td) : needs_update_(td.needs_update_), number_of_curves_(td.number_of_curves_), traits(td.traits), last_cv(NULL), prev_cv(NULL), depth_threshold(td.depth_threshold), size_threshold(td.size_threshold) { hash_map_tr_ptr htr; /*! \todo allocate hash_map size according to content. * \todo change vector<> to in_place_list and pointer hash to trapezoidal * hash.. */ vector_container vtr; int sz; Td_active_trapezoid pr; sz=X_trapezoid_filter(vtr, &td.get_data_structure()); //! \todo Reduce the 3 iterations to 1 (or 2) iterator. // First iteration: filter out the active trapezoids. typename vector_container::const_iterator it; for (it=vtr.begin(); it!=vtr.end(); ++it) { Data_structure* ds_copy=new Data_structure(*it); const X_trapezoid* cur=&*it; X_trapezoid* tr_copy=&*(*ds_copy); tr_copy->set_node(ds_copy); CGAL_assertion(&*(*tr_copy->get_node())==tr_copy); ds_copy->set_depth(cur->get_node()->depth()); // We cheat a little with the depth. htr.insert(typename hash_map_tr_ptr::value_type(cur, tr_copy)); // Second iteration: generate new copies of trapezoids and nodes. } for (it=vtr.begin(); it!=vtr.end(); ++it) { const X_trapezoid* cur=&*it; X_trapezoid* tr_copy=htr.find(cur)->second; const Data_structure *child; CGAL_assertion(tr_copy); tr_copy->set_rt(cur->get_rt() ? htr.find(cur->get_rt())->second : NULL); tr_copy->set_rb(cur->get_rb() ? htr.find(cur->get_rb())->second : NULL); tr_copy->set_lt(cur->get_lt() ? htr.find(cur->get_lt())->second : NULL); tr_copy->set_lb(cur->get_lb() ? htr.find(cur->get_lb())->second : NULL); if (cur->get_node()->is_inner_node()) { child=&cur->get_node()->right(); while (child && child->is_inner_node() && !pr(*(*child))) child=&child->left(); tr_copy->get_node()->set_right(*child); child=&cur->get_node()->left(); while (child && child->is_inner_node() && !pr(*(*child))) child=&child->left(); tr_copy->get_node()->set_left(*child); } // Third iteration: generate links in-between trapezoids // and in-between nodes . } DS=htr.find(&*(*td.DS))->second->get_node(); } /* TODO: Should we add another constructor with non const argument that rebuild the trapezoidal decomposition prior to copy construction? */ virtual ~Trapezoidal_decomposition_2() { #ifndef CGAL_TD_DEBUG CGAL_warning(DS); if (!DS) return; #else CGAL_assertion(DS); #endif delete DS; } /* Input: X_curve Output: if X_curve or twin already inserted the latter is returned. otherwise the left-low most edge-degenerate trapezoid that represents the input X_curve is returned Remark: Given an edge-degenerate trapezoid representing a X_curve, all the other trapezoids representing the X_curve can be extracted via moving continously to the left and right neighbours. */ X_trapezoid insert(curve_const_ref cv) { #ifdef CGAL_TD_DEBUG *cv.get_parent(); #endif /* Point tmp; // maintaining some bounding box for future use. if (!number_of_curves_) // give initiale values to bounding points when empty { POINT_AT_LEFT_TOP_INFINITY=POINT_AT_RIGHT_BOTTOM_INFINITY= traits->curve_source(cv); } if (!CGAL_POINT_IS_LEFT_LOW(POINT_AT_LEFT_TOP_INFINITY,tmp= traits->construct_min_vertex_2_object()(cv))) POINT_AT_LEFT_TOP_INFINITY=traits->point_to_left(tmp); if (!traits->point_is_right_top(POINT_AT_RIGHT_BOTTOM_INFINITY,tmp= traits->construct_max_vertex_2_object()(cv))) POINT_AT_RIGHT_BOTTOM_INFINITY=traits->point_to_right(tmp); */ return insert_in_face_interior(cv); } /* Input: X_curve Output: if X_curve or twin already inserted the latter is returned. otherwise the left-low most edge-degenerate trapezoid that represents the input X_curve is returned Remark: Given an edge-degenerate trapezoid representing a X_curve, all the other trapezoids representing the X_curve can be extracted via moving continously to the left and right neighbours. */ const X_trapezoid insert_in_face_interior(curve_const_ref cv) { #ifdef CGAL_TD_DEBUG *cv.get_parent(); #endif #ifdef CGAL_TDBB_DEBUG std::cout << "\ninsert_in_face_interior(" << cv << ")" << "\nBbox " << traits->get_bounding_box(); #endif #ifdef CGAL_TD_DEBUG std::cout << "\nTD::insert_in_face_interior(" << cv << ") called with " << (is_valid(*DS) ? "valid" : "invalid") << " data structure" << std::endl; write(std::cout,*DS,*traits) << std::endl; #endif if (needs_update_) update(); // locate the input X_curve end points in the X_trapezoid Dag CGAL_assertion(traits); #ifndef CGAL_TD_DEBUG CGAL_warning(!traits->equal_2_object() (traits->construct_min_vertex_2_object()(cv), traits->construct_max_vertex_2_object()(cv))); #else CGAL_precondition(!traits->equal_2_object() (traits->construct_min_vertex_2_object()(cv), traits->construct_max_vertex_2_object()(cv))); #endif //Point p[2]; //int i= CGAL_POINT_IS_LEFT_LOW( // p[0]=traits->curve_source(cv), // p[1]=traits->curve_target(cv) // ) ? 0 : 1; //IDIT: change this according to the new traits, we already know which //point is left and which is right Point p[2]; p[0] = traits->construct_min_vertex_2_object()(cv); p[1] = traits->construct_max_vertex_2_object()(cv); int i = 0; // Locate_type lt1,lt2; pointer tr1,tr2; #ifndef CGAL_NO_TRAPEZOIDAL_DECOMPOSITION_2_OPTIMIZATION locate_optimization(p[i],tr1,lt1); #else //location of the left endpoint of the curve we're inserting tr1=&locate(traits->construct_min_vertex_2_object(),lt1); #endif //the inserted curve should not cut any existing curve if (lt1==CURVE) { CGAL_precondition_msg(lt1!=CURVE,"Input is not planar as\ one of the input point inside previously inserted X_curve."); return X_trapezoid(); } //if the curve starts at vertex, we should not insert it into the DAG, //but we should update all the curves incident to the vertex. //else if this is a new vertex- insert a node to the DAG that will represent the new vertex. //the incident curves in this case is only the curve itself, and so it is a trivial operation. reference t_p1= (lt1==POINT) ? insert_curve_at_point_using_geometry(cv,p[i],tr1,lt1) : insert_curve_at_point_using_data_structure(cv,p[i],tr1,lt1); #ifndef CGAL_NO_TRAPEZOIDAL_DECOMPOSITION_2_OPTIMIZATION locate_optimization(p[1-i],tr2,lt2); locate_opt_empty(); #else //TODO(oren): locating the second endpoint. this is not necessary, and time consuming. tr2=&locate(p[1-i],lt2); #endif if (lt2==CURVE) { CGAL_precondition_msg(lt2!=CURVE,"Input is not planar as\ one of the input point inside previously inserted X_curve."); return X_trapezoid(); } reference t_p2= (lt2==POINT) ? insert_curve_at_point_using_geometry(cv,p[1-i],tr2,lt2) : insert_curve_at_point_using_data_structure(cv,p[1-i],tr2,lt2); // locate and insert end points of the input X_curve to the X_trapezoid // Dag if needed Data_structure tt_p1(*t_p1.get_node()); Data_structure tt_p2(*t_p2.get_node()); // create the X_trapezoid iterator for traveling along the Trapezoids that // intersect the input X_curve, using left-low to right-high order In_face_iterator it=follow_curve(tt_p1,cv,LARGER); pointer curr,prev=&t_p1,prev_bottom,prev_top; pointer old_output = it.operator->(), old_top = 0, old_bottom = 0; #ifndef CGAL_TD_DEBUG CGAL_warning(!traits->is_degenerate(*old_output)); #else CGAL_assertion(!traits->is_degenerate(*old_output)); #endif old_output=0; Data_structure *tt; bool first_time=true; while(!!it) //this means as long as the iterator is valid { curr=it.operator->(); prev_bottom=curr->left_bottom_neighbour(); prev_top=curr->left_top_neighbour(); // pass using it along cv it++; //this is the logic of the iterator. the iterator goes to the next trapezoid right-high. tt = curr->get_node(); if(first_time) { #ifndef CGAL_TD_DEBUG if(!curr->is_top_unbounded()&&traits->equal_2_object()(curr->top(),cv)) { CGAL_warning(!traits->equal_2_object()(curr->top(),cv)); return X_trapezoid(); } #else CGAL_precondition(curr->is_top_unbounded()|| !traits->equal_2_object()(curr->top(),cv)); #endif } split_trapezoid_by_curve(*tt,old_output, old_bottom, old_top, cv); #ifdef CGAL_TD_DEBUG CGAL_assertion(traits->equal_2_object()((**tt).top(),cv)); #endif if(first_time) { insert_curve_at_point_using_geometry(*old_output,t_p1); first_time=false; } if (tt->is_inner_node()) { // merge adjacent trapezoids on input X_curve's bottom side if possible if(merge_if_possible( prev_bottom, tt->left().operator->() )) { tt->set_left(*(prev_bottom->get_node())); old_bottom = prev_bottom; } // merge adjacent trapezoids on input X_curve's top side if possible if(merge_if_possible( prev_top, tt->right().operator->() )) { tt->set_right(*(prev_top->get_node())); old_top=prev_top; } // update trapezoid's left/right neighbouring relations if(!traits->is_degenerate(*prev) && !traits->is_degenerate(*curr)) { curr->set_lb(prev); curr->set_lt(prev); prev->set_rb(curr); prev->set_rt(curr); } } else { #ifdef CGAL_TD_DEBUG CGAL_assertion(curr->is_valid(traits)); #endif break; } #ifdef CGAL_TD_DEBUG CGAL_assertion(curr->is_valid(traits)); #endif } #ifdef CGAL_TD_DEBUG CGAL_postcondition(traits->is_degenerate_curve(*old_output)); CGAL_postcondition(traits->equal_2_object()((const X_curve)old_output->top(), cv)); #endif insert_curve_at_point_using_geometry(*old_output,t_p2); number_of_curves_++; #ifdef CGAL_TD_DEBUG write(std::cout,*DS,*traits) << std::endl; std::cout << "\nTD::insert_in_face_interior() exited with data structure" << is_valid(*DS) << std::endl; #endif return *old_output; } // removal functions void remove(curve_const_ref cv) // We assume here that the input curves are in planar position. { remove_in_face_interior(cv); } template <class curve_iterator> void remove(curve_iterator begin, curve_iterator end) { if(begin == end) return; std::random_shuffle(begin,end); curve_iterator it=begin,next=it; while(it!=end) {++next;remove(*it);it=next;} } void clear() { delete DS; init(); } void remove_in_face_interior(curve_const_ref cv) // Assumes the map to be planar. { #ifdef CGAL_TD_DEBUG std::cout << "\nTD::remove_in_face_interior(" << cv << ") called with " << (is_valid(*DS) ? "valid" : "invalid") << " data structure" << std::endl; write(std::cout,*DS,*traits) << std::endl; #endif if (needs_update_) update(); #ifndef CGAL_NO_TRAPEZOIDAL_DECOMPOSITION_2_OPTIMIZATION locate_opt_empty(); #endif #ifndef CGAL_TD_DEBUG CGAL_warning(traits); #else CGAL_assertion(traits); #endif // calculating leftmost and rightmost points of X_curve cv Point leftmost=traits->construct_min_vertex_2_object()(cv), rightmost=traits->construct_max_vertex_2_object()(cv); Locate_type lt1,lt2; reference t1=locate(leftmost,lt1), t2=locate(rightmost,lt2); CGAL_warning(lt1==POINT && lt2==POINT); if (!(lt1==POINT && lt2==POINT)) return; #ifndef CGAL_TD_DEBUG CGAL_warning(t1.get_node()); CGAL_warning(t2.get_node()); #endif Data_structure &tt1=*t1.get_node(), &tt2=*t2.get_node(); /* calculate the immediate lower central and upper neighbourhood of the curve in the data structure */ In_face_iterator bottom_it(follow_curve(tt1,cv,SMALLER)), mid_it(follow_curve(tt1,cv,EQUAL)), top_it(follow_curve(tt1,cv,LARGER)); bool bottom, old_bottom = false, end_reached; map_nodes new_array; int last_index[]={0,0}; int sz=0; Point left=bottom_it->left(),right; pointer last_bottom,last_top,last=0,old; #ifndef CGAL_TD_DEBUG CGAL_warning(traits->equal_2_object()(top_it->left(),left)); #else CGAL_precondition(traits->equal_2_object()(top_it->left(),left)); #endif // remove adjacency at left end point const_ref first=*mid_it; //X_curve const * old_cv=&first.top(); #ifdef CGAL_TD_DEBUG CGAL_assertion(traits->equal_2_object()(first.top(),cv)); CGAL_assertion(traits->equal_2_object()(t1.left(),leftmost)); #endif remove_curve_at_point_using_geometry(first,t1); do { // which of bottom_it,top_it to advance. bottom=CGAL_POINT_IS_LEFT_LOW(bottom_it->right(),top_it->right()); Iterator& it = bottom ? bottom_it : top_it; pointer& last_it = bottom ? last_bottom : last_top; right=it->right(); // copy trapezoid's content and node pointer. typename map_nodes::value_type pair(sz, Data_structure( X_trapezoid(&left,&right, !bottom_it->is_bottom_unbounded() ? &bottom_it->bottom() : 0, !top_it->is_top_unbounded() ? &top_it->top() : 0))); new_array.insert(pair); Data_structure & curr = (new_array.find(sz))->second; ++sz; curr->set_node(&curr); curr->set_lb(bottom_it->left_bottom_neighbour()); curr->set_lt(top_it->left_top_neighbour()); if (last) { if (traits->trapezoid_top_curve_equal(*last,*curr)) { curr->set_lt(last); } if (traits->trapezoid_bottom_curve_equal(*last,*curr)) { curr->set_lb(last); } } if (curr->left_bottom_neighbour()) curr->left_bottom_neighbour()->set_rb(curr.operator->()); if (curr->left_top_neighbour()) curr->left_top_neighbour()->set_rt(curr.operator->()); last=curr.operator->(); left=right; last_bottom=bottom_it.operator->(); last_top=top_it.operator->(); #ifdef CGAL_TD_DEBUG CGAL_warning(last_bottom); CGAL_warning(last_top); #endif old=it.operator->(); it++; end_reached=!bottom_it||!top_it; if (!bottom_it || bottom && !traits->trapezoid_bottom_curve_equal(*old,*it)) { pointer rb=old->right_bottom_neighbour(); if (rb) {rb->set_lb(last);last->set_rb(rb);} } if (!top_it || !bottom && !traits->trapezoid_top_curve_equal(*old,*it)) { pointer rt=old->right_top_neighbour(); if (rt) {rt->set_lt(last);last->set_rt(rt);} } #ifdef CGAL_TD_DEBUG CGAL_assertion(last->get_node()); #endif if (old_bottom != bottom) { Data_structure tmp=container2data_structure( new_array,last_index[bottom ? 0 : 1],sz-1); #ifdef CGAL_TD_DEBUG std::cout << "\nremove_in_face_interior allocated "; write(std::cout,tmp,*traits) << "\ninto "; write(std::cout,*last_it,*traits,false) << std::endl; #endif last_it->remove(&tmp); last_index[bottom ? 0 : 1] = sz; old_bottom = bottom; } else { Data_structure tmp=container2data_structure(new_array,sz-1,sz-1); #ifdef CGAL_TD_DEBUG std::cout << "\nremove_in_face_interior allocated "; write(std::cout,tmp,*traits) << "\ninto "; write(std::cout,*last_it,*traits,false) << std::endl; #endif last_it->remove(&tmp); last_index[bottom ? 0 : 1] = sz; } const Data_structure *real=&last_it->get_node()->left(); (*real)->set_node((Data_structure*)real); } while(!end_reached); Iterator & it = !old_bottom ? bottom_it : top_it; #ifdef CGAL_TD_DEBUG CGAL_warning(traits->equal_2_object()(it->right(),rightmost)); #endif pointer rb=it->right_bottom_neighbour(),rt=it->right_top_neighbour(); Data_structure tmp=container2data_structure(new_array, last_index[!bottom ? 0 : 1],new_array.size()-1); #ifdef CGAL_TD_DEBUG std::cout << "\nremove_in_face_interior allocated "; write(std::cout,tmp,*traits) << "\ninto "; write(std::cout,*it,*traits,false) << std::endl; #endif it->remove(&tmp); const Data_structure *real=&it->get_node()->left(); (*real)->set_node((Data_structure*)real); if (rb) {last->set_rb(rb);rb->set_lb(last);} if (rt) {last->set_rt(rt);rt->set_lt(last);} Base_trapezoid_iterator last_mid=mid_it; while(!!++mid_it) { #ifdef CGAL_TD_DEBUG CGAL_warning(traits->is_degenerate_curve(*last_mid)); #endif last_mid->remove(); last_mid=mid_it; } // remove adjacency at right end point #ifdef CGAL_TD_DEBUG CGAL_assertion(traits->equal_2_object()(cv,last_mid->top())); CGAL_assertion(traits->equal_2_object()(rightmost,t2.left())); #endif remove_curve_at_point_using_geometry(*last_mid,t2); last_mid->remove(); if (is_isolated_point(t1)) remove_split_trapezoid_by_point(tt1,leftmost); if (is_isolated_point(t2)) remove_split_trapezoid_by_point(tt2,rightmost); //freeing memory thasht was allocated for X_curve //delete old_cv; // reevaluating number of curves number_of_curves_--; #ifdef CGAL_TD_DEBUG std::cout << "\nTD::remove_in_face_interior() exited with data structure" << is_valid(*DS) << std::endl; write(std::cout,*DS,*traits) << std::endl; #endif } /* output: The active trapezoid representing the input point. preconditions: The trapezoidal tree is not empty postcondition: the input locate type is set to the type of the output trapezoid. remarks: locate call may change the class */ reference locate(const Point& p,Locate_type &t) const { #ifdef CGAL_TD_DEBUG CGAL_assertion(traits); CGAL_assertion(DS); #endif Data_structure curr=*DS; #ifdef CGAL_TD_DEBUG CGAL_precondition(!!curr); #endif //the actual locate. curr is the DAG root, the traits, //the point to location, and 0 - indicates point location t=search_using_data_structure(curr,traits,p,0); #ifdef CGAL_TD_DEBUG CGAL_postcondition(t == POINT || t == CURVE || t == TRAPEZOID || t == UNBOUNDED_TRAPEZOID); #endif #ifndef CGAL_NO_TRAPEZOIDAL_DECOMPOSITION_2_OPTIMIZATION locate_opt_push(curr.operator->()); #endif return *curr; } /* preconditions: p is not on an edge or a vertex. */ curve_const_ref vertical_ray_shoot(const Point & p,Locate_type & t, const bool up_direction = true) const { #ifdef CGAL_TD_DEBUG CGAL_assertion(traits); #endif // We replace the following locate with a direct call to // search_using_data_structure because we need to deal // with cases where the source of shoot is a point/curve. // reference t_p = locate(p,t); Data_structure curr=*DS; #ifdef CGAL_TD_DEBUG CGAL_precondition(!!curr); #endif t = search_using_data_structure(curr, traits, p, NULL, up_direction ? CGAL::LARGER : CGAL::SMALLER); reference t_p = *curr; //std::cout << "t" << t << "\n"; #ifdef CGAL_TD_DEBUG CGAL_warning(t_p.get_node()); #endif reference tr = **t_p.get_node(); // std::cout << "tr" << tr << "\n"; // tr should be non degenerate trapezoid /* using exact traits, it may happen that p is on the right side of the trapezoid directly under its right point(analogouly directly above its left point). with the trapezoid extending to the left. In this case vertical ray shoot upwards(downwards) doesn't returns c as output. Example. x---x p x------x */ if (up_direction && !tr.is_right_unbounded() && (traits->compare_x_2_object()(p,tr.right()) == EQUAL) && (tr.is_left_unbounded() || !traits->equal_2_object()(tr.left(),tr.right())) || !up_direction && !tr.is_left_unbounded() && (traits->compare_x_2_object()(p,tr.left()) == EQUAL) && (tr.is_right_unbounded() || !traits->equal_2_object()(tr.left(),tr.right()))) { // recalculate vertical ray shoot using locate on point return up_direction ? locate(tr.right(),t).top() : locate(tr.left(),t).bottom(); } curve_const_ref c = up_direction ? tr.top() : tr.bottom(); if (up_direction ? tr.is_top_unbounded() : tr.is_bottom_unbounded()) { t=UNBOUNDED_TRAPEZOID; } else { // Now we know that the trapezoid is bounded on in the // direction of the shoot. t = (traits->equal_2_object() (p,traits->construct_min_vertex_2_object()(c)) || traits->equal_2_object() (p,traits->construct_max_vertex_2_object()(c))) ? POINT : CURVE; } return c; } /* Input: 1 whole curves 2 partial curves Output: X_curve precondition: c The first input X_curve is the union of the other two. The intersection of the latter is a point inside the interior of the former. The latter are ordered from left-down to right-up postcondition: The first input X_curve is broken into two curves corresponding to the input. The output is the degenerate point trapezoid that corresponds to the splitting point.*/ void split_edge(curve_const_ref cv,curve_const_ref cv1, curve_const_ref cv2) { #ifdef CGAL_TD_DEBUG std::cout << "\nTD::split_edge(" << cv << "," << cv1 << "," << cv2 << ") called with " << (is_valid(*DS) ? "valid" : "invalid") << " data structure" << std::endl; write(std::cout,*DS,*traits) << std::endl; #endif if (needs_update_) update(); #ifndef CGAL_NO_TRAPEZOIDAL_DECOMPOSITION_2_OPTIMIZATION locate_opt_empty(); #endif #ifndef CGAL_TD_DEBUG if (!traits) { CGAL_warning(traits); return; } if (!traits->are_mergeable_2_object()(cv1,cv2)) { CGAL_warning(traits->are_mergeable_2_object()(cv1,cv2)); return; } #else if (!traits->are_mergeable_2_object()(cv1,cv2)) { std::cerr << "\ncv " << cv; std::cerr << "\ncv1 " << cv1; std::cerr << "\ncv2 " << cv2 << std::endl; } CGAL_precondition(traits); CGAL_precondition(traits->are_mergeable_2_object()(cv1,cv2)); #endif // spliting point Point p = traits->equal_2_object()( traits->construct_max_vertex_2_object()(cv1), traits->construct_min_vertex_2_object()(cv2)) ? traits->construct_max_vertex_2_object()(cv1) : traits->construct_max_vertex_2_object()(cv2); #ifndef CGAL_TD_DEBUG CGAL_warning( CGAL_POINT_IS_LEFT_LOW( traits->construct_min_vertex_2_object()(cv),p)); CGAL_warning( CGAL_POINT_IS_RIGHT_TOP( traits->construct_max_vertex_2_object()(cv),p)); #else CGAL_precondition( CGAL_POINT_IS_LEFT_LOW( traits->construct_min_vertex_2_object()(cv),p)); CGAL_precondition( CGAL_POINT_IS_RIGHT_TOP( traits->construct_max_vertex_2_object()(cv),p)); #endif // extremal points Point leftmost=traits->construct_min_vertex_2_object()(cv), rightmost=traits->construct_max_vertex_2_object()(cv); Locate_type lt1,lt2; // representing trapezoids for extremal points reference t1=locate(leftmost,lt1), t2=locate(rightmost,lt2); #ifndef CGAL_TD_DEBUG CGAL_warning(lt1==POINT && lt2==POINT); CGAL_warning(t1.is_active() && t2.is_active()); #else CGAL_precondition(lt1==POINT && lt2==POINT); CGAL_precondition(t1.is_active() && t2.is_active()); CGAL_warning(t1.get_node()); CGAL_warning(t2.get_node()); #endif Data_structure &tt1=*t1.get_node(); In_face_iterator bottom_it(follow_curve(tt1,cv,SMALLER)), mid_it(follow_curve(tt1,cv,EQUAL)), top_it(follow_curve(tt1,cv,LARGER)); Locate_type lt; reference old_t=locate(p,lt); //X_curve const * old_cv=&old_t.top(); #ifdef CGAL_TD_DEBUG CGAL_assertion(lt==CURVE); CGAL_precondition(old_t.is_active()); CGAL_warning(old_t.get_node()); #endif Data_structure &old_tt=*old_t.get_node(); // previous left and right sons of old_tt const Data_structure &old_left=old_tt.left(), &old_right=old_tt.right(); X_curve left_cv,right_cv; if (traits->equal_2_object()(traits->construct_min_vertex_2_object()(cv2),p)) { left_cv=cv1; right_cv=cv2; } else { left_cv=cv2; right_cv=cv1; } const Data_structure &new_left_tt=Data_structure(X_trapezoid(old_t.left(), p, left_cv, left_cv), old_left, old_right), &new_right_tt=Data_structure(X_trapezoid(p, old_t.right(), right_cv, right_cv), old_left, old_right), &new_tt=Data_structure(X_trapezoid(p, p, left_cv, right_cv), new_left_tt, new_right_tt); reference new_left_t=*new_left_tt, new_right_t=*new_right_tt, new_t=*new_tt; /* locate trapezoid trees that correspond to the closest trapezoids above and below p */ pointer left_top_t=top_it.operator->(), left_bottom_t=bottom_it.operator->(); while(CGAL_POINT_IS_LEFT_LOW(left_top_t->right(),p)) left_top_t=left_top_t->right_bottom_neighbour(); while(CGAL_POINT_IS_LEFT_LOW(left_bottom_t->right(),p)) left_bottom_t=left_bottom_t->right_top_neighbour(); Data_structure left_top=*left_top_t->get_node(), left_bottom=*left_bottom_t->get_node(); replace_curve_at_point_using_geometry(cv,left_cv,t1); replace_curve_at_point_using_geometry(cv,right_cv,t2); // the point p belongs to cv interior new_t.set_rt(&new_left_t); new_t.set_lb(&new_right_t); new_left_t.set_lb(old_t.left_bottom_neighbour() != &old_t ? old_t.left_bottom_neighbour() : &new_left_t); new_left_t.set_rt(&new_right_t); new_right_t.set_lb(&new_left_t); new_right_t.set_rt(old_t.right_top_neighbour() != &old_t ? old_t.right_top_neighbour() : &new_right_t); // update geometric boundary for trapezoids representing cv pointer prev=0; while(*mid_it != old_t) { mid_it->set_top(left_cv); mid_it->set_bottom(left_cv); mid_it->set_right(p); prev=mid_it.operator->();mid_it++; } if (prev) { prev->set_rb(&new_left_t); } // new_left_t is leftmost representative for cv else { replace_curve_at_point_using_geometry(new_left_t,t1); } if (t1.right_top_neighbour()==&old_t) t1.set_rt(&new_left_t); if (t1.left_bottom_neighbour()==&old_t) t1.set_lb(&new_left_t); mid_it++; new_right_t.set_rb(mid_it.operator->()); prev=0; while(!!mid_it) { mid_it->set_top(right_cv); mid_it->set_bottom(right_cv); mid_it->set_left(p); prev=mid_it.operator->(); mid_it++; } if (prev) { new_right_t.set_rb(old_t.right_bottom_neighbour()); } else // new_right_t is rightmost representative for cv { replace_curve_at_point_using_geometry(new_right_t,t2,false); } if (t2.right_top_neighbour()==&old_t) t2.set_rt(&new_right_t); if (t2.left_bottom_neighbour()==&old_t) t2.set_lb(&new_right_t); /* update geometric boundary for trapezoids below cv*/ while (*bottom_it!=*left_bottom) { #ifdef CGAL_TD_DEBUG CGAL_assertion(traits->equal_2_object()(bottom_it->top() ,cv)); #endif bottom_it->set_top(left_cv); bottom_it++; } #ifdef CGAL_TD_DEBUG CGAL_assertion(*bottom_it==*left_bottom); #endif Data_structure &bottom_tt=*bottom_it->get_node(); bottom_it++; #ifdef CGAL_TD_DEBUG CGAL_assertion(traits->is_in_closure(*bottom_tt,p)); #endif split_trapezoid_by_point(bottom_tt,p,left_cv,right_cv); // set the splitting trapezoid to be the same one that splits the // X_curve'like trapezoid *bottom_tt=new_t; // update top curves bottom_tt.left()->set_top(left_cv); bottom_tt.right()->set_top(right_cv); // left and right are not neighbours. bottom_tt.left()->set_rt(0); bottom_tt.right()->set_lt(0); while(!!bottom_it) { #ifdef CGAL_TD_DEBUG CGAL_assertion(traits->equal_2_object()(bottom_it->top(),cv)); #endif bottom_it->set_top(right_cv); bottom_it++; } /* update geometric boundary for trapezoids above cv*/ while (*top_it!=*left_top) { #ifdef CGAL_TD_DEBUG CGAL_assertion(traits->equal_2_object()(top_it->bottom(),cv)); #endif top_it->set_bottom(left_cv); top_it++; } #ifdef CGAL_TD_DEBUG CGAL_assertion(*top_it==*left_top); #endif Data_structure &top_tt=*top_it->get_node(); top_it++; #ifdef CGAL_TD_DEBUG CGAL_assertion(traits->is_in_closure(*bottom_tt,p)); #endif split_trapezoid_by_point(top_tt,p,left_cv,right_cv); // set the splitting trapezoid to be the same one that splits the // X_curve'like trapezoid *top_tt=new_t; // update bottom side top_tt.left()->set_bottom(left_cv); top_tt.right()->set_bottom(right_cv); // left and right aren't neighbours top_tt.left()->set_rb(0); top_tt.right()->set_lb(0); while(!!top_it) { #ifndef CGAL_TD_DEBUG CGAL_warning(traits->equal_2_object()(top_it->bottom(),cv)); #else if (!traits->equal_2_object()(top_it->bottom(),cv)) std::cout << "\ntop_it->bottom() "<< top_it->bottom() << "\t cv= " << cv; CGAL_assertion(traits->equal_2_object()(top_it->bottom(),cv)); #endif top_it->set_bottom(right_cv); top_it++; } // mark inactive trapezoids old_t.remove((Data_structure*)&new_tt); const Data_structure *newPtr=&old_t.get_node()->left(), *newleftPtr=&newPtr->left(), *newrightPtr=&newPtr->right(), *oldleftPtr=&newleftPtr->left(), *oldrightPtr=&newleftPtr->right(); (*newPtr)->set_node((Data_structure*)newPtr); (*newleftPtr)->set_node((Data_structure*)newleftPtr); (*newrightPtr)->set_node((Data_structure*)newrightPtr); (*oldleftPtr)->set_node((Data_structure*)oldleftPtr); (*oldrightPtr)->set_node((Data_structure*)oldrightPtr); #ifdef CGAL_TD_DEBUG CGAL_assertion(old_tt->is_valid(traits)); CGAL_assertion(new_tt->is_valid(traits)); CGAL_assertion((*newPtr)->is_valid(traits)); CGAL_assertion((*newleftPtr)->is_valid(traits)); CGAL_assertion((*newrightPtr)->is_valid(traits)); CGAL_assertion((*oldleftPtr)->is_valid(traits)); CGAL_assertion((*oldrightPtr)->is_valid(traits)); CGAL_assertion(top_tt->is_valid(traits)); CGAL_assertion(bottom_tt->is_valid(traits)); CGAL_assertion(old_left->is_valid(traits)); CGAL_assertion(old_right->is_valid(traits)); CGAL_assertion(traits->is_degenerate_point(**newPtr)); CGAL_assertion(traits->is_degenerate_curve(**newleftPtr)); CGAL_assertion(traits->is_degenerate_curve(**newrightPtr)); CGAL_assertion( traits->equal_2_object()( traits->construct_min_vertex_2_object()((*newrightPtr)->bottom()), (*newPtr)->right() ) ); CGAL_assertion( traits->equal_2_object()( traits->construct_max_vertex_2_object()((*newleftPtr)->top()), (*newPtr)->left() ) ); #endif // reevaluating number of curves number_of_curves_++; #ifdef CGAL_TD_DEBUG std::cout << "\nTD::split_edge() exited with data structure" << is_valid(*DS) << std::endl; write(std::cout,*DS,*traits) << std::endl; #endif } void merge_edge( curve_const_ref cv1 , curve_const_ref cv2, curve_const_ref cv) { #ifdef CGAL_TD_DEBUG std::cout << "\nTD::merge_edge(" << cv1 << "," << cv2 << "," << cv << ") called with " << (is_valid(*DS) ? "valid" : "invalid") << " data structure" << std::endl; write(std::cout,*DS,*traits) << std::endl; #endif if (needs_update_) update(); #ifndef CGAL_NO_TRAPEZOIDAL_DECOMPOSITION_2_OPTIMIZATION locate_opt_empty(); #endif #ifndef CGAL_TD_DEBUG if (!traits) { CGAL_warning(traits); return; } if (!traits->are_mergeable_2_object()(cv1,cv2)) { CGAL_warning(traits->are_mergeable_2_object()(cv1,cv2)); return; } #else if (!traits->are_mergeable_2_object()(cv1,cv2)) { std::cerr << "\ncv " << cv; std::cerr << "\ncv1 " << cv1; std::cerr << "\ncv2 " << cv2 << std::endl; } CGAL_assertion(traits); CGAL_precondition(traits->are_mergeable_2_object()(cv1,cv2)); #endif Point p= // Calculate the common point of cv1 and cv2. // There should be one! traits->equal_2_object()(traits->construct_max_vertex_2_object()(cv1), traits->construct_min_vertex_2_object()(cv2)) ? traits->construct_max_vertex_2_object()(cv1) : // [-- cv1 -->] p [-- cv2 -->] or [<-- cv2 --] p [<-- cv1 --] traits->equal_2_object()(traits->construct_min_vertex_2_object()(cv1), traits->construct_max_vertex_2_object()(cv2)) ? // [<-- cv1 --] p [<-- cv2 --] or [-- cv2 -->] p [-- cv1 -->] traits->construct_min_vertex_2_object()(cv1) : // traits->equal_2_object()(traits->construct_min_vertex_2_object()(cv1), traits->construct_min_vertex_2_object()(cv2)) ? // [<-- cv1 --] p [-- cv2 -->] traits->construct_min_vertex_2_object()(cv1) : // [-- cv1 -->] p [<-- cv2 --] traits->construct_max_vertex_2_object()(cv1); #ifdef CGAL_TD_DEBUG // p is interior to the union curve CGAL_precondition( CGAL_POINT_IS_LEFT_LOW( traits->construct_min_vertex_2_object()(cv),p )); CGAL_precondition( CGAL_POINT_IS_RIGHT_TOP( traits->construct_max_vertex_2_object()(cv),p )); #endif Point leftmost=traits->construct_min_vertex_2_object()(cv), rightmost=traits->construct_max_vertex_2_object()(cv); Locate_type lt1,lt2,lt; reference t1=locate(leftmost,lt1), t2=locate(rightmost,lt2), t=locate(p,lt); #ifndef CGAL_TD_DEBUG CGAL_warning(t1.get_node()); CGAL_warning(t2.get_node()); CGAL_warning(t.get_node()); #else CGAL_precondition(lt1==POINT && lt2==POINT && lt==POINT); CGAL_precondition(t1.is_active() && t2.is_active() && t.is_active()); CGAL_assertion(t1.get_node()); CGAL_assertion(t2.get_node()); CGAL_assertion(t.get_node()); #endif X_curve left_cv,right_cv; if (traits->equal_2_object()(traits->construct_min_vertex_2_object()(cv2),p)) { left_cv=cv1; right_cv=cv2; } else { left_cv=cv2; right_cv=cv1; } #ifdef CGAL_TD_DEBUG CGAL_assertion(traits->equal_2_object()( t1.left(),leftmost )); CGAL_assertion(traits->equal_2_object()( t2.right(),rightmost )); CGAL_assertion(CGAL_POINT_IS_LEFT_LOW( leftmost,p )); CGAL_assertion(CGAL_POINT_IS_LEFT_LOW( p,rightmost )); CGAL_assertion(traits->equal_2_object()( traits->construct_min_vertex_2_object()(left_cv),leftmost )); CGAL_assertion(traits->equal_2_object()( traits->construct_max_vertex_2_object()(left_cv),p )); CGAL_assertion(traits->equal_2_object()( traits->construct_min_vertex_2_object()(right_cv),p )); CGAL_assertion(traits->equal_2_object()( traits->construct_max_vertex_2_object()(right_cv),rightmost )); CGAL_assertion(traits->equal_2_object()( traits->construct_min_vertex_2_object()(cv),leftmost )); CGAL_assertion(traits->equal_2_object()( traits->construct_max_vertex_2_object()(cv),rightmost )); #endif Data_structure &tt1=*t1.get_node(), &tt=*t.get_node(); In_face_iterator bottom_left_it(follow_curve(tt1,left_cv,SMALLER)), mid_left_it(follow_curve(tt1,left_cv,EQUAL)), top_left_it(follow_curve(tt1,left_cv,LARGER)), bottom_right_it(follow_curve(tt,right_cv,SMALLER)), mid_right_it(follow_curve(tt,right_cv,EQUAL)), top_right_it(follow_curve(tt,right_cv,LARGER)); #ifdef CGAL_TD_DEBUG CGAL_assertion(bottom_left_it.operator->()); CGAL_assertion(mid_left_it.operator->()); CGAL_assertion(top_left_it.operator->()); CGAL_assertion(bottom_right_it.operator->()); CGAL_assertion(mid_right_it.operator->()); CGAL_assertion(top_right_it.operator->()); CGAL_assertion(bottom_left_it->is_active()); CGAL_assertion(mid_left_it->is_active()); CGAL_assertion(top_left_it->is_active()); CGAL_assertion(bottom_right_it->is_active()); CGAL_assertion(mid_right_it->is_active()); CGAL_assertion(top_right_it->is_active()); #endif pointer left=mid_left_it.operator->(), mid_left=0, mid_right=mid_right_it.operator->(), top_left=0, top_right=top_right_it.operator->(), bottom_left=0, bottom_right=bottom_right_it.operator->(), right=0, dummy=0, dummy2=0; replace_curve_using_geometry(mid_left_it,left_cv,cv,mid_left); replace_curve_using_geometry(mid_right_it,right_cv,cv,right); replace_curve_using_geometry(top_left_it,left_cv,cv,top_left); replace_curve_using_geometry(top_right_it,right_cv,cv,dummy); replace_curve_using_geometry(bottom_left_it,left_cv,cv,bottom_left); replace_curve_using_geometry(bottom_right_it,right_cv,cv,dummy2); // merge trapezoids splited by the upward and downward // vertical extensions from p #ifndef CGAL_TD_DEBUG merge_if_possible(top_left,top_right); merge_if_possible(bottom_left,bottom_right); #else CGAL_warning(top_left); CGAL_warning(top_right); CGAL_warning(merge_if_possible(top_left,top_right)); CGAL_warning(bottom_left); CGAL_warning(bottom_right); CGAL_warning(merge_if_possible(bottom_left,bottom_right)); #endif // mark older trapezoids as inactive top_right->remove(top_left->get_node()); bottom_right->remove(bottom_left->get_node()); #ifdef CGAL_TD_DEBUG CGAL_warning(mid_left); CGAL_warning(mid_right); CGAL_warning(tt->is_active()); #endif // make p's representative inactive tt->remove(); mid_left->set_rb(mid_right); mid_left->set_right(mid_right->right()); mid_right->set_left(mid_left->left()); mid_left->set_rt(0); mid_right->set_lb(0); replace_curve_at_point_using_geometry(left_cv,cv,t1); replace_curve_at_point_using_geometry(right_cv,cv,t2); #ifdef CGAL_TD_DEBUG CGAL_warning(left); CGAL_warning(right); #endif replace_curve_at_point_using_geometry(*left,t1,true); replace_curve_at_point_using_geometry(*right,t2,false); // reevaluating number of curves number_of_curves_--; #ifdef CGAL_TD_DEBUG std::cout << "\nTD::merge_edge() exited with data structure" << is_valid(*DS) << std::endl; write(std::cout,*DS,*traits) << std::endl; #endif } unsigned long size() const { return DS->size(); } unsigned long depth() const { return DS->depth(); } unsigned long number_of_curves() const { return number_of_curves_; } void init_traits(const_Traits_ptr t) { traits = t; #ifdef CGAL_TD_DEBUG CGAL_assertion(!!*DS); #endif } /* update geometric boundary(top and bottom) for trapezoids traveled along an iterator till end reached precondition: end==0 or end is on the path of the iterator postcondition: end is pointer to the last trapezoid encountered,if any */ /*------------------------------------------------------------------ description: returns whether the Trapezoidal Dag is valid */ #ifdef CGAL_TD_DEBUG bool is_valid(const Data_structure& ds) const { if ( !ds ) return true; if (ds->is_valid(traits) && ds->get_node() && is_valid(ds.left()) && is_valid(ds.right())) return true; CGAL_warning(ds->is_valid(traits)); CGAL_warning(ds->get_node()); CGAL_warning(is_valid(ds.left())); CGAL_warning(is_valid(ds.right())); return false; } /*------------------------------------------------------------------ description: returns whether the member Trapezoidal data structure is valid */ bool is_valid() const { return is_valid(*DS); } void debug() const { std::cout << "\nTrapezoidal_decomposition_2<Traits>::debug()\n" << *this << std::endl; X_trapezoid x; x.debug(); } #endif /*------------------------------------------------------------------ description: Rebuilds the trapezoid data structure by reinserting the curves in a random order in an empty data structure. postcondition: The old and new data structures agree on their member curves. ------------------------------------------------------------------*/ Self& rebuild() { #ifdef CGAL_TD_DEBUG std::cout << "\nrebuild()" << std::flush; #endif X_curve_container container; unsigned long rep = X_curve_filter(container, &get_data_structure()); clear(); // initialize container to point to curves in X_trapezoid Tree if (rep>0) { bool o=set_needs_update(false); typename std::vector<X_curve>::iterator it = container.begin(), it_end = container.end(); while(it!=it_end) { insert(*it); ++it; } set_needs_update(o); } #ifdef CGAL_TD_DEBUG CGAL_assertion(is_valid()); unsigned long sz=number_of_curves(); if(sz!=rep) { std::cerr << "\nnumber_of_curves()=" << sz; std::cerr << "\nrepresentatives.size()=" << rep; CGAL_assertion(number_of_curves()==rep); } #endif container.clear(); return *this; } /* Input: a list of pointers to X_trapezoids and a X_trapezoid boolean predicate. Output: void Postcondition: the list pointers correspond to all the X_trapezoids in the data structure for which the predicate value is true. */ template <class Container, class Predicate> void filter(Container& c, const Predicate& pr, const Data_structure* ds=&get_data_structure()) const { CGAL_assertion(ds); ds->filter(c,pr); } template <class Container> unsigned long X_trapezoid_filter(Container& container, const Data_structure* ds) const /* Return a container for all active trapeozoids */ { ds->filter(container, Td_active_trapezoid()); return container.size(); } template <class X_curve_container> unsigned long X_curve_filter(X_curve_container& container, const Data_structure* ds) const /* Return a container for all active curves */ { unsigned long sz=number_of_curves(); list_container representatives; ds->filter(representatives, Td_active_right_degenerate_curve_trapezoid(*traits)); #ifndef CGAL_TD_DEBUG CGAL_warning(sz==representatives.size()); #else unsigned long rep=representatives.size(); if (sz!=rep) { std::cerr << "\nnumber_of_curves()=" << sz; std::cerr << "\nrepresentatives.size()=" << rep; CGAL_assertion(number_of_curves()==representatives.size()); } #endif if (sz>0) { typename list_container::iterator it = representatives.begin(), it_end = representatives.end(); while(it!=it_end) { container.push_back(it->top()); ++it; } } if(! container.empty()) { std::random_shuffle(container.begin(),container.end()); } return sz; } /*------------------------------------------------------------------ Input: None Output: bool Description: determines according to pre defined conditions whether the current Trapezoidal_decomposition_2<Traits> needs update Postconditions: The output is true iff the depth of the Trapezoidal Tree is more then DepthThreshold times log of the X_curve count or the Trapezoidal Tree's size is more then SizeThreshold times the log of the last count. */ bool set_needs_update(bool u) { bool old=needs_update_; needs_update_=u; return old; } bool needs_update() { unsigned long sz = number_of_curves(); //to avoid signed / unsigned conversion warnings // rand() returns an int but a non negative one. if (static_cast<unsigned long>(std::rand()) > RAND_MAX / (sz+1)) return false; /* INTERNAL COMPILER ERROR overide #ifndef __GNUC__ */ #ifdef CGAL_TD_REBUILD_DEBUG std::cout << "\n|heavy!" << std::flush; #endif return depth()>(get_depth_threshold()*(CGAL_CLIB_STD::log(double(sz+1)))) || size()>(get_size_threshold()*(sz+1)); /* #else // to avoid comparison between signed and unsigned return ((depth()/10)>log(sz+1))||((size()/10)>(sz+1)); //return ((((signed)depth())/10)>log(sz+1))|| ((((signed)size())/10)>(sz+1)); #endif */ } /*------------------------------------------------------------------ input: None output: bool Description: uses needs_update to determine whether the Trapezoidal_decomposition_2<Traits> needs update and calls rebuild accordingly Postcondition: the return value is true iff rebuilding took place. */ bool update() { #ifdef CGAL_TD_REBUILD_DEBUG std::cout << "\n|" << needs_update() << std::flush; #endif if (needs_update()) {rebuild();return true;} return false; } /* returns a reference to the internal data structure */ const Data_structure& get_data_structure() const {return *DS;} /* returns a reference to the internal data structure */ const_Traits_ref get_traits() const {return *traits;} /* returns a reference to the internal depth threshold constant */ const double& get_depth_threshold() const { return depth_threshold; } /* returns a reference to the internal size threshold constant */ const double& get_size_threshold() const { return size_threshold; } /* sets the internal depth threshold constant to the parameter and returns its reference */ const double& set_depth_threshold(const double& depth_th) { return depth_threshold=depth_th; } /* sets the internal size threshold constant to the parameter and returns its reference */ const double& set_size_threshold(const double& size_th) { return size_threshold=size_th; } protected: Data_structure* DS; bool needs_update_; unsigned long number_of_curves_; const_Traits_ptr traits; private: #ifndef CGAL_NO_TRAPEZOIDAL_DECOMPOSITION_2_OPTIMIZATION mutable pointer last_cv,prev_cv; #endif void init() { // traits may be initialized later DS = new Data_structure(X_trapezoid()); (*DS)->set_node(DS); /* Point tmp; if (!CGAL_POINT_IS_LEFT_LOW(TD_X_trapezoid<Traits, X_curve>::POINT_AT_LEFT_TOP_INFINITY,tmp=TD_X_trapezoid<Traits, X_curve>::POINT_AT_RIGHT_BOTTOM_INFINITY)) TD_X_trapezoid<Traits, X_curve>::POINT_AT_LEFT_TOP_INFINITY=traits->point_to_left(tmp); */ #ifdef CGAL_TD_DEBUG CGAL_warning(!!*DS); #endif number_of_curves_=0; #ifndef CGAL_NO_TRAPEZOIDAL_DECOMPOSITION_2_OPTIMIZATION locate_opt_empty(); #endif } #ifndef CGAL_NO_TRAPEZOIDAL_DECOMPOSITION_2_OPTIMIZATION void locate_opt_push(pointer cv) const { prev_cv=last_cv; last_cv=cv; } void locate_opt_empty() const { last_cv=prev_cv=0; } bool locate_opt_swap(pointer& cv) const { cv=last_cv; last_cv=prev_cv; prev_cv=cv; return (cv!=0); } void locate_optimization(const Point& p,pointer& tr,Locate_type& lt) const { // optimization if (locate_opt_swap(tr)&&tr->is_active()&& (traits->is_degenerate_point(*tr)&& traits->equal_2_object()(tr->left(),p)|| !traits->is_degenerate(*tr)&& traits->is_inside(*tr,p) )|| locate_opt_swap(tr)&&tr->is_active()&& (traits->is_degenerate_point(*tr)&& traits->equal_2_object()(tr->left(),p)|| !traits->is_degenerate(*tr)&& traits->is_inside(*tr,p) ) ) if(traits->is_degenerate_point(*tr)) lt=POINT; else lt=tr->is_unbounded()?UNBOUNDED_TRAPEZOID:TRAPEZOID; else tr=&locate(p,lt); } #endif protected: bool is_isolated_point(const_ref tr) const { #ifdef CGAL_TD_DEBUG CGAL_precondition(traits->is_degenerate_point(tr)); #endif return !tr.right_top_neighbour()&&!tr.left_bottom_neighbour(); } protected: double depth_threshold,size_threshold; }; CGAL_END_NAMESPACE #ifndef CGAL_TD_X_TRAPEZOID_H #include <CGAL/Arr_point_location/Td_X_trapezoid.h> #endif #ifdef CGAL_TD_DEBUG #ifndef CGAL_TRAPEZOIDAL_DECOMPOSITION_2_IOSTREAM_H #include <CGAL/Arr_point_location/Trapezoidal_decomposition_2_iostream.h> #endif #endif #endif
[ "viticm@126.com" ]
viticm@126.com
191646664dc7d0a052d73bddc09d00a7344a69e0
9ff7ecb1cd346cd2523b5c556405c75cebb4e66f
/282.expression-add-operators.cpp
121acbf34c41c3a84d43839a381a8d4cdd258396
[]
no_license
kingsmad/leetcode_2017
c8785ce3fb56e0eab0c7b5013b0bc52570bdd418
f5cc0d09c3b77faa804739ea43ba4a090397c718
refs/heads/master
2021-03-22T01:29:51.127263
2018-08-08T22:43:25
2018-08-08T22:43:25
97,318,569
0
0
null
null
null
null
UTF-8
C++
false
false
1,071
cpp
#include <bits/stdc++.h> using namespace std; int n; vector<string> ans; using ll = long long; class Solution { public: vector<string> addOperators(string num, int target) { n = num.size(); ans.clear(); string path = ""; for (int i = 1; i <= n; ++i) { if (num[0] == '0' && i > 1) break; path = num.substr(0, i); ll cv = stoll(path); dfs(i, cv, cv, path, num, target); } return ans; } void dfs(int p, ll tot, ll pre, const string path, const string& num, const int target) { if (p == n) { if (tot == target) ans.emplace_back(path); return; } ll cv = 0, q = p; while (q < n) { if (num.at(p) == '0' && q > p + 1) break; cv = 10 * cv + num.at(q++) - '0'; const string cv_str = to_string(cv); if (num.at(p) == '0' && q > p + 1) break; dfs(q, tot + cv, cv, path + "+" + cv_str, num, target); dfs(q, tot - cv, -cv, path + "-" + cv_str, num, target); dfs(q, tot - pre + pre * cv, pre * cv, path + "*" + cv_str, num, target); } } };
[ "grinchcoder@gmail.com" ]
grinchcoder@gmail.com
d5b2abcfec31956aa62717ad67dbdbecdb303476
cf4edc2a34c4627d45c47feeacf2acf079aa596f
/source/QXmlStreamNamespaceDeclaration.cpp
e543f184366423e08ca5082c3eb6a120849490b3
[ "MIT" ]
permissive
diegopego/Qt4xHb
eeb7c3e33b570193469bfca47d7d1835c2efbc38
5f96614f794cc8392b4d97f7dcd80b2fbf46ab65
refs/heads/master
2021-01-09T05:55:50.167467
2017-02-01T22:44:30
2017-02-01T22:44:30
null
0
0
null
null
null
null
ISO-8859-1
C++
false
false
4,381
cpp
/* Qt4xHb - bibliotecas de ligação entre Harbour/xHarbour e Qt Framework 4 Copyright (C) 2012-2017 Marcos Antonio Gambeta <marcosgambeta@uol.com.br> */ #include <QXmlStreamNamespaceDeclaration> #include "hbapi.h" #include "hbapiitm.h" #include "hbapierr.h" #include "hbvm.h" #include "hbstack.h" #ifndef __XHARBOUR__ #include "hbapicls.h" #define ISNIL HB_ISNIL #define ISLOG HB_ISLOG #define ISNUM HB_ISNUM #define ISCHAR HB_ISCHAR #define ISPOINTER HB_ISPOINTER #define ISOBJECT HB_ISOBJECT #define ISARRAY HB_ISARRAY #endif #include "qt4xhb_clsid.h" #include "qt4xhb_utils.h" /* QXmlStreamNamespaceDeclaration() */ HB_FUNC( QXMLSTREAMNAMESPACEDECLARATION_NEW1 ) { QXmlStreamNamespaceDeclaration * o = NULL; o = new QXmlStreamNamespaceDeclaration ( ); PHB_ITEM self = hb_stackSelfItem(); PHB_ITEM ptr = hb_itemPutPtr( NULL,(QXmlStreamNamespaceDeclaration *) o ); hb_objSendMsg( self, "_pointer", 1, ptr ); hb_itemRelease( ptr ); PHB_ITEM des = hb_itemPutL( NULL, true ); hb_objSendMsg( self, "_SELF_DESTRUCTION", 1, des ); hb_itemRelease( des ); hb_itemReturn( self ); } /* QXmlStreamNamespaceDeclaration(const QXmlStreamNamespaceDeclaration & other) */ HB_FUNC( QXMLSTREAMNAMESPACEDECLARATION_NEW2 ) { QXmlStreamNamespaceDeclaration * o = NULL; QXmlStreamNamespaceDeclaration * par1 = (QXmlStreamNamespaceDeclaration *) hb_itemGetPtr( hb_objSendMsg( hb_param(1, HB_IT_OBJECT ), "POINTER", 0 ) ); o = new QXmlStreamNamespaceDeclaration ( *par1 ); PHB_ITEM self = hb_stackSelfItem(); PHB_ITEM ptr = hb_itemPutPtr( NULL,(QXmlStreamNamespaceDeclaration *) o ); hb_objSendMsg( self, "_pointer", 1, ptr ); hb_itemRelease( ptr ); PHB_ITEM des = hb_itemPutL( NULL, true ); hb_objSendMsg( self, "_SELF_DESTRUCTION", 1, des ); hb_itemRelease( des ); hb_itemReturn( self ); } /* QXmlStreamNamespaceDeclaration(const QString & prefix, const QString & namespaceUri) */ HB_FUNC( QXMLSTREAMNAMESPACEDECLARATION_NEW3 ) { QXmlStreamNamespaceDeclaration * o = NULL; QString par1 = hb_parc(1); QString par2 = hb_parc(2); o = new QXmlStreamNamespaceDeclaration ( par1, par2 ); PHB_ITEM self = hb_stackSelfItem(); PHB_ITEM ptr = hb_itemPutPtr( NULL,(QXmlStreamNamespaceDeclaration *) o ); hb_objSendMsg( self, "_pointer", 1, ptr ); hb_itemRelease( ptr ); PHB_ITEM des = hb_itemPutL( NULL, true ); hb_objSendMsg( self, "_SELF_DESTRUCTION", 1, des ); hb_itemRelease( des ); hb_itemReturn( self ); } //[1]QXmlStreamNamespaceDeclaration() //[2]QXmlStreamNamespaceDeclaration(const QXmlStreamNamespaceDeclaration & other) //[3]QXmlStreamNamespaceDeclaration(const QString & prefix, const QString & namespaceUri) HB_FUNC( QXMLSTREAMNAMESPACEDECLARATION_NEW ) { if( ISNUMPAR(0) ) { HB_FUNC_EXEC( QXMLSTREAMNAMESPACEDECLARATION_NEW1 ); } else if( ISNUMPAR(1) && ISQXMLSTREAMNAMESPACEDECLARATION(1) ) { HB_FUNC_EXEC( QXMLSTREAMNAMESPACEDECLARATION_NEW2 ); } else if( ISNUMPAR(2) && ISCHAR(1) && ISCHAR(2) ) { HB_FUNC_EXEC( QXMLSTREAMNAMESPACEDECLARATION_NEW3 ); } else { hb_errRT_BASE( EG_ARG, 3012, NULL, HB_ERR_FUNCNAME, HB_ERR_ARGS_BASEPARAMS ); } } HB_FUNC( QXMLSTREAMNAMESPACEDECLARATION_DELETE ) { QXmlStreamNamespaceDeclaration * obj = (QXmlStreamNamespaceDeclaration *) hb_itemGetPtr( hb_objSendMsg( hb_stackSelfItem(), "POINTER", 0 ) ); if( obj ) { delete obj; obj = NULL; PHB_ITEM self = hb_stackSelfItem(); PHB_ITEM ptr = hb_itemPutPtr( NULL, NULL ); hb_objSendMsg( self, "_pointer", 1, ptr ); hb_itemRelease( ptr ); } hb_itemReturn( hb_stackSelfItem() ); } /* QStringRef namespaceUri() const */ HB_FUNC( QXMLSTREAMNAMESPACEDECLARATION_NAMESPACEURI ) { QXmlStreamNamespaceDeclaration * obj = (QXmlStreamNamespaceDeclaration *) hb_itemGetPtr( hb_objSendMsg( hb_stackSelfItem(), "POINTER", 0 ) ); if( obj ) { QStringRef * ptr = new QStringRef( obj->namespaceUri ( ) ); _qt4xhb_createReturnClass ( ptr, "QSTRINGREF" ); } } /* QStringRef prefix() const */ HB_FUNC( QXMLSTREAMNAMESPACEDECLARATION_PREFIX ) { QXmlStreamNamespaceDeclaration * obj = (QXmlStreamNamespaceDeclaration *) hb_itemGetPtr( hb_objSendMsg( hb_stackSelfItem(), "POINTER", 0 ) ); if( obj ) { QStringRef * ptr = new QStringRef( obj->prefix ( ) ); _qt4xhb_createReturnClass ( ptr, "QSTRINGREF" ); } }
[ "marcosgambeta@uol.com.br" ]
marcosgambeta@uol.com.br
a45b5d0cbb581372015100ad4646bac2d2c86ba5
eee4e1d7e3bd56bd0c24da12f727017d509f919d
/Case/case7/2200/phi
0e1a63bdd5481f2133c5f912a03bd94445cd027f
[]
no_license
mamitsu2/aircond5_play5
35ea72345d23c5217564bf191921fbbe412b90f2
f1974714161f5f6dad9ae6d9a77d74b6a19d5579
refs/heads/master
2021-10-30T08:59:18.692891
2019-04-26T01:48:44
2019-04-26T01:48:44
183,529,942
0
0
null
null
null
null
UTF-8
C++
false
false
13,505
/*--------------------------------*- C++ -*----------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Version: 6 \\/ M anipulation | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class surfaceScalarField; location "2200"; object phi; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [1 0 -1 0 0 0 0]; internalField nonuniform List<scalar> 850 ( -0.00241109 0.0024758 -0.00251553 0.0001045 -0.00274828 0.000232822 -0.00304701 0.000298805 -0.00333954 0.000292605 -0.00359232 0.000252859 -0.00378339 0.000191163 -0.00389351 0.000110216 -0.00390335 9.93791e-06 -0.00379075 -0.000112496 -0.00353352 -0.000257122 -0.00311424 -0.000419162 -0.00249971 -0.000614401 -0.001559 -0.000940581 -0.00155657 -0.000622052 0.000626281 -0.000520071 -0.000101953 -0.000272771 -0.000247281 -0.000259896 -1.28987e-05 -0.000491013 0.000231052 -0.000679285 0.00018822 -0.000743039 6.37271e-05 -0.000735708 -7.34346e-06 -0.000684676 -5.10323e-05 -0.000598814 -8.58531e-05 -0.000473266 -0.000125529 -0.000322687 -0.000150544 -0.000250414 -7.22092e-05 -0.000274786 2.44656e-05 -7.86548e-05 -0.000196016 0.000370637 -0.000449169 0.000686042 -0.000315283 0.000690233 -0.00177366 0.00441606 -0.00230792 0.000638835 -0.0027344 0.00065938 -0.00309702 0.000661509 -0.00342239 0.000618066 -0.00370093 0.000531497 -0.00391883 0.000409163 -0.00406133 0.000252834 -0.00411371 6.24356e-05 -0.00406417 -0.000161913 -0.00390205 -0.000419101 -0.00361277 -0.000708302 -0.00318606 -0.00104096 -0.00270385 -0.00142264 -0.00257945 -0.00168082 -0.00100497 -0.00157001 0.000494294 -0.00149447 0.000508609 0.000674489 -3.68686e-05 0.0003968 0.000175789 6.07614e-05 8.88103e-05 9.75021e-06 3.81519e-05 -6.69214e-05 0.000307727 -0.00022004 0.000341312 -0.000263897 0.00010756 -0.000284794 1.35376e-05 -0.00029382 -4.20114e-05 -0.000288185 -9.14826e-05 -0.000263417 -0.00015028 -0.000220465 -0.000193456 -0.000202249 -9.0336e-05 -0.000234978 5.73132e-05 -6.71219e-05 -0.000363765 9.02123e-05 -0.000606406 6.12856e-05 -0.000286248 0.000763362 -0.00133149 0.0059942 -0.0020458 0.00135322 -0.00255166 0.00116532 -0.0029399 0.00104984 -0.00327825 0.000956519 -0.00356954 0.00082289 -0.00380636 0.000646094 -0.00397849 0.000425079 -0.00407519 0.000159263 -0.00408921 -0.000147759 -0.00401927 -0.000488893 -0.00387186 -0.000855563 -0.00367512 -0.00123755 -0.00349703 -0.00160057 -0.00333129 -0.00184638 -0.00295122 -0.0019499 -0.00244307 -0.00200245 -0.00192289 -0.00103082 0.00100761 -0.00114935 0.000294414 -0.00110424 4.37998e-05 -0.000907731 -0.000158268 -0.000253381 -0.000346541 8.80975e-05 0.000195824 0.000209531 0.000167688 7.63718e-05 -7.37476e-05 -0.000266988 -0.000356998 -0.000299315 7.81963e-06 -0.000670806 -0.000582193 -1.63404e-05 -0.00104787 0.000179515 -0.000267882 -0.00100927 0.00731536 -0.00178255 0.00212658 -0.00226241 0.00164527 -0.00262917 0.00141669 -0.00294411 0.00127156 -0.00321427 0.00109315 -0.00343862 0.000870559 -0.00361196 0.000598536 -0.00372627 0.000273703 -0.00377467 -9.92325e-05 -0.00376363 -0.000499788 -0.00372123 -0.000897818 -0.00369102 -0.0012676 -0.00371677 -0.00157466 -0.00378875 -0.00177423 -0.00387715 -0.00186132 -0.00406538 -0.00181404 -0.00465019 -0.00133791 -0.0040595 -0.000577239 -0.00316403 0.000112283 -0.00303921 0.000169738 -0.00298095 -1.43169e-05 -0.00294036 -0.000198713 -0.00298665 -0.000300126 -0.00269804 -0.000288649 -0.00236884 -0.00032925 -0.00197061 -0.000398293 -0.00149903 -0.000471657 -0.000960051 -0.000539048 -0.00037007 -0.000590051 0.000238133 -0.000608258 0.000809661 -0.000571572 0.00134878 -0.000539153 0.00123998 -0.000561872 0.00138419 -0.00016044 0.00127492 0.000288888 0.00102351 -0.000758012 0.00844067 -0.00154151 0.00291016 -0.00190963 0.00201348 -0.0022152 0.00172235 -0.00246818 0.00152464 -0.0026739 0.00129897 -0.0028385 0.00103527 -0.00296316 0.000723312 -0.00304364 0.000354299 -0.00307152 -7.1227e-05 -0.00305602 -0.000515165 -0.00303741 -0.000916291 -0.00305727 -0.00124761 -0.00313895 -0.00149283 -0.00327388 -0.00163914 -0.00345453 -0.00168051 -0.0036987 -0.0015697 -0.00384305 -0.00119338 -0.0037375 -0.000682614 -0.0033419 -0.000283152 -0.0030121 -0.000159902 -0.00281729 -0.000208984 -0.00271233 -0.000303546 -0.00262946 -0.00038289 -0.00246864 -0.000449385 -0.00225635 -0.000541472 -0.0019983 -0.000656276 -0.00169717 -0.000772722 -0.0013686 -0.000867532 -0.00103499 -0.00092354 -0.000711329 -0.000931763 -0.000385961 -0.000896748 -7.50531e-05 -0.000849828 0.000163285 -0.000799941 0.000650243 -0.000647105 0.00132475 -0.000385299 0.00244475 -9.62105e-05 0.00218619 0.000274008 9.38074e-05 0.00210914 0.000159999 -0.000684774 0.0095414 -0.00143002 0.00365549 -0.00152527 0.00210882 -0.00172548 0.00192266 -0.00189497 0.00169423 -0.00200245 0.00140655 -0.00206426 0.00109717 -0.0020923 0.000751463 -0.00208926 0.00035137 -0.00204852 -0.000111859 -0.00198781 -0.000575754 -0.00195374 -0.00095024 -0.00197811 -0.00122312 -0.0020696 -0.00140121 -0.00221783 -0.00149078 -0.00240898 -0.00148921 -0.00261145 -0.00136708 -0.00270907 -0.0010956 -0.0026452 -0.000746331 -0.00246027 -0.000467927 -0.00228546 -0.000334558 -0.00217939 -0.000314919 -0.00213243 -0.000350401 -0.00210801 -0.000407216 -0.00207328 -0.00048405 -0.00202264 -0.00059206 -0.00195694 -0.000721931 -0.00188239 -0.000847188 -0.00181317 -0.000936633 -0.00176326 -0.000973253 -0.00173422 -0.000960547 -0.0017116 -0.000919053 -0.0016776 -0.000883449 -0.00159698 -0.000880124 -0.00132642 -0.000917174 -0.000665144 -0.00104603 0.000460443 -0.00122116 0.00150229 -0.000767168 0.00253608 0.0010757 0.00274806 -0.000964796 0.0109659 -0.00125854 0.00394932 -0.000894555 0.00174493 -0.0010111 0.0020393 -0.00114892 0.00183215 -0.00116053 0.00141826 -0.00109304 0.00102979 -0.000984203 0.000642733 -0.000842401 0.000209678 -0.000699129 -0.00025502 -0.000593171 -0.000681602 -0.000557339 -0.000985964 -0.000600618 -0.00117973 -0.000715923 -0.0012858 -0.00088696 -0.00131962 -0.00109035 -0.00128571 -0.0012838 -0.00117349 -0.00140274 -0.000976529 -0.00141561 -0.000733316 -0.00135718 -0.000526219 -0.00129361 -0.000397995 -0.00126696 -0.00034144 -0.00128666 -0.000330594 -0.00134581 -0.000347984 -0.00143765 -0.000392152 -0.00156178 -0.000467899 -0.00171834 -0.000565323 -0.00191079 -0.000654635 -0.00214793 -0.000699325 -0.00243265 -0.000688267 -0.00275038 -0.000642458 -0.0030742 -0.00059481 -0.00337307 -0.000584112 -0.00361163 -0.000641049 -0.00373113 -0.000797147 -0.00366145 -0.00111517 -0.00323862 -0.00164346 -0.00185762 -0.00214762 0.00038312 -0.00116426 0.00319178 0.00161841 0.00985945 0.00196902 0.00359878 0.00140104 0.00231299 0.000868486 0.00257195 0.000494839 0.0022059 0.000392689 0.00152052 0.000491696 0.000930889 0.000677042 0.000457497 0.000911368 -2.45338e-05 0.00110743 -0.000450972 0.00117311 -0.00074718 0.00113329 -0.00094603 0.00101738 -0.00106372 0.000844702 -0.00111301 0.000630155 -0.00110497 0.000392616 -0.00104806 0.000165404 -0.000946166 -7.86808e-06 -0.000803141 -0.00010262 -0.000638442 -0.000138317 -0.000490398 -0.00015549 -0.000380698 -0.000185227 -0.000311584 -0.000243842 -0.000271871 -0.000341913 -0.000249825 -0.000493781 -0.00024022 -0.000717754 -0.000243882 -0.00102472 -0.000258303 -0.00141483 -0.000264415 -0.00188809 -0.000225875 -0.00244064 -0.000135431 -0.00304867 -3.40662e-05 -0.00368489 4.18124e-05 -0.00433511 6.65079e-05 -0.00498513 9.37551e-06 -0.00563039 -0.000151493 -0.00633457 -0.000410601 -0.00726138 -0.000716268 -0.00829518 -0.00111344 -0.00727598 -0.00218309 -0.00379906 0.0104238 0.0140169 0.0102667 0.00606316 0.00803604 0.00480274 0.0064366 0.00380541 0.00538216 0.00257505 0.00473402 0.00157912 0.00433882 0.000852798 0.00400781 0.000306578 0.00367453 -0.000117592 0.00336312 -0.000435672 0.00306641 -0.000649224 0.00277598 -0.000773189 0.00248752 -0.00082446 0.00220044 -0.000817784 0.00191887 -0.000766387 0.00165539 -0.000682592 0.00143076 -0.000578395 0.00126062 -0.0004682 0.00113908 -0.000368741 0.00104819 -0.000289698 0.000968938 -0.000232218 0.000887848 -0.000190674 0.000794927 -0.000156805 0.000678526 -0.000123734 0.000522568 -8.78541e-05 0.000314047 -4.97149e-05 6.02898e-05 -1.05526e-05 -0.000199805 3.441e-05 -0.000433527 9.85289e-05 -0.000644669 0.000177349 -0.000853082 0.000250516 -0.00107596 0.000289688 -0.00133181 0.000265523 -0.00160832 0.000125304 -0.00188223 -0.00013641 -0.00219686 -0.000401382 -0.00255013 -0.000759913 -0.00233011 -0.00240284 -0.00582947 0.00358247 0.00425453 0.00394577 0.00443949 0.00477264 0.00297862 0.00518416 0.00216361 0.00530351 0.00145985 0.00529978 0.000856617 0.00521331 0.000393124 0.00504098 5.48289e-05 0.0047946 -0.000189203 0.00450063 -0.000355166 0.00418298 -0.00045545 0.00385953 -0.000500921 0.00354371 -0.000501871 0.00324571 -0.000468293 0.00297375 -0.000410534 0.00273518 -0.000339733 0.00253461 -0.000267524 0.00237001 -0.000204029 0.00223468 -0.000154264 0.00212026 -0.000117687 0.00201982 -9.01219e-05 0.00192842 -6.52942e-05 0.00184322 -3.84373e-05 0.00176313 -7.67139e-06 0.00168486 2.86397e-05 0.0016003 7.4097e-05 0.00150766 0.000127141 0.00142139 0.000184923 0.00135663 0.00024225 0.00131962 0.000287713 0.00130719 0.00030233 0.0013139 0.000259069 0.00131902 0.00012045 0.00131494 -0.000132038 0.00140018 -0.000486323 0.00167163 -0.00103107 0.00149856 -0.0022295 -0.00426448 -6.97066e-05 0.00432403 0.00220428 0.00216556 0.00349959 0.00168336 0.00437363 0.00128963 0.00495685 0.000876701 0.00528586 0.000527689 0.00541841 0.000260649 0.00540599 6.73218e-05 0.00528067 -6.38047e-05 0.0050759 -0.000150313 0.00482301 -0.000202484 0.00454833 -0.000226151 0.00427337 -0.000226829 0.00401487 -0.000209708 0.00378439 -0.000179965 0.00358786 -0.000143105 0.00342527 -0.00010484 0.0032915 -7.01574e-05 0.00317928 -4.19338e-05 0.00308221 -2.0506e-05 0.00299667 -4.47058e-06 0.00292247 9.02061e-06 0.00286154 2.26096e-05 0.00281544 3.85345e-05 0.00278438 5.98122e-05 0.00277187 8.67029e-05 0.00278125 0.00011786 0.00281548 0.000150791 0.00287677 0.000181068 0.00296303 0.000201569 0.00306366 0.000201835 0.00315563 0.000167268 0.0031977 7.85805e-05 0.00314599 -8.00998e-05 0.00297839 -0.000318486 0.00260647 -0.000658893 0.00159951 -0.0012223 -0.00258566 -0.00464078 -0.00593451 -0.0016112 0.000551053 0.00223014 0.00351508 0.00438678 0.00490918 0.00516429 0.00522582 0.00515599 0.00499943 0.00479048 0.00455767 0.00432399 0.00410726 0.00392012 0.00376971 0.00365747 0.00357987 0.0035305 0.00350262 0.0034909 0.00349286 0.00350868 0.00354076 0.00359455 0.00367578 0.00378883 0.0039356 0.00411351 0.00431279 0.00451315 0.00467965 0.00475802 0.00467816 0.00436032 0.00370246 0.00248157 ) ; boundaryField { floor { type calculated; value nonuniform List<scalar> 36 ( 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -4.07861e-06 -1.17396e-05 -1.65227e-05 -1.63692e-05 -1.52158e-05 -1.65925e-05 -1.71691e-05 -2.28928e-06 -4.32274e-06 -4.64459e-06 -5.65055e-06 -4.19655e-06 -8.55256e-06 -1.12923e-05 -1.14102e-05 -1.35757e-05 -1.32929e-05 ) ; } ceiling { type calculated; value nonuniform List<scalar> 43 ( 1.77816e-06 8.7991e-07 7.56456e-07 3.35413e-06 4.33235e-06 4.75684e-06 5.07296e-06 5.34992e-06 5.6104e-06 5.86266e-06 6.10053e-06 6.32312e-06 6.53523e-06 6.73798e-06 6.93007e-06 7.10799e-06 7.26609e-06 7.39692e-06 7.49192e-06 7.54249e-06 7.54114e-06 7.48222e-06 7.36213e-06 7.17402e-06 6.91281e-06 6.57371e-06 6.14243e-06 5.59937e-06 4.9297e-06 4.14079e-06 3.27448e-06 2.39994e-06 1.58894e-06 8.94488e-07 3.45259e-07 -9.46352e-08 -4.93001e-07 -8.65416e-07 -1.23165e-06 -1.12057e-06 8.65848e-06 5.74828e-06 2.41328e-07 ) ; } sWall { type calculated; value uniform -0.000198176; } nWall { type calculated; value nonuniform List<scalar> 6(-4.88675e-05 -5.16911e-05 -6.03517e-05 -6.61763e-05 -7.90731e-05 -0.000102752); } sideWalls { type empty; value nonuniform 0(); } glass1 { type calculated; value nonuniform List<scalar> 9(-6.46447e-05 -0.000166549 -0.000246594 -0.000311829 -0.000367245 -0.000415904 -0.000459598 -0.00051196 -0.000572914); } glass2 { type calculated; value nonuniform List<scalar> 2(-0.000284785 -0.000299431); } sun { type calculated; value uniform 0; } Table_master { type calculated; value nonuniform List<scalar> 9(-1.54604e-07 -1.54716e-07 -1.5474e-07 -1.54765e-07 -1.54804e-07 -1.54833e-07 -1.54796e-07 -1.54691e-07 -1.54514e-07); } Table_slave { type calculated; value nonuniform List<scalar> 9(1.53203e-07 1.53299e-07 1.53405e-07 1.53535e-07 1.53692e-07 1.53873e-07 1.53995e-07 1.53935e-07 1.5375e-07); } inlet { type calculated; value uniform -0.00177382; } outlet { type calculated; value nonuniform List<scalar> 2(0.00483721 0.00129289); } } // ************************************************************************* //
[ "mitsuaki.makino@tryeting.jp" ]
mitsuaki.makino@tryeting.jp
28dae2c2dd1ddcf4901e12f4700b44ea7d2c5c26
fba6ee80ae03468ad5c6f29c07be4b7f88456e47
/test3503-udp-multicast-recv.cpp
23ee9c0b8d7ae2d12d2ca1945a9a8bf7b6b235c6
[]
no_license
shane0314/testcpp
397df85eaab2244debe000fd366c30037d83b60e
480f70913e6b3939cc4b60b1a543810890b3e317
refs/heads/master
2021-07-09T15:35:37.373116
2020-07-17T09:13:49
2020-07-17T09:13:49
163,728,721
0
0
null
null
null
null
UTF-8
C++
false
false
2,519
cpp
#include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <netdb.h> #include <errno.h> #include <iostream> #include <unistd.h> using namespace std; int main( int argc, char* args[] ) { char mcast_ip[20]; char source_ip[20]; char local_ip[20]; if( argc < 5 ) { std::cout << "Usage : ./t3503 <mcast-ip> <mcast-port> <source-ip> <local-ip>" << std::endl; exit(1); } strcpy( mcast_ip, args[1] ); int mcast_port = atoi( args[2] ); strcpy( source_ip, args[3] ); strcpy( local_ip, args[4] ); //int mcast_port = 11111; //strcpy(mcast_ip, "231.1.1.1"); char recvmsg[256]; struct sockaddr_in mcast_addr; //group address //struct sockaddr_in local_addr; //local address struct ip_mreq_source mreq; socklen_t addr_len = sizeof(mcast_addr); int socket_fd; socket_fd = socket(AF_INET, SOCK_DGRAM, 0); if( socket_fd < 0 ) { perror("socket multicast failed"); exit(1); } std::cout << "socket success!" << std::endl; //allow multiple sockets to use the same PORT number u_int yes; if( setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)) < 0 ) { perror("Reusing ADDR failed"); exit(1); } memset( &mcast_addr, 0, sizeof(struct sockaddr_in) ); mcast_addr.sin_family = AF_INET; mcast_addr.sin_port = htons( mcast_port ); mcast_addr.sin_addr.s_addr = inet_addr( mcast_ip ); /* memset( &local_addr, 0, sizeof(local_addr) ); local_addr.sin_family = AF_INET; local_addr.sin_port = htons( mcast_port ); local_addr.sin_addr.s_addr = mcast_ip; */ if( bind(socket_fd, (struct sockaddr*)&mcast_addr, sizeof(mcast_addr)) < 0 ) { perror("bind mulitcast failed!"); exit(1); } std::cout << "bind multicast success!" << std::endl; mreq.imr_multiaddr.s_addr = inet_addr(mcast_ip); mreq.imr_interface.s_addr = inet_addr(local_ip); mreq.imr_sourceaddr.s_addr = inet_addr(source_ip); if( setsockopt( socket_fd, IPPROTO_IP, IP_ADD_SOURCE_MEMBERSHIP, &mreq, sizeof(mreq) ) < 0 ) { std:cerr << ( "setsockopt multicast failed!") << std::endl; exit(1); } std::cout << "setsockopt multicast successed!" << std::endl; while(1) { /*recv*/ memset(recvmsg, 0, sizeof(recvmsg) ); auto n = recvfrom( socket_fd, recvmsg, sizeof(recvmsg)-1, 0, (struct sockaddr*)&mcast_addr, &addr_len ); if( n < 0 ) { std::cerr << "recvfrom failed!" << std::endl; exit(4); } else { recvmsg[n] = 0; std::cout << "received msg:" << recvmsg << std::endl; } } }
[ "swang@shancetech.com" ]
swang@shancetech.com
50ce4bd685384d1dd382b0aa21140eecb27dc430
70ae02b374982343bbb330bff9643c99b7aa9689
/cpp/C++PrimerPlus/chapter17/PE/17-5main.cpp
31bb689f7e84eeabd1ab63a8cce71ff5c200274e
[]
no_license
Brightlpf/MY-LEARN
370cf018bb63d9a79a04da14b4650db41c386e34
f43a77c89c680d5a212fb158b94a0fb403aaf027
refs/heads/master
2021-05-04T08:39:22.770559
2016-10-11T04:03:12
2016-10-11T04:03:12
70,401,627
0
0
null
null
null
null
UTF-8
C++
false
false
2,685
cpp
#include <cstdlib> #include "17-5.h" void showMenu(); const int MAX = 10; const char * pdata = "employee.dat"; int main() { using namespace std; abstr_emp * pemp[MAX]; int emptype; int emp_count = 0; ifstream fin(pdata); if(fin.is_open()) { for(int i = 0; i < MAX; i++) { fin >> emptype; if(fin.bad()) { cerr << "read file type wrong" << endl; exit(1); } if(!fin.eof()) { /*enum emp_type{EMPLYEE, MANAGER, FINK, HIGHFINK};*/ switch(emptype) { case EMPLYEE: pemp[i] = new employee; pemp[i]->GetAll(fin); break; case MANAGER: pemp[i] = new manager; pemp[i]->GetAll(fin); break; case FINK: pemp[i] = new fink; pemp[i]->GetAll(fin); break; case HIGHFINK: pemp[i] = new highfink; pemp[i]->GetAll(fin); break; default: cout << "unkonwn type." << endl; exit(1); } emp_count++; } else { fin.clear(); break; } } for(int i = 0; i < emp_count; i++) pemp[i]->ShowAll(); fin.close(); } ofstream fout; fout.open(pdata, ios_base::out | ios_base::app); if(!fout.is_open()) { cerr << "open file failed." << endl; exit(1); } while(emp_count != MAX) { showMenu(); char choice; cin.get(choice); while(cin.get() != '\n') continue; switch(choice) { case 'e': pemp[emp_count] = new employee; pemp[emp_count]->SetAll(); pemp[emp_count]->WriteAll(fout); emp_count++; break; case 'm': pemp[emp_count] = new manager; pemp[emp_count]->SetAll(); pemp[emp_count]->WriteAll(fout); emp_count++; break; case 'f': pemp[emp_count] = new fink; pemp[emp_count]->SetAll(); pemp[emp_count]->WriteAll(fout); emp_count++; break; case 'h': pemp[emp_count] = new highfink; pemp[emp_count]->SetAll(); pemp[emp_count]->WriteAll(fout); emp_count++; break; case 'q': cout << "Bye.\n"; return 0; default: cout << "bad choice" << endl; continue; } cout << "Now info: " << endl; for(int i = 0; i < emp_count; i++) pemp[i]->ShowAll(); } cout << "The max number of employeeer is " << MAX << endl; cout << "Bye.\n"; return 0; } void showMenu() { std::cout << "*******************menu*******************" << std::endl; std::cout << "e: add a employee" << std::endl; std::cout << "f: add a fink" << std::endl; std::cout << "m: add a manager" << std::endl; std::cout << "h: add a high fink" << std::endl; std::cout << "q: to quit" << std::endl; std::cout << "*******************menu*******************" << std::endl; std::cout << "Please make your choice: " ; }
[ "lipengfei2@konka.com" ]
lipengfei2@konka.com
eb4b6761eb680212dc3e1f46d8e4901bf32b0f24
897868d4960eee6e728597e4ec5576aa03064785
/llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp
3958b7ba0f505139e4eed52d2bc2a9119cec482c
[ "NCSA", "MIT" ]
permissive
martell/ellcc
ab95d98c6023a23402a474044730db125349c843
b144e161b5f70da528ae64329f27e4dfab489e5a
refs/heads/master
2021-04-26T11:49:19.551929
2016-10-05T09:21:00
2016-10-05T09:21:00
70,063,491
2
1
NOASSERTION
2020-03-07T21:58:00
2016-10-05T13:32:53
null
UTF-8
C++
false
false
143,362
cpp
//===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This implements the SelectionDAGISel class. // //===----------------------------------------------------------------------===// #include "llvm/CodeGen/SelectionDAG.h" #include "ScheduleDAGSDNodes.h" #include "SelectionDAGBuilder.h" #include "llvm/ADT/PostOrderIterator.h" #include "llvm/ADT/Statistic.h" #include "llvm/Analysis/AliasAnalysis.h" #include "llvm/Analysis/BranchProbabilityInfo.h" #include "llvm/Analysis/CFG.h" #include "llvm/Analysis/EHPersonalities.h" #include "llvm/Analysis/TargetLibraryInfo.h" #include "llvm/CodeGen/FastISel.h" #include "llvm/CodeGen/FunctionLoweringInfo.h" #include "llvm/CodeGen/GCMetadata.h" #include "llvm/CodeGen/GCStrategy.h" #include "llvm/CodeGen/MachineFrameInfo.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/MachineInstrBuilder.h" #include "llvm/CodeGen/MachineModuleInfo.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/CodeGen/ScheduleHazardRecognizer.h" #include "llvm/CodeGen/SchedulerRegistry.h" #include "llvm/CodeGen/SelectionDAGISel.h" #include "llvm/CodeGen/StackProtector.h" #include "llvm/CodeGen/WinEHFuncInfo.h" #include "llvm/IR/Constants.h" #include "llvm/IR/DebugInfo.h" #include "llvm/IR/Function.h" #include "llvm/IR/InlineAsm.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/IntrinsicInst.h" #include "llvm/IR/Intrinsics.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Module.h" #include "llvm/MC/MCAsmInfo.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/Debug.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/Timer.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Target/TargetInstrInfo.h" #include "llvm/Target/TargetIntrinsicInfo.h" #include "llvm/Target/TargetLowering.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetOptions.h" #include "llvm/Target/TargetRegisterInfo.h" #include "llvm/Target/TargetSubtargetInfo.h" #include "llvm/Transforms/Utils/BasicBlockUtils.h" #include <algorithm> using namespace llvm; #define DEBUG_TYPE "isel" STATISTIC(NumFastIselFailures, "Number of instructions fast isel failed on"); STATISTIC(NumFastIselSuccess, "Number of instructions fast isel selected"); STATISTIC(NumFastIselBlocks, "Number of blocks selected entirely by fast isel"); STATISTIC(NumDAGBlocks, "Number of blocks selected using DAG"); STATISTIC(NumDAGIselRetries,"Number of times dag isel has to try another path"); STATISTIC(NumEntryBlocks, "Number of entry blocks encountered"); STATISTIC(NumFastIselFailLowerArguments, "Number of entry blocks where fast isel failed to lower arguments"); #ifndef NDEBUG static cl::opt<bool> EnableFastISelVerbose2("fast-isel-verbose2", cl::Hidden, cl::desc("Enable extra verbose messages in the \"fast\" " "instruction selector")); // Terminators STATISTIC(NumFastIselFailRet,"Fast isel fails on Ret"); STATISTIC(NumFastIselFailBr,"Fast isel fails on Br"); STATISTIC(NumFastIselFailSwitch,"Fast isel fails on Switch"); STATISTIC(NumFastIselFailIndirectBr,"Fast isel fails on IndirectBr"); STATISTIC(NumFastIselFailInvoke,"Fast isel fails on Invoke"); STATISTIC(NumFastIselFailResume,"Fast isel fails on Resume"); STATISTIC(NumFastIselFailUnreachable,"Fast isel fails on Unreachable"); // Standard binary operators... STATISTIC(NumFastIselFailAdd,"Fast isel fails on Add"); STATISTIC(NumFastIselFailFAdd,"Fast isel fails on FAdd"); STATISTIC(NumFastIselFailSub,"Fast isel fails on Sub"); STATISTIC(NumFastIselFailFSub,"Fast isel fails on FSub"); STATISTIC(NumFastIselFailMul,"Fast isel fails on Mul"); STATISTIC(NumFastIselFailFMul,"Fast isel fails on FMul"); STATISTIC(NumFastIselFailUDiv,"Fast isel fails on UDiv"); STATISTIC(NumFastIselFailSDiv,"Fast isel fails on SDiv"); STATISTIC(NumFastIselFailFDiv,"Fast isel fails on FDiv"); STATISTIC(NumFastIselFailURem,"Fast isel fails on URem"); STATISTIC(NumFastIselFailSRem,"Fast isel fails on SRem"); STATISTIC(NumFastIselFailFRem,"Fast isel fails on FRem"); // Logical operators... STATISTIC(NumFastIselFailAnd,"Fast isel fails on And"); STATISTIC(NumFastIselFailOr,"Fast isel fails on Or"); STATISTIC(NumFastIselFailXor,"Fast isel fails on Xor"); // Memory instructions... STATISTIC(NumFastIselFailAlloca,"Fast isel fails on Alloca"); STATISTIC(NumFastIselFailLoad,"Fast isel fails on Load"); STATISTIC(NumFastIselFailStore,"Fast isel fails on Store"); STATISTIC(NumFastIselFailAtomicCmpXchg,"Fast isel fails on AtomicCmpXchg"); STATISTIC(NumFastIselFailAtomicRMW,"Fast isel fails on AtomicRWM"); STATISTIC(NumFastIselFailFence,"Fast isel fails on Frence"); STATISTIC(NumFastIselFailGetElementPtr,"Fast isel fails on GetElementPtr"); // Convert instructions... STATISTIC(NumFastIselFailTrunc,"Fast isel fails on Trunc"); STATISTIC(NumFastIselFailZExt,"Fast isel fails on ZExt"); STATISTIC(NumFastIselFailSExt,"Fast isel fails on SExt"); STATISTIC(NumFastIselFailFPTrunc,"Fast isel fails on FPTrunc"); STATISTIC(NumFastIselFailFPExt,"Fast isel fails on FPExt"); STATISTIC(NumFastIselFailFPToUI,"Fast isel fails on FPToUI"); STATISTIC(NumFastIselFailFPToSI,"Fast isel fails on FPToSI"); STATISTIC(NumFastIselFailUIToFP,"Fast isel fails on UIToFP"); STATISTIC(NumFastIselFailSIToFP,"Fast isel fails on SIToFP"); STATISTIC(NumFastIselFailIntToPtr,"Fast isel fails on IntToPtr"); STATISTIC(NumFastIselFailPtrToInt,"Fast isel fails on PtrToInt"); STATISTIC(NumFastIselFailBitCast,"Fast isel fails on BitCast"); // Other instructions... STATISTIC(NumFastIselFailICmp,"Fast isel fails on ICmp"); STATISTIC(NumFastIselFailFCmp,"Fast isel fails on FCmp"); STATISTIC(NumFastIselFailPHI,"Fast isel fails on PHI"); STATISTIC(NumFastIselFailSelect,"Fast isel fails on Select"); STATISTIC(NumFastIselFailCall,"Fast isel fails on Call"); STATISTIC(NumFastIselFailShl,"Fast isel fails on Shl"); STATISTIC(NumFastIselFailLShr,"Fast isel fails on LShr"); STATISTIC(NumFastIselFailAShr,"Fast isel fails on AShr"); STATISTIC(NumFastIselFailVAArg,"Fast isel fails on VAArg"); STATISTIC(NumFastIselFailExtractElement,"Fast isel fails on ExtractElement"); STATISTIC(NumFastIselFailInsertElement,"Fast isel fails on InsertElement"); STATISTIC(NumFastIselFailShuffleVector,"Fast isel fails on ShuffleVector"); STATISTIC(NumFastIselFailExtractValue,"Fast isel fails on ExtractValue"); STATISTIC(NumFastIselFailInsertValue,"Fast isel fails on InsertValue"); STATISTIC(NumFastIselFailLandingPad,"Fast isel fails on LandingPad"); // Intrinsic instructions... STATISTIC(NumFastIselFailIntrinsicCall, "Fast isel fails on Intrinsic call"); STATISTIC(NumFastIselFailSAddWithOverflow, "Fast isel fails on sadd.with.overflow"); STATISTIC(NumFastIselFailUAddWithOverflow, "Fast isel fails on uadd.with.overflow"); STATISTIC(NumFastIselFailSSubWithOverflow, "Fast isel fails on ssub.with.overflow"); STATISTIC(NumFastIselFailUSubWithOverflow, "Fast isel fails on usub.with.overflow"); STATISTIC(NumFastIselFailSMulWithOverflow, "Fast isel fails on smul.with.overflow"); STATISTIC(NumFastIselFailUMulWithOverflow, "Fast isel fails on umul.with.overflow"); STATISTIC(NumFastIselFailFrameaddress, "Fast isel fails on Frameaddress"); STATISTIC(NumFastIselFailSqrt, "Fast isel fails on sqrt call"); STATISTIC(NumFastIselFailStackMap, "Fast isel fails on StackMap call"); STATISTIC(NumFastIselFailPatchPoint, "Fast isel fails on PatchPoint call"); #endif static cl::opt<bool> EnableFastISelVerbose("fast-isel-verbose", cl::Hidden, cl::desc("Enable verbose messages in the \"fast\" " "instruction selector")); static cl::opt<int> EnableFastISelAbort( "fast-isel-abort", cl::Hidden, cl::desc("Enable abort calls when \"fast\" instruction selection " "fails to lower an instruction: 0 disable the abort, 1 will " "abort but for args, calls and terminators, 2 will also " "abort for argument lowering, and 3 will never fallback " "to SelectionDAG.")); static cl::opt<bool> UseMBPI("use-mbpi", cl::desc("use Machine Branch Probability Info"), cl::init(true), cl::Hidden); #ifndef NDEBUG static cl::opt<std::string> FilterDAGBasicBlockName("filter-view-dags", cl::Hidden, cl::desc("Only display the basic block whose name " "matches this for all view-*-dags options")); static cl::opt<bool> ViewDAGCombine1("view-dag-combine1-dags", cl::Hidden, cl::desc("Pop up a window to show dags before the first " "dag combine pass")); static cl::opt<bool> ViewLegalizeTypesDAGs("view-legalize-types-dags", cl::Hidden, cl::desc("Pop up a window to show dags before legalize types")); static cl::opt<bool> ViewLegalizeDAGs("view-legalize-dags", cl::Hidden, cl::desc("Pop up a window to show dags before legalize")); static cl::opt<bool> ViewDAGCombine2("view-dag-combine2-dags", cl::Hidden, cl::desc("Pop up a window to show dags before the second " "dag combine pass")); static cl::opt<bool> ViewDAGCombineLT("view-dag-combine-lt-dags", cl::Hidden, cl::desc("Pop up a window to show dags before the post legalize types" " dag combine pass")); static cl::opt<bool> ViewISelDAGs("view-isel-dags", cl::Hidden, cl::desc("Pop up a window to show isel dags as they are selected")); static cl::opt<bool> ViewSchedDAGs("view-sched-dags", cl::Hidden, cl::desc("Pop up a window to show sched dags as they are processed")); static cl::opt<bool> ViewSUnitDAGs("view-sunit-dags", cl::Hidden, cl::desc("Pop up a window to show SUnit dags after they are processed")); #else static const bool ViewDAGCombine1 = false, ViewLegalizeTypesDAGs = false, ViewLegalizeDAGs = false, ViewDAGCombine2 = false, ViewDAGCombineLT = false, ViewISelDAGs = false, ViewSchedDAGs = false, ViewSUnitDAGs = false; #endif //===---------------------------------------------------------------------===// /// /// RegisterScheduler class - Track the registration of instruction schedulers. /// //===---------------------------------------------------------------------===// MachinePassRegistry RegisterScheduler::Registry; //===---------------------------------------------------------------------===// /// /// ISHeuristic command line option for instruction schedulers. /// //===---------------------------------------------------------------------===// static cl::opt<RegisterScheduler::FunctionPassCtor, false, RegisterPassParser<RegisterScheduler> > ISHeuristic("pre-RA-sched", cl::init(&createDefaultScheduler), cl::Hidden, cl::desc("Instruction schedulers available (before register" " allocation):")); static RegisterScheduler defaultListDAGScheduler("default", "Best scheduler for the target", createDefaultScheduler); namespace llvm { //===--------------------------------------------------------------------===// /// \brief This class is used by SelectionDAGISel to temporarily override /// the optimization level on a per-function basis. class OptLevelChanger { SelectionDAGISel &IS; CodeGenOpt::Level SavedOptLevel; bool SavedFastISel; public: OptLevelChanger(SelectionDAGISel &ISel, CodeGenOpt::Level NewOptLevel) : IS(ISel) { SavedOptLevel = IS.OptLevel; if (NewOptLevel == SavedOptLevel) return; IS.OptLevel = NewOptLevel; IS.TM.setOptLevel(NewOptLevel); DEBUG(dbgs() << "\nChanging optimization level for Function " << IS.MF->getFunction()->getName() << "\n"); DEBUG(dbgs() << "\tBefore: -O" << SavedOptLevel << " ; After: -O" << NewOptLevel << "\n"); SavedFastISel = IS.TM.Options.EnableFastISel; if (NewOptLevel == CodeGenOpt::None) { IS.TM.setFastISel(IS.TM.getO0WantsFastISel()); DEBUG(dbgs() << "\tFastISel is " << (IS.TM.Options.EnableFastISel ? "enabled" : "disabled") << "\n"); } } ~OptLevelChanger() { if (IS.OptLevel == SavedOptLevel) return; DEBUG(dbgs() << "\nRestoring optimization level for Function " << IS.MF->getFunction()->getName() << "\n"); DEBUG(dbgs() << "\tBefore: -O" << IS.OptLevel << " ; After: -O" << SavedOptLevel << "\n"); IS.OptLevel = SavedOptLevel; IS.TM.setOptLevel(SavedOptLevel); IS.TM.setFastISel(SavedFastISel); } }; //===--------------------------------------------------------------------===// /// createDefaultScheduler - This creates an instruction scheduler appropriate /// for the target. ScheduleDAGSDNodes* createDefaultScheduler(SelectionDAGISel *IS, CodeGenOpt::Level OptLevel) { const TargetLowering *TLI = IS->TLI; const TargetSubtargetInfo &ST = IS->MF->getSubtarget(); // Try first to see if the Target has its own way of selecting a scheduler if (auto *SchedulerCtor = ST.getDAGScheduler(OptLevel)) { return SchedulerCtor(IS, OptLevel); } if (OptLevel == CodeGenOpt::None || (ST.enableMachineScheduler() && ST.enableMachineSchedDefaultSched()) || TLI->getSchedulingPreference() == Sched::Source) return createSourceListDAGScheduler(IS, OptLevel); if (TLI->getSchedulingPreference() == Sched::RegPressure) return createBURRListDAGScheduler(IS, OptLevel); if (TLI->getSchedulingPreference() == Sched::Hybrid) return createHybridListDAGScheduler(IS, OptLevel); if (TLI->getSchedulingPreference() == Sched::VLIW) return createVLIWDAGScheduler(IS, OptLevel); assert(TLI->getSchedulingPreference() == Sched::ILP && "Unknown sched type!"); return createILPListDAGScheduler(IS, OptLevel); } } // end namespace llvm // EmitInstrWithCustomInserter - This method should be implemented by targets // that mark instructions with the 'usesCustomInserter' flag. These // instructions are special in various ways, which require special support to // insert. The specified MachineInstr is created but not inserted into any // basic blocks, and this method is called to expand it into a sequence of // instructions, potentially also creating new basic blocks and control flow. // When new basic blocks are inserted and the edges from MBB to its successors // are modified, the method should insert pairs of <OldSucc, NewSucc> into the // DenseMap. MachineBasicBlock * TargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, MachineBasicBlock *MBB) const { #ifndef NDEBUG dbgs() << "If a target marks an instruction with " "'usesCustomInserter', it must implement " "TargetLowering::EmitInstrWithCustomInserter!"; #endif llvm_unreachable(nullptr); } void TargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, SDNode *Node) const { assert(!MI.hasPostISelHook() && "If a target marks an instruction with 'hasPostISelHook', " "it must implement TargetLowering::AdjustInstrPostInstrSelection!"); } //===----------------------------------------------------------------------===// // SelectionDAGISel code //===----------------------------------------------------------------------===// SelectionDAGISel::SelectionDAGISel(TargetMachine &tm, CodeGenOpt::Level OL) : MachineFunctionPass(ID), TM(tm), FuncInfo(new FunctionLoweringInfo()), CurDAG(new SelectionDAG(tm, OL)), SDB(new SelectionDAGBuilder(*CurDAG, *FuncInfo, OL)), GFI(), OptLevel(OL), DAGSize(0) { initializeGCModuleInfoPass(*PassRegistry::getPassRegistry()); initializeBranchProbabilityInfoWrapperPassPass( *PassRegistry::getPassRegistry()); initializeAAResultsWrapperPassPass(*PassRegistry::getPassRegistry()); initializeTargetLibraryInfoWrapperPassPass( *PassRegistry::getPassRegistry()); } SelectionDAGISel::~SelectionDAGISel() { delete SDB; delete CurDAG; delete FuncInfo; } void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const { AU.addRequired<AAResultsWrapperPass>(); AU.addRequired<GCModuleInfo>(); AU.addRequired<StackProtector>(); AU.addPreserved<StackProtector>(); AU.addPreserved<GCModuleInfo>(); AU.addRequired<TargetLibraryInfoWrapperPass>(); if (UseMBPI && OptLevel != CodeGenOpt::None) AU.addRequired<BranchProbabilityInfoWrapperPass>(); MachineFunctionPass::getAnalysisUsage(AU); } /// SplitCriticalSideEffectEdges - Look for critical edges with a PHI value that /// may trap on it. In this case we have to split the edge so that the path /// through the predecessor block that doesn't go to the phi block doesn't /// execute the possibly trapping instruction. /// /// This is required for correctness, so it must be done at -O0. /// static void SplitCriticalSideEffectEdges(Function &Fn) { // Loop for blocks with phi nodes. for (BasicBlock &BB : Fn) { PHINode *PN = dyn_cast<PHINode>(BB.begin()); if (!PN) continue; ReprocessBlock: // For each block with a PHI node, check to see if any of the input values // are potentially trapping constant expressions. Constant expressions are // the only potentially trapping value that can occur as the argument to a // PHI. for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I)); ++I) for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { ConstantExpr *CE = dyn_cast<ConstantExpr>(PN->getIncomingValue(i)); if (!CE || !CE->canTrap()) continue; // The only case we have to worry about is when the edge is critical. // Since this block has a PHI Node, we assume it has multiple input // edges: check to see if the pred has multiple successors. BasicBlock *Pred = PN->getIncomingBlock(i); if (Pred->getTerminator()->getNumSuccessors() == 1) continue; // Okay, we have to split this edge. SplitCriticalEdge( Pred->getTerminator(), GetSuccessorNumber(Pred, &BB), CriticalEdgeSplittingOptions().setMergeIdenticalEdges()); goto ReprocessBlock; } } } bool SelectionDAGISel::runOnMachineFunction(MachineFunction &mf) { // If we already selected that function, we do not need to run SDISel. if (mf.getProperties().hasProperty( MachineFunctionProperties::Property::Selected)) return false; // Do some sanity-checking on the command-line options. assert((!EnableFastISelVerbose || TM.Options.EnableFastISel) && "-fast-isel-verbose requires -fast-isel"); assert((!EnableFastISelAbort || TM.Options.EnableFastISel) && "-fast-isel-abort > 0 requires -fast-isel"); const Function &Fn = *mf.getFunction(); MF = &mf; // Reset the target options before resetting the optimization // level below. // FIXME: This is a horrible hack and should be processed via // codegen looking at the optimization level explicitly when // it wants to look at it. TM.resetTargetOptions(Fn); // Reset OptLevel to None for optnone functions. CodeGenOpt::Level NewOptLevel = OptLevel; if (OptLevel != CodeGenOpt::None && skipFunction(Fn)) NewOptLevel = CodeGenOpt::None; OptLevelChanger OLC(*this, NewOptLevel); TII = MF->getSubtarget().getInstrInfo(); TLI = MF->getSubtarget().getTargetLowering(); RegInfo = &MF->getRegInfo(); AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); LibInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(); GFI = Fn.hasGC() ? &getAnalysis<GCModuleInfo>().getFunctionInfo(Fn) : nullptr; DEBUG(dbgs() << "\n\n\n=== " << Fn.getName() << "\n"); SplitCriticalSideEffectEdges(const_cast<Function &>(Fn)); CurDAG->init(*MF); FuncInfo->set(Fn, *MF, CurDAG); if (UseMBPI && OptLevel != CodeGenOpt::None) FuncInfo->BPI = &getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI(); else FuncInfo->BPI = nullptr; SDB->init(GFI, *AA, LibInfo); MF->setHasInlineAsm(false); FuncInfo->SplitCSR = false; // We split CSR if the target supports it for the given function // and the function has only return exits. if (OptLevel != CodeGenOpt::None && TLI->supportSplitCSR(MF)) { FuncInfo->SplitCSR = true; // Collect all the return blocks. for (const BasicBlock &BB : Fn) { if (!succ_empty(&BB)) continue; const TerminatorInst *Term = BB.getTerminator(); if (isa<UnreachableInst>(Term) || isa<ReturnInst>(Term)) continue; // Bail out if the exit block is not Return nor Unreachable. FuncInfo->SplitCSR = false; break; } } MachineBasicBlock *EntryMBB = &MF->front(); if (FuncInfo->SplitCSR) // This performs initialization so lowering for SplitCSR will be correct. TLI->initializeSplitCSR(EntryMBB); SelectAllBasicBlocks(Fn); // If the first basic block in the function has live ins that need to be // copied into vregs, emit the copies into the top of the block before // emitting the code for the block. const TargetRegisterInfo &TRI = *MF->getSubtarget().getRegisterInfo(); RegInfo->EmitLiveInCopies(EntryMBB, TRI, *TII); // Insert copies in the entry block and the return blocks. if (FuncInfo->SplitCSR) { SmallVector<MachineBasicBlock*, 4> Returns; // Collect all the return blocks. for (MachineBasicBlock &MBB : mf) { if (!MBB.succ_empty()) continue; MachineBasicBlock::iterator Term = MBB.getFirstTerminator(); if (Term != MBB.end() && Term->isReturn()) { Returns.push_back(&MBB); continue; } } TLI->insertCopiesSplitCSR(EntryMBB, Returns); } DenseMap<unsigned, unsigned> LiveInMap; if (!FuncInfo->ArgDbgValues.empty()) for (MachineRegisterInfo::livein_iterator LI = RegInfo->livein_begin(), E = RegInfo->livein_end(); LI != E; ++LI) if (LI->second) LiveInMap.insert(std::make_pair(LI->first, LI->second)); // Insert DBG_VALUE instructions for function arguments to the entry block. for (unsigned i = 0, e = FuncInfo->ArgDbgValues.size(); i != e; ++i) { MachineInstr *MI = FuncInfo->ArgDbgValues[e-i-1]; bool hasFI = MI->getOperand(0).isFI(); unsigned Reg = hasFI ? TRI.getFrameRegister(*MF) : MI->getOperand(0).getReg(); if (TargetRegisterInfo::isPhysicalRegister(Reg)) EntryMBB->insert(EntryMBB->begin(), MI); else { MachineInstr *Def = RegInfo->getVRegDef(Reg); if (Def) { MachineBasicBlock::iterator InsertPos = Def; // FIXME: VR def may not be in entry block. Def->getParent()->insert(std::next(InsertPos), MI); } else DEBUG(dbgs() << "Dropping debug info for dead vreg" << TargetRegisterInfo::virtReg2Index(Reg) << "\n"); } // If Reg is live-in then update debug info to track its copy in a vreg. DenseMap<unsigned, unsigned>::iterator LDI = LiveInMap.find(Reg); if (LDI != LiveInMap.end()) { assert(!hasFI && "There's no handling of frame pointer updating here yet " "- add if needed"); MachineInstr *Def = RegInfo->getVRegDef(LDI->second); MachineBasicBlock::iterator InsertPos = Def; const MDNode *Variable = MI->getDebugVariable(); const MDNode *Expr = MI->getDebugExpression(); DebugLoc DL = MI->getDebugLoc(); bool IsIndirect = MI->isIndirectDebugValue(); unsigned Offset = IsIndirect ? MI->getOperand(1).getImm() : 0; assert(cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(DL) && "Expected inlined-at fields to agree"); // Def is never a terminator here, so it is ok to increment InsertPos. BuildMI(*EntryMBB, ++InsertPos, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect, LDI->second, Offset, Variable, Expr); // If this vreg is directly copied into an exported register then // that COPY instructions also need DBG_VALUE, if it is the only // user of LDI->second. MachineInstr *CopyUseMI = nullptr; for (MachineRegisterInfo::use_instr_iterator UI = RegInfo->use_instr_begin(LDI->second), E = RegInfo->use_instr_end(); UI != E; ) { MachineInstr *UseMI = &*(UI++); if (UseMI->isDebugValue()) continue; if (UseMI->isCopy() && !CopyUseMI && UseMI->getParent() == EntryMBB) { CopyUseMI = UseMI; continue; } // Otherwise this is another use or second copy use. CopyUseMI = nullptr; break; } if (CopyUseMI) { // Use MI's debug location, which describes where Variable was // declared, rather than whatever is attached to CopyUseMI. MachineInstr *NewMI = BuildMI(*MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect, CopyUseMI->getOperand(0).getReg(), Offset, Variable, Expr); MachineBasicBlock::iterator Pos = CopyUseMI; EntryMBB->insertAfter(Pos, NewMI); } } } // Determine if there are any calls in this machine function. MachineFrameInfo &MFI = MF->getFrameInfo(); for (const auto &MBB : *MF) { if (MFI.hasCalls() && MF->hasInlineAsm()) break; for (const auto &MI : MBB) { const MCInstrDesc &MCID = TII->get(MI.getOpcode()); if ((MCID.isCall() && !MCID.isReturn()) || MI.isStackAligningInlineAsm()) { MFI.setHasCalls(true); } if (MI.isInlineAsm()) { MF->setHasInlineAsm(true); } } } // Determine if there is a call to setjmp in the machine function. MF->setExposesReturnsTwice(Fn.callsFunctionThatReturnsTwice()); // Replace forward-declared registers with the registers containing // the desired value. MachineRegisterInfo &MRI = MF->getRegInfo(); for (DenseMap<unsigned, unsigned>::iterator I = FuncInfo->RegFixups.begin(), E = FuncInfo->RegFixups.end(); I != E; ++I) { unsigned From = I->first; unsigned To = I->second; // If To is also scheduled to be replaced, find what its ultimate // replacement is. for (;;) { DenseMap<unsigned, unsigned>::iterator J = FuncInfo->RegFixups.find(To); if (J == E) break; To = J->second; } // Make sure the new register has a sufficiently constrained register class. if (TargetRegisterInfo::isVirtualRegister(From) && TargetRegisterInfo::isVirtualRegister(To)) MRI.constrainRegClass(To, MRI.getRegClass(From)); // Replace it. // Replacing one register with another won't touch the kill flags. // We need to conservatively clear the kill flags as a kill on the old // register might dominate existing uses of the new register. if (!MRI.use_empty(To)) MRI.clearKillFlags(From); MRI.replaceRegWith(From, To); } if (TLI->hasCopyImplyingStackAdjustment(MF)) MFI.setHasCopyImplyingStackAdjustment(true); // Freeze the set of reserved registers now that MachineFrameInfo has been // set up. All the information required by getReservedRegs() should be // available now. MRI.freezeReservedRegs(*MF); // Release function-specific state. SDB and CurDAG are already cleared // at this point. FuncInfo->clear(); DEBUG(dbgs() << "*** MachineFunction at end of ISel ***\n"); DEBUG(MF->print(dbgs())); return true; } void SelectionDAGISel::SelectBasicBlock(BasicBlock::const_iterator Begin, BasicBlock::const_iterator End, bool &HadTailCall) { // Lower the instructions. If a call is emitted as a tail call, cease emitting // nodes for this block. for (BasicBlock::const_iterator I = Begin; I != End && !SDB->HasTailCall; ++I) SDB->visit(*I); // Make sure the root of the DAG is up-to-date. CurDAG->setRoot(SDB->getControlRoot()); HadTailCall = SDB->HasTailCall; SDB->clear(); // Final step, emit the lowered DAG as machine code. CodeGenAndEmitDAG(); } void SelectionDAGISel::ComputeLiveOutVRegInfo() { SmallPtrSet<SDNode*, 16> VisitedNodes; SmallVector<SDNode*, 128> Worklist; Worklist.push_back(CurDAG->getRoot().getNode()); APInt KnownZero; APInt KnownOne; do { SDNode *N = Worklist.pop_back_val(); // If we've already seen this node, ignore it. if (!VisitedNodes.insert(N).second) continue; // Otherwise, add all chain operands to the worklist. for (const SDValue &Op : N->op_values()) if (Op.getValueType() == MVT::Other) Worklist.push_back(Op.getNode()); // If this is a CopyToReg with a vreg dest, process it. if (N->getOpcode() != ISD::CopyToReg) continue; unsigned DestReg = cast<RegisterSDNode>(N->getOperand(1))->getReg(); if (!TargetRegisterInfo::isVirtualRegister(DestReg)) continue; // Ignore non-scalar or non-integer values. SDValue Src = N->getOperand(2); EVT SrcVT = Src.getValueType(); if (!SrcVT.isInteger() || SrcVT.isVector()) continue; unsigned NumSignBits = CurDAG->ComputeNumSignBits(Src); CurDAG->computeKnownBits(Src, KnownZero, KnownOne); FuncInfo->AddLiveOutRegInfo(DestReg, NumSignBits, KnownZero, KnownOne); } while (!Worklist.empty()); } void SelectionDAGISel::CodeGenAndEmitDAG() { std::string GroupName; if (TimePassesIsEnabled) GroupName = "Instruction Selection and Scheduling"; std::string BlockName; int BlockNumber = -1; (void)BlockNumber; bool MatchFilterBB = false; (void)MatchFilterBB; #ifndef NDEBUG MatchFilterBB = (FilterDAGBasicBlockName.empty() || FilterDAGBasicBlockName == FuncInfo->MBB->getBasicBlock()->getName().str()); #endif #ifdef NDEBUG if (ViewDAGCombine1 || ViewLegalizeTypesDAGs || ViewLegalizeDAGs || ViewDAGCombine2 || ViewDAGCombineLT || ViewISelDAGs || ViewSchedDAGs || ViewSUnitDAGs) #endif { BlockNumber = FuncInfo->MBB->getNumber(); BlockName = (MF->getName() + ":" + FuncInfo->MBB->getBasicBlock()->getName()).str(); } DEBUG(dbgs() << "Initial selection DAG: BB#" << BlockNumber << " '" << BlockName << "'\n"; CurDAG->dump()); if (ViewDAGCombine1 && MatchFilterBB) CurDAG->viewGraph("dag-combine1 input for " + BlockName); // Run the DAG combiner in pre-legalize mode. { NamedRegionTimer T("DAG Combining 1", GroupName, TimePassesIsEnabled); CurDAG->Combine(BeforeLegalizeTypes, *AA, OptLevel); } DEBUG(dbgs() << "Optimized lowered selection DAG: BB#" << BlockNumber << " '" << BlockName << "'\n"; CurDAG->dump()); // Second step, hack on the DAG until it only uses operations and types that // the target supports. if (ViewLegalizeTypesDAGs && MatchFilterBB) CurDAG->viewGraph("legalize-types input for " + BlockName); bool Changed; { NamedRegionTimer T("Type Legalization", GroupName, TimePassesIsEnabled); Changed = CurDAG->LegalizeTypes(); } DEBUG(dbgs() << "Type-legalized selection DAG: BB#" << BlockNumber << " '" << BlockName << "'\n"; CurDAG->dump()); CurDAG->NewNodesMustHaveLegalTypes = true; if (Changed) { if (ViewDAGCombineLT && MatchFilterBB) CurDAG->viewGraph("dag-combine-lt input for " + BlockName); // Run the DAG combiner in post-type-legalize mode. { NamedRegionTimer T("DAG Combining after legalize types", GroupName, TimePassesIsEnabled); CurDAG->Combine(AfterLegalizeTypes, *AA, OptLevel); } DEBUG(dbgs() << "Optimized type-legalized selection DAG: BB#" << BlockNumber << " '" << BlockName << "'\n"; CurDAG->dump()); } { NamedRegionTimer T("Vector Legalization", GroupName, TimePassesIsEnabled); Changed = CurDAG->LegalizeVectors(); } if (Changed) { { NamedRegionTimer T("Type Legalization 2", GroupName, TimePassesIsEnabled); CurDAG->LegalizeTypes(); } if (ViewDAGCombineLT && MatchFilterBB) CurDAG->viewGraph("dag-combine-lv input for " + BlockName); // Run the DAG combiner in post-type-legalize mode. { NamedRegionTimer T("DAG Combining after legalize vectors", GroupName, TimePassesIsEnabled); CurDAG->Combine(AfterLegalizeVectorOps, *AA, OptLevel); } DEBUG(dbgs() << "Optimized vector-legalized selection DAG: BB#" << BlockNumber << " '" << BlockName << "'\n"; CurDAG->dump()); } if (ViewLegalizeDAGs && MatchFilterBB) CurDAG->viewGraph("legalize input for " + BlockName); { NamedRegionTimer T("DAG Legalization", GroupName, TimePassesIsEnabled); CurDAG->Legalize(); } DEBUG(dbgs() << "Legalized selection DAG: BB#" << BlockNumber << " '" << BlockName << "'\n"; CurDAG->dump()); if (ViewDAGCombine2 && MatchFilterBB) CurDAG->viewGraph("dag-combine2 input for " + BlockName); // Run the DAG combiner in post-legalize mode. { NamedRegionTimer T("DAG Combining 2", GroupName, TimePassesIsEnabled); CurDAG->Combine(AfterLegalizeDAG, *AA, OptLevel); } DEBUG(dbgs() << "Optimized legalized selection DAG: BB#" << BlockNumber << " '" << BlockName << "'\n"; CurDAG->dump()); if (OptLevel != CodeGenOpt::None) ComputeLiveOutVRegInfo(); if (ViewISelDAGs && MatchFilterBB) CurDAG->viewGraph("isel input for " + BlockName); // Third, instruction select all of the operations to machine code, adding the // code to the MachineBasicBlock. { NamedRegionTimer T("Instruction Selection", GroupName, TimePassesIsEnabled); DoInstructionSelection(); } DEBUG(dbgs() << "Selected selection DAG: BB#" << BlockNumber << " '" << BlockName << "'\n"; CurDAG->dump()); if (ViewSchedDAGs && MatchFilterBB) CurDAG->viewGraph("scheduler input for " + BlockName); // Schedule machine code. ScheduleDAGSDNodes *Scheduler = CreateScheduler(); { NamedRegionTimer T("Instruction Scheduling", GroupName, TimePassesIsEnabled); Scheduler->Run(CurDAG, FuncInfo->MBB); } if (ViewSUnitDAGs && MatchFilterBB) Scheduler->viewGraph(); // Emit machine code to BB. This can change 'BB' to the last block being // inserted into. MachineBasicBlock *FirstMBB = FuncInfo->MBB, *LastMBB; { NamedRegionTimer T("Instruction Creation", GroupName, TimePassesIsEnabled); // FuncInfo->InsertPt is passed by reference and set to the end of the // scheduled instructions. LastMBB = FuncInfo->MBB = Scheduler->EmitSchedule(FuncInfo->InsertPt); } // If the block was split, make sure we update any references that are used to // update PHI nodes later on. if (FirstMBB != LastMBB) SDB->UpdateSplitBlock(FirstMBB, LastMBB); // Free the scheduler state. { NamedRegionTimer T("Instruction Scheduling Cleanup", GroupName, TimePassesIsEnabled); delete Scheduler; } // Free the SelectionDAG state, now that we're finished with it. CurDAG->clear(); } namespace { /// ISelUpdater - helper class to handle updates of the instruction selection /// graph. class ISelUpdater : public SelectionDAG::DAGUpdateListener { SelectionDAG::allnodes_iterator &ISelPosition; public: ISelUpdater(SelectionDAG &DAG, SelectionDAG::allnodes_iterator &isp) : SelectionDAG::DAGUpdateListener(DAG), ISelPosition(isp) {} /// NodeDeleted - Handle nodes deleted from the graph. If the node being /// deleted is the current ISelPosition node, update ISelPosition. /// void NodeDeleted(SDNode *N, SDNode *E) override { if (ISelPosition == SelectionDAG::allnodes_iterator(N)) ++ISelPosition; } }; } // end anonymous namespace void SelectionDAGISel::DoInstructionSelection() { DEBUG(dbgs() << "===== Instruction selection begins: BB#" << FuncInfo->MBB->getNumber() << " '" << FuncInfo->MBB->getName() << "'\n"); PreprocessISelDAG(); // Select target instructions for the DAG. { // Number all nodes with a topological order and set DAGSize. DAGSize = CurDAG->AssignTopologicalOrder(); // Create a dummy node (which is not added to allnodes), that adds // a reference to the root node, preventing it from being deleted, // and tracking any changes of the root. HandleSDNode Dummy(CurDAG->getRoot()); SelectionDAG::allnodes_iterator ISelPosition (CurDAG->getRoot().getNode()); ++ISelPosition; // Make sure that ISelPosition gets properly updated when nodes are deleted // in calls made from this function. ISelUpdater ISU(*CurDAG, ISelPosition); // The AllNodes list is now topological-sorted. Visit the // nodes by starting at the end of the list (the root of the // graph) and preceding back toward the beginning (the entry // node). while (ISelPosition != CurDAG->allnodes_begin()) { SDNode *Node = &*--ISelPosition; // Skip dead nodes. DAGCombiner is expected to eliminate all dead nodes, // but there are currently some corner cases that it misses. Also, this // makes it theoretically possible to disable the DAGCombiner. if (Node->use_empty()) continue; Select(Node); } CurDAG->setRoot(Dummy.getValue()); } DEBUG(dbgs() << "===== Instruction selection ends:\n"); PostprocessISelDAG(); } static bool hasExceptionPointerOrCodeUser(const CatchPadInst *CPI) { for (const User *U : CPI->users()) { if (const IntrinsicInst *EHPtrCall = dyn_cast<IntrinsicInst>(U)) { Intrinsic::ID IID = EHPtrCall->getIntrinsicID(); if (IID == Intrinsic::eh_exceptionpointer || IID == Intrinsic::eh_exceptioncode) return true; } } return false; } /// PrepareEHLandingPad - Emit an EH_LABEL, set up live-in registers, and /// do other setup for EH landing-pad blocks. bool SelectionDAGISel::PrepareEHLandingPad() { MachineBasicBlock *MBB = FuncInfo->MBB; const Constant *PersonalityFn = FuncInfo->Fn->getPersonalityFn(); const BasicBlock *LLVMBB = MBB->getBasicBlock(); const TargetRegisterClass *PtrRC = TLI->getRegClassFor(TLI->getPointerTy(CurDAG->getDataLayout())); // Catchpads have one live-in register, which typically holds the exception // pointer or code. if (const auto *CPI = dyn_cast<CatchPadInst>(LLVMBB->getFirstNonPHI())) { if (hasExceptionPointerOrCodeUser(CPI)) { // Get or create the virtual register to hold the pointer or code. Mark // the live in physreg and copy into the vreg. MCPhysReg EHPhysReg = TLI->getExceptionPointerRegister(PersonalityFn); assert(EHPhysReg && "target lacks exception pointer register"); MBB->addLiveIn(EHPhysReg); unsigned VReg = FuncInfo->getCatchPadExceptionPointerVReg(CPI, PtrRC); BuildMI(*MBB, FuncInfo->InsertPt, SDB->getCurDebugLoc(), TII->get(TargetOpcode::COPY), VReg) .addReg(EHPhysReg, RegState::Kill); } return true; } if (!LLVMBB->isLandingPad()) return true; // Add a label to mark the beginning of the landing pad. Deletion of the // landing pad can thus be detected via the MachineModuleInfo. MCSymbol *Label = MF->getMMI().addLandingPad(MBB); // Assign the call site to the landing pad's begin label. MF->getMMI().setCallSiteLandingPad(Label, SDB->LPadToCallSiteMap[MBB]); const MCInstrDesc &II = TII->get(TargetOpcode::EH_LABEL); BuildMI(*MBB, FuncInfo->InsertPt, SDB->getCurDebugLoc(), II) .addSym(Label); // Mark exception register as live in. if (unsigned Reg = TLI->getExceptionPointerRegister(PersonalityFn)) FuncInfo->ExceptionPointerVirtReg = MBB->addLiveIn(Reg, PtrRC); // Mark exception selector register as live in. if (unsigned Reg = TLI->getExceptionSelectorRegister(PersonalityFn)) FuncInfo->ExceptionSelectorVirtReg = MBB->addLiveIn(Reg, PtrRC); return true; } /// isFoldedOrDeadInstruction - Return true if the specified instruction is /// side-effect free and is either dead or folded into a generated instruction. /// Return false if it needs to be emitted. static bool isFoldedOrDeadInstruction(const Instruction *I, FunctionLoweringInfo *FuncInfo) { return !I->mayWriteToMemory() && // Side-effecting instructions aren't folded. !isa<TerminatorInst>(I) && // Terminators aren't folded. !isa<DbgInfoIntrinsic>(I) && // Debug instructions aren't folded. !I->isEHPad() && // EH pad instructions aren't folded. !FuncInfo->isExportedInst(I); // Exported instrs must be computed. } #ifndef NDEBUG // Collect per Instruction statistics for fast-isel misses. Only those // instructions that cause the bail are accounted for. It does not account for // instructions higher in the block. Thus, summing the per instructions stats // will not add up to what is reported by NumFastIselFailures. static void collectFailStats(const Instruction *I) { switch (I->getOpcode()) { default: assert (0 && "<Invalid operator> "); // Terminators case Instruction::Ret: NumFastIselFailRet++; return; case Instruction::Br: NumFastIselFailBr++; return; case Instruction::Switch: NumFastIselFailSwitch++; return; case Instruction::IndirectBr: NumFastIselFailIndirectBr++; return; case Instruction::Invoke: NumFastIselFailInvoke++; return; case Instruction::Resume: NumFastIselFailResume++; return; case Instruction::Unreachable: NumFastIselFailUnreachable++; return; // Standard binary operators... case Instruction::Add: NumFastIselFailAdd++; return; case Instruction::FAdd: NumFastIselFailFAdd++; return; case Instruction::Sub: NumFastIselFailSub++; return; case Instruction::FSub: NumFastIselFailFSub++; return; case Instruction::Mul: NumFastIselFailMul++; return; case Instruction::FMul: NumFastIselFailFMul++; return; case Instruction::UDiv: NumFastIselFailUDiv++; return; case Instruction::SDiv: NumFastIselFailSDiv++; return; case Instruction::FDiv: NumFastIselFailFDiv++; return; case Instruction::URem: NumFastIselFailURem++; return; case Instruction::SRem: NumFastIselFailSRem++; return; case Instruction::FRem: NumFastIselFailFRem++; return; // Logical operators... case Instruction::And: NumFastIselFailAnd++; return; case Instruction::Or: NumFastIselFailOr++; return; case Instruction::Xor: NumFastIselFailXor++; return; // Memory instructions... case Instruction::Alloca: NumFastIselFailAlloca++; return; case Instruction::Load: NumFastIselFailLoad++; return; case Instruction::Store: NumFastIselFailStore++; return; case Instruction::AtomicCmpXchg: NumFastIselFailAtomicCmpXchg++; return; case Instruction::AtomicRMW: NumFastIselFailAtomicRMW++; return; case Instruction::Fence: NumFastIselFailFence++; return; case Instruction::GetElementPtr: NumFastIselFailGetElementPtr++; return; // Convert instructions... case Instruction::Trunc: NumFastIselFailTrunc++; return; case Instruction::ZExt: NumFastIselFailZExt++; return; case Instruction::SExt: NumFastIselFailSExt++; return; case Instruction::FPTrunc: NumFastIselFailFPTrunc++; return; case Instruction::FPExt: NumFastIselFailFPExt++; return; case Instruction::FPToUI: NumFastIselFailFPToUI++; return; case Instruction::FPToSI: NumFastIselFailFPToSI++; return; case Instruction::UIToFP: NumFastIselFailUIToFP++; return; case Instruction::SIToFP: NumFastIselFailSIToFP++; return; case Instruction::IntToPtr: NumFastIselFailIntToPtr++; return; case Instruction::PtrToInt: NumFastIselFailPtrToInt++; return; case Instruction::BitCast: NumFastIselFailBitCast++; return; // Other instructions... case Instruction::ICmp: NumFastIselFailICmp++; return; case Instruction::FCmp: NumFastIselFailFCmp++; return; case Instruction::PHI: NumFastIselFailPHI++; return; case Instruction::Select: NumFastIselFailSelect++; return; case Instruction::Call: { if (auto const *Intrinsic = dyn_cast<IntrinsicInst>(I)) { switch (Intrinsic->getIntrinsicID()) { default: NumFastIselFailIntrinsicCall++; return; case Intrinsic::sadd_with_overflow: NumFastIselFailSAddWithOverflow++; return; case Intrinsic::uadd_with_overflow: NumFastIselFailUAddWithOverflow++; return; case Intrinsic::ssub_with_overflow: NumFastIselFailSSubWithOverflow++; return; case Intrinsic::usub_with_overflow: NumFastIselFailUSubWithOverflow++; return; case Intrinsic::smul_with_overflow: NumFastIselFailSMulWithOverflow++; return; case Intrinsic::umul_with_overflow: NumFastIselFailUMulWithOverflow++; return; case Intrinsic::frameaddress: NumFastIselFailFrameaddress++; return; case Intrinsic::sqrt: NumFastIselFailSqrt++; return; case Intrinsic::experimental_stackmap: NumFastIselFailStackMap++; return; case Intrinsic::experimental_patchpoint_void: // fall-through case Intrinsic::experimental_patchpoint_i64: NumFastIselFailPatchPoint++; return; } } NumFastIselFailCall++; return; } case Instruction::Shl: NumFastIselFailShl++; return; case Instruction::LShr: NumFastIselFailLShr++; return; case Instruction::AShr: NumFastIselFailAShr++; return; case Instruction::VAArg: NumFastIselFailVAArg++; return; case Instruction::ExtractElement: NumFastIselFailExtractElement++; return; case Instruction::InsertElement: NumFastIselFailInsertElement++; return; case Instruction::ShuffleVector: NumFastIselFailShuffleVector++; return; case Instruction::ExtractValue: NumFastIselFailExtractValue++; return; case Instruction::InsertValue: NumFastIselFailInsertValue++; return; case Instruction::LandingPad: NumFastIselFailLandingPad++; return; } } #endif // NDEBUG /// Set up SwiftErrorVals by going through the function. If the function has /// swifterror argument, it will be the first entry. static void setupSwiftErrorVals(const Function &Fn, const TargetLowering *TLI, FunctionLoweringInfo *FuncInfo) { if (!TLI->supportSwiftError()) return; FuncInfo->SwiftErrorVals.clear(); FuncInfo->SwiftErrorMap.clear(); FuncInfo->SwiftErrorWorklist.clear(); // Check if function has a swifterror argument. for (Function::const_arg_iterator AI = Fn.arg_begin(), AE = Fn.arg_end(); AI != AE; ++AI) if (AI->hasSwiftErrorAttr()) FuncInfo->SwiftErrorVals.push_back(&*AI); for (const auto &LLVMBB : Fn) for (const auto &Inst : LLVMBB) { if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(&Inst)) if (Alloca->isSwiftError()) FuncInfo->SwiftErrorVals.push_back(Alloca); } } /// For each basic block, merge incoming swifterror values or simply propagate /// them. The merged results will be saved in SwiftErrorMap. For predecessors /// that are not yet visited, we create virtual registers to hold the swifterror /// values and save them in SwiftErrorWorklist. static void mergeIncomingSwiftErrors(FunctionLoweringInfo *FuncInfo, const TargetLowering *TLI, const TargetInstrInfo *TII, const BasicBlock *LLVMBB, SelectionDAGBuilder *SDB) { if (!TLI->supportSwiftError()) return; // We should only do this when we have swifterror parameter or swifterror // alloc. if (FuncInfo->SwiftErrorVals.empty()) return; // At beginning of a basic block, insert PHI nodes or get the virtual // register from the only predecessor, and update SwiftErrorMap; if one // of the predecessors is not visited, update SwiftErrorWorklist. // At end of a basic block, if a block is in SwiftErrorWorklist, insert copy // to sync up the virtual register assignment. // Always create a virtual register for each swifterror value in entry block. auto &DL = SDB->DAG.getDataLayout(); const TargetRegisterClass *RC = TLI->getRegClassFor(TLI->getPointerTy(DL)); if (pred_begin(LLVMBB) == pred_end(LLVMBB)) { for (unsigned I = 0, E = FuncInfo->SwiftErrorVals.size(); I < E; I++) { unsigned VReg = FuncInfo->MF->getRegInfo().createVirtualRegister(RC); // Assign Undef to Vreg. We construct MI directly to make sure it works // with FastISel. BuildMI(*FuncInfo->MBB, FuncInfo->InsertPt, SDB->getCurDebugLoc(), TII->get(TargetOpcode::IMPLICIT_DEF), VReg); FuncInfo->SwiftErrorMap[FuncInfo->MBB].push_back(VReg); } return; } if (auto *UniquePred = LLVMBB->getUniquePredecessor()) { auto *UniquePredMBB = FuncInfo->MBBMap[UniquePred]; if (!FuncInfo->SwiftErrorMap.count(UniquePredMBB)) { // Update SwiftErrorWorklist with a new virtual register. for (unsigned I = 0, E = FuncInfo->SwiftErrorVals.size(); I < E; I++) { unsigned VReg = FuncInfo->MF->getRegInfo().createVirtualRegister(RC); FuncInfo->SwiftErrorWorklist[UniquePredMBB].push_back(VReg); // Propagate the information from the single predecessor. FuncInfo->SwiftErrorMap[FuncInfo->MBB].push_back(VReg); } return; } // Propagate the information from the single predecessor. FuncInfo->SwiftErrorMap[FuncInfo->MBB] = FuncInfo->SwiftErrorMap[UniquePredMBB]; return; } // For the case of multiple predecessors, update SwiftErrorWorklist. // Handle the case where we have two or more predecessors being the same. for (const_pred_iterator PI = pred_begin(LLVMBB), PE = pred_end(LLVMBB); PI != PE; ++PI) { auto *PredMBB = FuncInfo->MBBMap[*PI]; if (!FuncInfo->SwiftErrorMap.count(PredMBB) && !FuncInfo->SwiftErrorWorklist.count(PredMBB)) { for (unsigned I = 0, E = FuncInfo->SwiftErrorVals.size(); I < E; I++) { unsigned VReg = FuncInfo->MF->getRegInfo().createVirtualRegister(RC); // When we actually visit the basic block PredMBB, we will materialize // the virtual register assignment in copySwiftErrorsToFinalVRegs. FuncInfo->SwiftErrorWorklist[PredMBB].push_back(VReg); } } } // For the case of multiple predecessors, create a virtual register for // each swifterror value and generate Phi node. for (unsigned I = 0, E = FuncInfo->SwiftErrorVals.size(); I < E; I++) { unsigned VReg = FuncInfo->MF->getRegInfo().createVirtualRegister(RC); FuncInfo->SwiftErrorMap[FuncInfo->MBB].push_back(VReg); MachineInstrBuilder SwiftErrorPHI = BuildMI(*FuncInfo->MBB, FuncInfo->InsertPt, SDB->getCurDebugLoc(), TII->get(TargetOpcode::PHI), VReg); for (const_pred_iterator PI = pred_begin(LLVMBB), PE = pred_end(LLVMBB); PI != PE; ++PI) { auto *PredMBB = FuncInfo->MBBMap[*PI]; unsigned SwiftErrorReg = FuncInfo->SwiftErrorMap.count(PredMBB) ? FuncInfo->SwiftErrorMap[PredMBB][I] : FuncInfo->SwiftErrorWorklist[PredMBB][I]; SwiftErrorPHI.addReg(SwiftErrorReg) .addMBB(PredMBB); } } } void SelectionDAGISel::SelectAllBasicBlocks(const Function &Fn) { // Initialize the Fast-ISel state, if needed. FastISel *FastIS = nullptr; if (TM.Options.EnableFastISel) FastIS = TLI->createFastISel(*FuncInfo, LibInfo); setupSwiftErrorVals(Fn, TLI, FuncInfo); // Iterate over all basic blocks in the function. ReversePostOrderTraversal<const Function*> RPOT(&Fn); for (ReversePostOrderTraversal<const Function*>::rpo_iterator I = RPOT.begin(), E = RPOT.end(); I != E; ++I) { const BasicBlock *LLVMBB = *I; if (OptLevel != CodeGenOpt::None) { bool AllPredsVisited = true; for (const_pred_iterator PI = pred_begin(LLVMBB), PE = pred_end(LLVMBB); PI != PE; ++PI) { if (!FuncInfo->VisitedBBs.count(*PI)) { AllPredsVisited = false; break; } } if (AllPredsVisited) { for (BasicBlock::const_iterator I = LLVMBB->begin(); const PHINode *PN = dyn_cast<PHINode>(I); ++I) FuncInfo->ComputePHILiveOutRegInfo(PN); } else { for (BasicBlock::const_iterator I = LLVMBB->begin(); const PHINode *PN = dyn_cast<PHINode>(I); ++I) FuncInfo->InvalidatePHILiveOutRegInfo(PN); } FuncInfo->VisitedBBs.insert(LLVMBB); } BasicBlock::const_iterator const Begin = LLVMBB->getFirstNonPHI()->getIterator(); BasicBlock::const_iterator const End = LLVMBB->end(); BasicBlock::const_iterator BI = End; FuncInfo->MBB = FuncInfo->MBBMap[LLVMBB]; if (!FuncInfo->MBB) continue; // Some blocks like catchpads have no code or MBB. FuncInfo->InsertPt = FuncInfo->MBB->getFirstNonPHI(); mergeIncomingSwiftErrors(FuncInfo, TLI, TII, LLVMBB, SDB); // Setup an EH landing-pad block. FuncInfo->ExceptionPointerVirtReg = 0; FuncInfo->ExceptionSelectorVirtReg = 0; if (LLVMBB->isEHPad()) if (!PrepareEHLandingPad()) continue; // Before doing SelectionDAG ISel, see if FastISel has been requested. if (FastIS) { FastIS->startNewBlock(); // Emit code for any incoming arguments. This must happen before // beginning FastISel on the entry block. if (LLVMBB == &Fn.getEntryBlock()) { ++NumEntryBlocks; // Lower any arguments needed in this block if this is the entry block. if (!FastIS->lowerArguments()) { // Fast isel failed to lower these arguments ++NumFastIselFailLowerArguments; if (EnableFastISelAbort > 1) report_fatal_error("FastISel didn't lower all arguments"); // Use SelectionDAG argument lowering LowerArguments(Fn); CurDAG->setRoot(SDB->getControlRoot()); SDB->clear(); CodeGenAndEmitDAG(); } // If we inserted any instructions at the beginning, make a note of // where they are, so we can be sure to emit subsequent instructions // after them. if (FuncInfo->InsertPt != FuncInfo->MBB->begin()) FastIS->setLastLocalValue(&*std::prev(FuncInfo->InsertPt)); else FastIS->setLastLocalValue(nullptr); } unsigned NumFastIselRemaining = std::distance(Begin, End); // Do FastISel on as many instructions as possible. for (; BI != Begin; --BI) { const Instruction *Inst = &*std::prev(BI); // If we no longer require this instruction, skip it. if (isFoldedOrDeadInstruction(Inst, FuncInfo)) { --NumFastIselRemaining; continue; } // Bottom-up: reset the insert pos at the top, after any local-value // instructions. FastIS->recomputeInsertPt(); // Try to select the instruction with FastISel. if (FastIS->selectInstruction(Inst)) { --NumFastIselRemaining; ++NumFastIselSuccess; // If fast isel succeeded, skip over all the folded instructions, and // then see if there is a load right before the selected instructions. // Try to fold the load if so. const Instruction *BeforeInst = Inst; while (BeforeInst != &*Begin) { BeforeInst = &*std::prev(BasicBlock::const_iterator(BeforeInst)); if (!isFoldedOrDeadInstruction(BeforeInst, FuncInfo)) break; } if (BeforeInst != Inst && isa<LoadInst>(BeforeInst) && BeforeInst->hasOneUse() && FastIS->tryToFoldLoad(cast<LoadInst>(BeforeInst), Inst)) { // If we succeeded, don't re-select the load. BI = std::next(BasicBlock::const_iterator(BeforeInst)); --NumFastIselRemaining; ++NumFastIselSuccess; } continue; } #ifndef NDEBUG if (EnableFastISelVerbose2) collectFailStats(Inst); #endif // Then handle certain instructions as single-LLVM-Instruction blocks. if (isa<CallInst>(Inst)) { if (EnableFastISelVerbose || EnableFastISelAbort) { dbgs() << "FastISel missed call: "; Inst->dump(); } if (EnableFastISelAbort > 2) // FastISel selector couldn't handle something and bailed. // For the purpose of debugging, just abort. report_fatal_error("FastISel didn't select the entire block"); if (!Inst->getType()->isVoidTy() && !Inst->getType()->isTokenTy() && !Inst->use_empty()) { unsigned &R = FuncInfo->ValueMap[Inst]; if (!R) R = FuncInfo->CreateRegs(Inst->getType()); } bool HadTailCall = false; MachineBasicBlock::iterator SavedInsertPt = FuncInfo->InsertPt; SelectBasicBlock(Inst->getIterator(), BI, HadTailCall); // If the call was emitted as a tail call, we're done with the block. // We also need to delete any previously emitted instructions. if (HadTailCall) { FastIS->removeDeadCode(SavedInsertPt, FuncInfo->MBB->end()); --BI; break; } // Recompute NumFastIselRemaining as Selection DAG instruction // selection may have handled the call, input args, etc. unsigned RemainingNow = std::distance(Begin, BI); NumFastIselFailures += NumFastIselRemaining - RemainingNow; NumFastIselRemaining = RemainingNow; continue; } bool ShouldAbort = EnableFastISelAbort; if (EnableFastISelVerbose || EnableFastISelAbort) { if (isa<TerminatorInst>(Inst)) { // Use a different message for terminator misses. dbgs() << "FastISel missed terminator: "; // Don't abort unless for terminator unless the level is really high ShouldAbort = (EnableFastISelAbort > 2); } else { dbgs() << "FastISel miss: "; } Inst->dump(); } if (ShouldAbort) // FastISel selector couldn't handle something and bailed. // For the purpose of debugging, just abort. report_fatal_error("FastISel didn't select the entire block"); NumFastIselFailures += NumFastIselRemaining; break; } FastIS->recomputeInsertPt(); } else { // Lower any arguments needed in this block if this is the entry block. if (LLVMBB == &Fn.getEntryBlock()) { ++NumEntryBlocks; LowerArguments(Fn); } } if (getAnalysis<StackProtector>().shouldEmitSDCheck(*LLVMBB)) { bool FunctionBasedInstrumentation = TLI->getSSPStackGuardCheck(*Fn.getParent()); SDB->SPDescriptor.initialize(LLVMBB, FuncInfo->MBBMap[LLVMBB], FunctionBasedInstrumentation); } if (Begin != BI) ++NumDAGBlocks; else ++NumFastIselBlocks; if (Begin != BI) { // Run SelectionDAG instruction selection on the remainder of the block // not handled by FastISel. If FastISel is not run, this is the entire // block. bool HadTailCall; SelectBasicBlock(Begin, BI, HadTailCall); } FinishBasicBlock(); FuncInfo->PHINodesToUpdate.clear(); } delete FastIS; SDB->clearDanglingDebugInfo(); SDB->SPDescriptor.resetPerFunctionState(); } /// Given that the input MI is before a partial terminator sequence TSeq, return /// true if M + TSeq also a partial terminator sequence. /// /// A Terminator sequence is a sequence of MachineInstrs which at this point in /// lowering copy vregs into physical registers, which are then passed into /// terminator instructors so we can satisfy ABI constraints. A partial /// terminator sequence is an improper subset of a terminator sequence (i.e. it /// may be the whole terminator sequence). static bool MIIsInTerminatorSequence(const MachineInstr &MI) { // If we do not have a copy or an implicit def, we return true if and only if // MI is a debug value. if (!MI.isCopy() && !MI.isImplicitDef()) // Sometimes DBG_VALUE MI sneak in between the copies from the vregs to the // physical registers if there is debug info associated with the terminator // of our mbb. We want to include said debug info in our terminator // sequence, so we return true in that case. return MI.isDebugValue(); // We have left the terminator sequence if we are not doing one of the // following: // // 1. Copying a vreg into a physical register. // 2. Copying a vreg into a vreg. // 3. Defining a register via an implicit def. // OPI should always be a register definition... MachineInstr::const_mop_iterator OPI = MI.operands_begin(); if (!OPI->isReg() || !OPI->isDef()) return false; // Defining any register via an implicit def is always ok. if (MI.isImplicitDef()) return true; // Grab the copy source... MachineInstr::const_mop_iterator OPI2 = OPI; ++OPI2; assert(OPI2 != MI.operands_end() && "Should have a copy implying we should have 2 arguments."); // Make sure that the copy dest is not a vreg when the copy source is a // physical register. if (!OPI2->isReg() || (!TargetRegisterInfo::isPhysicalRegister(OPI->getReg()) && TargetRegisterInfo::isPhysicalRegister(OPI2->getReg()))) return false; return true; } /// Find the split point at which to splice the end of BB into its success stack /// protector check machine basic block. /// /// On many platforms, due to ABI constraints, terminators, even before register /// allocation, use physical registers. This creates an issue for us since /// physical registers at this point can not travel across basic /// blocks. Luckily, selectiondag always moves physical registers into vregs /// when they enter functions and moves them through a sequence of copies back /// into the physical registers right before the terminator creating a /// ``Terminator Sequence''. This function is searching for the beginning of the /// terminator sequence so that we can ensure that we splice off not just the /// terminator, but additionally the copies that move the vregs into the /// physical registers. static MachineBasicBlock::iterator FindSplitPointForStackProtector(MachineBasicBlock *BB) { MachineBasicBlock::iterator SplitPoint = BB->getFirstTerminator(); // if (SplitPoint == BB->begin()) return SplitPoint; MachineBasicBlock::iterator Start = BB->begin(); MachineBasicBlock::iterator Previous = SplitPoint; --Previous; while (MIIsInTerminatorSequence(*Previous)) { SplitPoint = Previous; if (Previous == Start) break; --Previous; } return SplitPoint; } void SelectionDAGISel::FinishBasicBlock() { DEBUG(dbgs() << "Total amount of phi nodes to update: " << FuncInfo->PHINodesToUpdate.size() << "\n"; for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; ++i) dbgs() << "Node " << i << " : (" << FuncInfo->PHINodesToUpdate[i].first << ", " << FuncInfo->PHINodesToUpdate[i].second << ")\n"); // Next, now that we know what the last MBB the LLVM BB expanded is, update // PHI nodes in successors. for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; ++i) { MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[i].first); assert(PHI->isPHI() && "This is not a machine PHI node that we are updating!"); if (!FuncInfo->MBB->isSuccessor(PHI->getParent())) continue; PHI.addReg(FuncInfo->PHINodesToUpdate[i].second).addMBB(FuncInfo->MBB); } // Handle stack protector. if (SDB->SPDescriptor.shouldEmitFunctionBasedCheckStackProtector()) { // The target provides a guard check function. There is no need to // generate error handling code or to split current basic block. MachineBasicBlock *ParentMBB = SDB->SPDescriptor.getParentMBB(); // Add load and check to the basicblock. FuncInfo->MBB = ParentMBB; FuncInfo->InsertPt = FindSplitPointForStackProtector(ParentMBB); SDB->visitSPDescriptorParent(SDB->SPDescriptor, ParentMBB); CurDAG->setRoot(SDB->getRoot()); SDB->clear(); CodeGenAndEmitDAG(); // Clear the Per-BB State. SDB->SPDescriptor.resetPerBBState(); } else if (SDB->SPDescriptor.shouldEmitStackProtector()) { MachineBasicBlock *ParentMBB = SDB->SPDescriptor.getParentMBB(); MachineBasicBlock *SuccessMBB = SDB->SPDescriptor.getSuccessMBB(); // Find the split point to split the parent mbb. At the same time copy all // physical registers used in the tail of parent mbb into virtual registers // before the split point and back into physical registers after the split // point. This prevents us needing to deal with Live-ins and many other // register allocation issues caused by us splitting the parent mbb. The // register allocator will clean up said virtual copies later on. MachineBasicBlock::iterator SplitPoint = FindSplitPointForStackProtector(ParentMBB); // Splice the terminator of ParentMBB into SuccessMBB. SuccessMBB->splice(SuccessMBB->end(), ParentMBB, SplitPoint, ParentMBB->end()); // Add compare/jump on neq/jump to the parent BB. FuncInfo->MBB = ParentMBB; FuncInfo->InsertPt = ParentMBB->end(); SDB->visitSPDescriptorParent(SDB->SPDescriptor, ParentMBB); CurDAG->setRoot(SDB->getRoot()); SDB->clear(); CodeGenAndEmitDAG(); // CodeGen Failure MBB if we have not codegened it yet. MachineBasicBlock *FailureMBB = SDB->SPDescriptor.getFailureMBB(); if (FailureMBB->empty()) { FuncInfo->MBB = FailureMBB; FuncInfo->InsertPt = FailureMBB->end(); SDB->visitSPDescriptorFailure(SDB->SPDescriptor); CurDAG->setRoot(SDB->getRoot()); SDB->clear(); CodeGenAndEmitDAG(); } // Clear the Per-BB State. SDB->SPDescriptor.resetPerBBState(); } // Lower each BitTestBlock. for (auto &BTB : SDB->BitTestCases) { // Lower header first, if it wasn't already lowered if (!BTB.Emitted) { // Set the current basic block to the mbb we wish to insert the code into FuncInfo->MBB = BTB.Parent; FuncInfo->InsertPt = FuncInfo->MBB->end(); // Emit the code SDB->visitBitTestHeader(BTB, FuncInfo->MBB); CurDAG->setRoot(SDB->getRoot()); SDB->clear(); CodeGenAndEmitDAG(); } BranchProbability UnhandledProb = BTB.Prob; for (unsigned j = 0, ej = BTB.Cases.size(); j != ej; ++j) { UnhandledProb -= BTB.Cases[j].ExtraProb; // Set the current basic block to the mbb we wish to insert the code into FuncInfo->MBB = BTB.Cases[j].ThisBB; FuncInfo->InsertPt = FuncInfo->MBB->end(); // Emit the code // If all cases cover a contiguous range, it is not necessary to jump to // the default block after the last bit test fails. This is because the // range check during bit test header creation has guaranteed that every // case here doesn't go outside the range. In this case, there is no need // to perform the last bit test, as it will always be true. Instead, make // the second-to-last bit-test fall through to the target of the last bit // test, and delete the last bit test. MachineBasicBlock *NextMBB; if (BTB.ContiguousRange && j + 2 == ej) { // Second-to-last bit-test with contiguous range: fall through to the // target of the final bit test. NextMBB = BTB.Cases[j + 1].TargetBB; } else if (j + 1 == ej) { // For the last bit test, fall through to Default. NextMBB = BTB.Default; } else { // Otherwise, fall through to the next bit test. NextMBB = BTB.Cases[j + 1].ThisBB; } SDB->visitBitTestCase(BTB, NextMBB, UnhandledProb, BTB.Reg, BTB.Cases[j], FuncInfo->MBB); CurDAG->setRoot(SDB->getRoot()); SDB->clear(); CodeGenAndEmitDAG(); if (BTB.ContiguousRange && j + 2 == ej) { // Since we're not going to use the final bit test, remove it. BTB.Cases.pop_back(); break; } } // Update PHI Nodes for (unsigned pi = 0, pe = FuncInfo->PHINodesToUpdate.size(); pi != pe; ++pi) { MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[pi].first); MachineBasicBlock *PHIBB = PHI->getParent(); assert(PHI->isPHI() && "This is not a machine PHI node that we are updating!"); // This is "default" BB. We have two jumps to it. From "header" BB and // from last "case" BB, unless the latter was skipped. if (PHIBB == BTB.Default) { PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second).addMBB(BTB.Parent); if (!BTB.ContiguousRange) { PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second) .addMBB(BTB.Cases.back().ThisBB); } } // One of "cases" BB. for (unsigned j = 0, ej = BTB.Cases.size(); j != ej; ++j) { MachineBasicBlock* cBB = BTB.Cases[j].ThisBB; if (cBB->isSuccessor(PHIBB)) PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second).addMBB(cBB); } } } SDB->BitTestCases.clear(); // If the JumpTable record is filled in, then we need to emit a jump table. // Updating the PHI nodes is tricky in this case, since we need to determine // whether the PHI is a successor of the range check MBB or the jump table MBB for (unsigned i = 0, e = SDB->JTCases.size(); i != e; ++i) { // Lower header first, if it wasn't already lowered if (!SDB->JTCases[i].first.Emitted) { // Set the current basic block to the mbb we wish to insert the code into FuncInfo->MBB = SDB->JTCases[i].first.HeaderBB; FuncInfo->InsertPt = FuncInfo->MBB->end(); // Emit the code SDB->visitJumpTableHeader(SDB->JTCases[i].second, SDB->JTCases[i].first, FuncInfo->MBB); CurDAG->setRoot(SDB->getRoot()); SDB->clear(); CodeGenAndEmitDAG(); } // Set the current basic block to the mbb we wish to insert the code into FuncInfo->MBB = SDB->JTCases[i].second.MBB; FuncInfo->InsertPt = FuncInfo->MBB->end(); // Emit the code SDB->visitJumpTable(SDB->JTCases[i].second); CurDAG->setRoot(SDB->getRoot()); SDB->clear(); CodeGenAndEmitDAG(); // Update PHI Nodes for (unsigned pi = 0, pe = FuncInfo->PHINodesToUpdate.size(); pi != pe; ++pi) { MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[pi].first); MachineBasicBlock *PHIBB = PHI->getParent(); assert(PHI->isPHI() && "This is not a machine PHI node that we are updating!"); // "default" BB. We can go there only from header BB. if (PHIBB == SDB->JTCases[i].second.Default) PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second) .addMBB(SDB->JTCases[i].first.HeaderBB); // JT BB. Just iterate over successors here if (FuncInfo->MBB->isSuccessor(PHIBB)) PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second).addMBB(FuncInfo->MBB); } } SDB->JTCases.clear(); // If we generated any switch lowering information, build and codegen any // additional DAGs necessary. for (unsigned i = 0, e = SDB->SwitchCases.size(); i != e; ++i) { // Set the current basic block to the mbb we wish to insert the code into FuncInfo->MBB = SDB->SwitchCases[i].ThisBB; FuncInfo->InsertPt = FuncInfo->MBB->end(); // Determine the unique successors. SmallVector<MachineBasicBlock *, 2> Succs; Succs.push_back(SDB->SwitchCases[i].TrueBB); if (SDB->SwitchCases[i].TrueBB != SDB->SwitchCases[i].FalseBB) Succs.push_back(SDB->SwitchCases[i].FalseBB); // Emit the code. Note that this could result in FuncInfo->MBB being split. SDB->visitSwitchCase(SDB->SwitchCases[i], FuncInfo->MBB); CurDAG->setRoot(SDB->getRoot()); SDB->clear(); CodeGenAndEmitDAG(); // Remember the last block, now that any splitting is done, for use in // populating PHI nodes in successors. MachineBasicBlock *ThisBB = FuncInfo->MBB; // Handle any PHI nodes in successors of this chunk, as if we were coming // from the original BB before switch expansion. Note that PHI nodes can // occur multiple times in PHINodesToUpdate. We have to be very careful to // handle them the right number of times. for (unsigned i = 0, e = Succs.size(); i != e; ++i) { FuncInfo->MBB = Succs[i]; FuncInfo->InsertPt = FuncInfo->MBB->end(); // FuncInfo->MBB may have been removed from the CFG if a branch was // constant folded. if (ThisBB->isSuccessor(FuncInfo->MBB)) { for (MachineBasicBlock::iterator MBBI = FuncInfo->MBB->begin(), MBBE = FuncInfo->MBB->end(); MBBI != MBBE && MBBI->isPHI(); ++MBBI) { MachineInstrBuilder PHI(*MF, MBBI); // This value for this PHI node is recorded in PHINodesToUpdate. for (unsigned pn = 0; ; ++pn) { assert(pn != FuncInfo->PHINodesToUpdate.size() && "Didn't find PHI entry!"); if (FuncInfo->PHINodesToUpdate[pn].first == PHI) { PHI.addReg(FuncInfo->PHINodesToUpdate[pn].second).addMBB(ThisBB); break; } } } } } } SDB->SwitchCases.clear(); } /// Create the scheduler. If a specific scheduler was specified /// via the SchedulerRegistry, use it, otherwise select the /// one preferred by the target. /// ScheduleDAGSDNodes *SelectionDAGISel::CreateScheduler() { return ISHeuristic(this, OptLevel); } //===----------------------------------------------------------------------===// // Helper functions used by the generated instruction selector. //===----------------------------------------------------------------------===// // Calls to these methods are generated by tblgen. /// CheckAndMask - The isel is trying to match something like (and X, 255). If /// the dag combiner simplified the 255, we still want to match. RHS is the /// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value /// specified in the .td file (e.g. 255). bool SelectionDAGISel::CheckAndMask(SDValue LHS, ConstantSDNode *RHS, int64_t DesiredMaskS) const { const APInt &ActualMask = RHS->getAPIntValue(); const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS); // If the actual mask exactly matches, success! if (ActualMask == DesiredMask) return true; // If the actual AND mask is allowing unallowed bits, this doesn't match. if (ActualMask.intersects(~DesiredMask)) return false; // Otherwise, the DAG Combiner may have proven that the value coming in is // either already zero or is not demanded. Check for known zero input bits. APInt NeededMask = DesiredMask & ~ActualMask; if (CurDAG->MaskedValueIsZero(LHS, NeededMask)) return true; // TODO: check to see if missing bits are just not demanded. // Otherwise, this pattern doesn't match. return false; } /// CheckOrMask - The isel is trying to match something like (or X, 255). If /// the dag combiner simplified the 255, we still want to match. RHS is the /// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value /// specified in the .td file (e.g. 255). bool SelectionDAGISel::CheckOrMask(SDValue LHS, ConstantSDNode *RHS, int64_t DesiredMaskS) const { const APInt &ActualMask = RHS->getAPIntValue(); const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS); // If the actual mask exactly matches, success! if (ActualMask == DesiredMask) return true; // If the actual AND mask is allowing unallowed bits, this doesn't match. if (ActualMask.intersects(~DesiredMask)) return false; // Otherwise, the DAG Combiner may have proven that the value coming in is // either already zero or is not demanded. Check for known zero input bits. APInt NeededMask = DesiredMask & ~ActualMask; APInt KnownZero, KnownOne; CurDAG->computeKnownBits(LHS, KnownZero, KnownOne); // If all the missing bits in the or are already known to be set, match! if ((NeededMask & KnownOne) == NeededMask) return true; // TODO: check to see if missing bits are just not demanded. // Otherwise, this pattern doesn't match. return false; } /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated /// by tblgen. Others should not call it. void SelectionDAGISel::SelectInlineAsmMemoryOperands(std::vector<SDValue> &Ops, const SDLoc &DL) { std::vector<SDValue> InOps; std::swap(InOps, Ops); Ops.push_back(InOps[InlineAsm::Op_InputChain]); // 0 Ops.push_back(InOps[InlineAsm::Op_AsmString]); // 1 Ops.push_back(InOps[InlineAsm::Op_MDNode]); // 2, !srcloc Ops.push_back(InOps[InlineAsm::Op_ExtraInfo]); // 3 (SideEffect, AlignStack) unsigned i = InlineAsm::Op_FirstOperand, e = InOps.size(); if (InOps[e-1].getValueType() == MVT::Glue) --e; // Don't process a glue operand if it is here. while (i != e) { unsigned Flags = cast<ConstantSDNode>(InOps[i])->getZExtValue(); if (!InlineAsm::isMemKind(Flags)) { // Just skip over this operand, copying the operands verbatim. Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+InlineAsm::getNumOperandRegisters(Flags) + 1); i += InlineAsm::getNumOperandRegisters(Flags) + 1; } else { assert(InlineAsm::getNumOperandRegisters(Flags) == 1 && "Memory operand with multiple values?"); unsigned TiedToOperand; if (InlineAsm::isUseOperandTiedToDef(Flags, TiedToOperand)) { // We need the constraint ID from the operand this is tied to. unsigned CurOp = InlineAsm::Op_FirstOperand; Flags = cast<ConstantSDNode>(InOps[CurOp])->getZExtValue(); for (; TiedToOperand; --TiedToOperand) { CurOp += InlineAsm::getNumOperandRegisters(Flags)+1; Flags = cast<ConstantSDNode>(InOps[CurOp])->getZExtValue(); } } // Otherwise, this is a memory operand. Ask the target to select it. std::vector<SDValue> SelOps; unsigned ConstraintID = InlineAsm::getMemoryConstraintID(Flags); if (SelectInlineAsmMemoryOperand(InOps[i+1], ConstraintID, SelOps)) report_fatal_error("Could not match memory address. Inline asm" " failure!"); // Add this to the output node. unsigned NewFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, SelOps.size()); NewFlags = InlineAsm::getFlagWordForMem(NewFlags, ConstraintID); Ops.push_back(CurDAG->getTargetConstant(NewFlags, DL, MVT::i32)); Ops.insert(Ops.end(), SelOps.begin(), SelOps.end()); i += 2; } } // Add the glue input back if present. if (e != InOps.size()) Ops.push_back(InOps.back()); } /// findGlueUse - Return use of MVT::Glue value produced by the specified /// SDNode. /// static SDNode *findGlueUse(SDNode *N) { unsigned FlagResNo = N->getNumValues()-1; for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) { SDUse &Use = I.getUse(); if (Use.getResNo() == FlagResNo) return Use.getUser(); } return nullptr; } /// findNonImmUse - Return true if "Use" is a non-immediate use of "Def". /// This function recursively traverses up the operand chain, ignoring /// certain nodes. static bool findNonImmUse(SDNode *Use, SDNode* Def, SDNode *ImmedUse, SDNode *Root, SmallPtrSetImpl<SDNode*> &Visited, bool IgnoreChains) { // The NodeID's are given uniques ID's where a node ID is guaranteed to be // greater than all of its (recursive) operands. If we scan to a point where // 'use' is smaller than the node we're scanning for, then we know we will // never find it. // // The Use may be -1 (unassigned) if it is a newly allocated node. This can // happen because we scan down to newly selected nodes in the case of glue // uses. if ((Use->getNodeId() < Def->getNodeId() && Use->getNodeId() != -1)) return false; // Don't revisit nodes if we already scanned it and didn't fail, we know we // won't fail if we scan it again. if (!Visited.insert(Use).second) return false; for (const SDValue &Op : Use->op_values()) { // Ignore chain uses, they are validated by HandleMergeInputChains. if (Op.getValueType() == MVT::Other && IgnoreChains) continue; SDNode *N = Op.getNode(); if (N == Def) { if (Use == ImmedUse || Use == Root) continue; // We are not looking for immediate use. assert(N != Root); return true; } // Traverse up the operand chain. if (findNonImmUse(N, Def, ImmedUse, Root, Visited, IgnoreChains)) return true; } return false; } /// IsProfitableToFold - Returns true if it's profitable to fold the specific /// operand node N of U during instruction selection that starts at Root. bool SelectionDAGISel::IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const { if (OptLevel == CodeGenOpt::None) return false; return N.hasOneUse(); } /// IsLegalToFold - Returns true if the specific operand node N of /// U can be folded during instruction selection that starts at Root. bool SelectionDAGISel::IsLegalToFold(SDValue N, SDNode *U, SDNode *Root, CodeGenOpt::Level OptLevel, bool IgnoreChains) { if (OptLevel == CodeGenOpt::None) return false; // If Root use can somehow reach N through a path that that doesn't contain // U then folding N would create a cycle. e.g. In the following // diagram, Root can reach N through X. If N is folded into into Root, then // X is both a predecessor and a successor of U. // // [N*] // // ^ ^ // // / \ // // [U*] [X]? // // ^ ^ // // \ / // // \ / // // [Root*] // // // * indicates nodes to be folded together. // // If Root produces glue, then it gets (even more) interesting. Since it // will be "glued" together with its glue use in the scheduler, we need to // check if it might reach N. // // [N*] // // ^ ^ // // / \ // // [U*] [X]? // // ^ ^ // // \ \ // // \ | // // [Root*] | // // ^ | // // f | // // | / // // [Y] / // // ^ / // // f / // // | / // // [GU] // // // If GU (glue use) indirectly reaches N (the load), and Root folds N // (call it Fold), then X is a predecessor of GU and a successor of // Fold. But since Fold and GU are glued together, this will create // a cycle in the scheduling graph. // If the node has glue, walk down the graph to the "lowest" node in the // glueged set. EVT VT = Root->getValueType(Root->getNumValues()-1); while (VT == MVT::Glue) { SDNode *GU = findGlueUse(Root); if (!GU) break; Root = GU; VT = Root->getValueType(Root->getNumValues()-1); // If our query node has a glue result with a use, we've walked up it. If // the user (which has already been selected) has a chain or indirectly uses // the chain, our WalkChainUsers predicate will not consider it. Because of // this, we cannot ignore chains in this predicate. IgnoreChains = false; } SmallPtrSet<SDNode*, 16> Visited; return !findNonImmUse(Root, N.getNode(), U, Root, Visited, IgnoreChains); } void SelectionDAGISel::Select_INLINEASM(SDNode *N) { SDLoc DL(N); std::vector<SDValue> Ops(N->op_begin(), N->op_end()); SelectInlineAsmMemoryOperands(Ops, DL); const EVT VTs[] = {MVT::Other, MVT::Glue}; SDValue New = CurDAG->getNode(ISD::INLINEASM, DL, VTs, Ops); New->setNodeId(-1); ReplaceUses(N, New.getNode()); CurDAG->RemoveDeadNode(N); } void SelectionDAGISel::Select_READ_REGISTER(SDNode *Op) { SDLoc dl(Op); MDNodeSDNode *MD = dyn_cast<MDNodeSDNode>(Op->getOperand(1)); const MDString *RegStr = dyn_cast<MDString>(MD->getMD()->getOperand(0)); unsigned Reg = TLI->getRegisterByName(RegStr->getString().data(), Op->getValueType(0), *CurDAG); SDValue New = CurDAG->getCopyFromReg( Op->getOperand(0), dl, Reg, Op->getValueType(0)); New->setNodeId(-1); ReplaceUses(Op, New.getNode()); CurDAG->RemoveDeadNode(Op); } void SelectionDAGISel::Select_WRITE_REGISTER(SDNode *Op) { SDLoc dl(Op); MDNodeSDNode *MD = dyn_cast<MDNodeSDNode>(Op->getOperand(1)); const MDString *RegStr = dyn_cast<MDString>(MD->getMD()->getOperand(0)); unsigned Reg = TLI->getRegisterByName(RegStr->getString().data(), Op->getOperand(2).getValueType(), *CurDAG); SDValue New = CurDAG->getCopyToReg( Op->getOperand(0), dl, Reg, Op->getOperand(2)); New->setNodeId(-1); ReplaceUses(Op, New.getNode()); CurDAG->RemoveDeadNode(Op); } void SelectionDAGISel::Select_UNDEF(SDNode *N) { CurDAG->SelectNodeTo(N, TargetOpcode::IMPLICIT_DEF, N->getValueType(0)); } /// GetVBR - decode a vbr encoding whose top bit is set. LLVM_ATTRIBUTE_ALWAYS_INLINE static inline uint64_t GetVBR(uint64_t Val, const unsigned char *MatcherTable, unsigned &Idx) { assert(Val >= 128 && "Not a VBR"); Val &= 127; // Remove first vbr bit. unsigned Shift = 7; uint64_t NextBits; do { NextBits = MatcherTable[Idx++]; Val |= (NextBits&127) << Shift; Shift += 7; } while (NextBits & 128); return Val; } /// When a match is complete, this method updates uses of interior chain results /// to use the new results. void SelectionDAGISel::UpdateChains( SDNode *NodeToMatch, SDValue InputChain, const SmallVectorImpl<SDNode *> &ChainNodesMatched, bool isMorphNodeTo) { SmallVector<SDNode*, 4> NowDeadNodes; // Now that all the normal results are replaced, we replace the chain and // glue results if present. if (!ChainNodesMatched.empty()) { assert(InputChain.getNode() && "Matched input chains but didn't produce a chain"); // Loop over all of the nodes we matched that produced a chain result. // Replace all the chain results with the final chain we ended up with. for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) { SDNode *ChainNode = ChainNodesMatched[i]; assert(ChainNode->getOpcode() != ISD::DELETED_NODE && "Deleted node left in chain"); // Don't replace the results of the root node if we're doing a // MorphNodeTo. if (ChainNode == NodeToMatch && isMorphNodeTo) continue; SDValue ChainVal = SDValue(ChainNode, ChainNode->getNumValues()-1); if (ChainVal.getValueType() == MVT::Glue) ChainVal = ChainVal.getValue(ChainVal->getNumValues()-2); assert(ChainVal.getValueType() == MVT::Other && "Not a chain?"); CurDAG->ReplaceAllUsesOfValueWith(ChainVal, InputChain); // If the node became dead and we haven't already seen it, delete it. if (ChainNode != NodeToMatch && ChainNode->use_empty() && !std::count(NowDeadNodes.begin(), NowDeadNodes.end(), ChainNode)) NowDeadNodes.push_back(ChainNode); } } if (!NowDeadNodes.empty()) CurDAG->RemoveDeadNodes(NowDeadNodes); DEBUG(dbgs() << "ISEL: Match complete!\n"); } enum ChainResult { CR_Simple, CR_InducesCycle, CR_LeadsToInteriorNode }; /// WalkChainUsers - Walk down the users of the specified chained node that is /// part of the pattern we're matching, looking at all of the users we find. /// This determines whether something is an interior node, whether we have a /// non-pattern node in between two pattern nodes (which prevent folding because /// it would induce a cycle) and whether we have a TokenFactor node sandwiched /// between pattern nodes (in which case the TF becomes part of the pattern). /// /// The walk we do here is guaranteed to be small because we quickly get down to /// already selected nodes "below" us. static ChainResult WalkChainUsers(const SDNode *ChainedNode, SmallVectorImpl<SDNode *> &ChainedNodesInPattern, DenseMap<const SDNode *, ChainResult> &TokenFactorResult, SmallVectorImpl<SDNode *> &InteriorChainedNodes) { ChainResult Result = CR_Simple; for (SDNode::use_iterator UI = ChainedNode->use_begin(), E = ChainedNode->use_end(); UI != E; ++UI) { // Make sure the use is of the chain, not some other value we produce. if (UI.getUse().getValueType() != MVT::Other) continue; SDNode *User = *UI; if (User->getOpcode() == ISD::HANDLENODE) // Root of the graph. continue; // If we see an already-selected machine node, then we've gone beyond the // pattern that we're selecting down into the already selected chunk of the // DAG. unsigned UserOpcode = User->getOpcode(); if (User->isMachineOpcode() || UserOpcode == ISD::CopyToReg || UserOpcode == ISD::CopyFromReg || UserOpcode == ISD::INLINEASM || UserOpcode == ISD::EH_LABEL || UserOpcode == ISD::LIFETIME_START || UserOpcode == ISD::LIFETIME_END) { // If their node ID got reset to -1 then they've already been selected. // Treat them like a MachineOpcode. if (User->getNodeId() == -1) continue; } // If we have a TokenFactor, we handle it specially. if (User->getOpcode() != ISD::TokenFactor) { // If the node isn't a token factor and isn't part of our pattern, then it // must be a random chained node in between two nodes we're selecting. // This happens when we have something like: // x = load ptr // call // y = x+4 // store y -> ptr // Because we structurally match the load/store as a read/modify/write, // but the call is chained between them. We cannot fold in this case // because it would induce a cycle in the graph. if (!std::count(ChainedNodesInPattern.begin(), ChainedNodesInPattern.end(), User)) return CR_InducesCycle; // Otherwise we found a node that is part of our pattern. For example in: // x = load ptr // y = x+4 // store y -> ptr // This would happen when we're scanning down from the load and see the // store as a user. Record that there is a use of ChainedNode that is // part of the pattern and keep scanning uses. Result = CR_LeadsToInteriorNode; InteriorChainedNodes.push_back(User); continue; } // If we found a TokenFactor, there are two cases to consider: first if the // TokenFactor is just hanging "below" the pattern we're matching (i.e. no // uses of the TF are in our pattern) we just want to ignore it. Second, // the TokenFactor can be sandwiched in between two chained nodes, like so: // [Load chain] // ^ // | // [Load] // ^ ^ // | \ DAG's like cheese // / \ do you? // / | // [TokenFactor] [Op] // ^ ^ // | | // \ / // \ / // [Store] // // In this case, the TokenFactor becomes part of our match and we rewrite it // as a new TokenFactor. // // To distinguish these two cases, do a recursive walk down the uses. auto MemoizeResult = TokenFactorResult.find(User); bool Visited = MemoizeResult != TokenFactorResult.end(); // Recursively walk chain users only if the result is not memoized. if (!Visited) { auto Res = WalkChainUsers(User, ChainedNodesInPattern, TokenFactorResult, InteriorChainedNodes); MemoizeResult = TokenFactorResult.insert(std::make_pair(User, Res)).first; } switch (MemoizeResult->second) { case CR_Simple: // If the uses of the TokenFactor are just already-selected nodes, ignore // it, it is "below" our pattern. continue; case CR_InducesCycle: // If the uses of the TokenFactor lead to nodes that are not part of our // pattern that are not selected, folding would turn this into a cycle, // bail out now. return CR_InducesCycle; case CR_LeadsToInteriorNode: break; // Otherwise, keep processing. } // Okay, we know we're in the interesting interior case. The TokenFactor // is now going to be considered part of the pattern so that we rewrite its // uses (it may have uses that are not part of the pattern) with the // ultimate chain result of the generated code. We will also add its chain // inputs as inputs to the ultimate TokenFactor we create. Result = CR_LeadsToInteriorNode; if (!Visited) { ChainedNodesInPattern.push_back(User); InteriorChainedNodes.push_back(User); } } return Result; } /// HandleMergeInputChains - This implements the OPC_EmitMergeInputChains /// operation for when the pattern matched at least one node with a chains. The /// input vector contains a list of all of the chained nodes that we match. We /// must determine if this is a valid thing to cover (i.e. matching it won't /// induce cycles in the DAG) and if so, creating a TokenFactor node. that will /// be used as the input node chain for the generated nodes. static SDValue HandleMergeInputChains(SmallVectorImpl<SDNode*> &ChainNodesMatched, SelectionDAG *CurDAG) { // Used for memoization. Without it WalkChainUsers could take exponential // time to run. DenseMap<const SDNode *, ChainResult> TokenFactorResult; // Walk all of the chained nodes we've matched, recursively scanning down the // users of the chain result. This adds any TokenFactor nodes that are caught // in between chained nodes to the chained and interior nodes list. SmallVector<SDNode*, 3> InteriorChainedNodes; for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) { if (WalkChainUsers(ChainNodesMatched[i], ChainNodesMatched, TokenFactorResult, InteriorChainedNodes) == CR_InducesCycle) return SDValue(); // Would induce a cycle. } // Okay, we have walked all the matched nodes and collected TokenFactor nodes // that we are interested in. Form our input TokenFactor node. SmallVector<SDValue, 3> InputChains; for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) { // Add the input chain of this node to the InputChains list (which will be // the operands of the generated TokenFactor) if it's not an interior node. SDNode *N = ChainNodesMatched[i]; if (N->getOpcode() != ISD::TokenFactor) { if (std::count(InteriorChainedNodes.begin(),InteriorChainedNodes.end(),N)) continue; // Otherwise, add the input chain. SDValue InChain = ChainNodesMatched[i]->getOperand(0); assert(InChain.getValueType() == MVT::Other && "Not a chain"); InputChains.push_back(InChain); continue; } // If we have a token factor, we want to add all inputs of the token factor // that are not part of the pattern we're matching. for (const SDValue &Op : N->op_values()) { if (!std::count(ChainNodesMatched.begin(), ChainNodesMatched.end(), Op.getNode())) InputChains.push_back(Op); } } if (InputChains.size() == 1) return InputChains[0]; return CurDAG->getNode(ISD::TokenFactor, SDLoc(ChainNodesMatched[0]), MVT::Other, InputChains); } /// MorphNode - Handle morphing a node in place for the selector. SDNode *SelectionDAGISel:: MorphNode(SDNode *Node, unsigned TargetOpc, SDVTList VTList, ArrayRef<SDValue> Ops, unsigned EmitNodeInfo) { // It is possible we're using MorphNodeTo to replace a node with no // normal results with one that has a normal result (or we could be // adding a chain) and the input could have glue and chains as well. // In this case we need to shift the operands down. // FIXME: This is a horrible hack and broken in obscure cases, no worse // than the old isel though. int OldGlueResultNo = -1, OldChainResultNo = -1; unsigned NTMNumResults = Node->getNumValues(); if (Node->getValueType(NTMNumResults-1) == MVT::Glue) { OldGlueResultNo = NTMNumResults-1; if (NTMNumResults != 1 && Node->getValueType(NTMNumResults-2) == MVT::Other) OldChainResultNo = NTMNumResults-2; } else if (Node->getValueType(NTMNumResults-1) == MVT::Other) OldChainResultNo = NTMNumResults-1; // Call the underlying SelectionDAG routine to do the transmogrification. Note // that this deletes operands of the old node that become dead. SDNode *Res = CurDAG->MorphNodeTo(Node, ~TargetOpc, VTList, Ops); // MorphNodeTo can operate in two ways: if an existing node with the // specified operands exists, it can just return it. Otherwise, it // updates the node in place to have the requested operands. if (Res == Node) { // If we updated the node in place, reset the node ID. To the isel, // this should be just like a newly allocated machine node. Res->setNodeId(-1); } unsigned ResNumResults = Res->getNumValues(); // Move the glue if needed. if ((EmitNodeInfo & OPFL_GlueOutput) && OldGlueResultNo != -1 && (unsigned)OldGlueResultNo != ResNumResults-1) CurDAG->ReplaceAllUsesOfValueWith(SDValue(Node, OldGlueResultNo), SDValue(Res, ResNumResults-1)); if ((EmitNodeInfo & OPFL_GlueOutput) != 0) --ResNumResults; // Move the chain reference if needed. if ((EmitNodeInfo & OPFL_Chain) && OldChainResultNo != -1 && (unsigned)OldChainResultNo != ResNumResults-1) CurDAG->ReplaceAllUsesOfValueWith(SDValue(Node, OldChainResultNo), SDValue(Res, ResNumResults-1)); // Otherwise, no replacement happened because the node already exists. Replace // Uses of the old node with the new one. if (Res != Node) { CurDAG->ReplaceAllUsesWith(Node, Res); CurDAG->RemoveDeadNode(Node); } return Res; } /// CheckSame - Implements OP_CheckSame. LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool CheckSame(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N, const SmallVectorImpl<std::pair<SDValue, SDNode*> > &RecordedNodes) { // Accept if it is exactly the same as a previously recorded node. unsigned RecNo = MatcherTable[MatcherIndex++]; assert(RecNo < RecordedNodes.size() && "Invalid CheckSame"); return N == RecordedNodes[RecNo].first; } /// CheckChildSame - Implements OP_CheckChildXSame. LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool CheckChildSame(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N, const SmallVectorImpl<std::pair<SDValue, SDNode*> > &RecordedNodes, unsigned ChildNo) { if (ChildNo >= N.getNumOperands()) return false; // Match fails if out of range child #. return ::CheckSame(MatcherTable, MatcherIndex, N.getOperand(ChildNo), RecordedNodes); } /// CheckPatternPredicate - Implements OP_CheckPatternPredicate. LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool CheckPatternPredicate(const unsigned char *MatcherTable, unsigned &MatcherIndex, const SelectionDAGISel &SDISel) { return SDISel.CheckPatternPredicate(MatcherTable[MatcherIndex++]); } /// CheckNodePredicate - Implements OP_CheckNodePredicate. LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool CheckNodePredicate(const unsigned char *MatcherTable, unsigned &MatcherIndex, const SelectionDAGISel &SDISel, SDNode *N) { return SDISel.CheckNodePredicate(N, MatcherTable[MatcherIndex++]); } LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool CheckOpcode(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDNode *N) { uint16_t Opc = MatcherTable[MatcherIndex++]; Opc |= (unsigned short)MatcherTable[MatcherIndex++] << 8; return N->getOpcode() == Opc; } LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool CheckType(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N, const TargetLowering *TLI, const DataLayout &DL) { MVT::SimpleValueType VT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++]; if (N.getValueType() == VT) return true; // Handle the case when VT is iPTR. return VT == MVT::iPTR && N.getValueType() == TLI->getPointerTy(DL); } LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool CheckChildType(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N, const TargetLowering *TLI, const DataLayout &DL, unsigned ChildNo) { if (ChildNo >= N.getNumOperands()) return false; // Match fails if out of range child #. return ::CheckType(MatcherTable, MatcherIndex, N.getOperand(ChildNo), TLI, DL); } LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool CheckCondCode(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N) { return cast<CondCodeSDNode>(N)->get() == (ISD::CondCode)MatcherTable[MatcherIndex++]; } LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool CheckValueType(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N, const TargetLowering *TLI, const DataLayout &DL) { MVT::SimpleValueType VT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++]; if (cast<VTSDNode>(N)->getVT() == VT) return true; // Handle the case when VT is iPTR. return VT == MVT::iPTR && cast<VTSDNode>(N)->getVT() == TLI->getPointerTy(DL); } LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool CheckInteger(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N) { int64_t Val = MatcherTable[MatcherIndex++]; if (Val & 128) Val = GetVBR(Val, MatcherTable, MatcherIndex); ConstantSDNode *C = dyn_cast<ConstantSDNode>(N); return C && C->getSExtValue() == Val; } LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool CheckChildInteger(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N, unsigned ChildNo) { if (ChildNo >= N.getNumOperands()) return false; // Match fails if out of range child #. return ::CheckInteger(MatcherTable, MatcherIndex, N.getOperand(ChildNo)); } LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool CheckAndImm(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N, const SelectionDAGISel &SDISel) { int64_t Val = MatcherTable[MatcherIndex++]; if (Val & 128) Val = GetVBR(Val, MatcherTable, MatcherIndex); if (N->getOpcode() != ISD::AND) return false; ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1)); return C && SDISel.CheckAndMask(N.getOperand(0), C, Val); } LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool CheckOrImm(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N, const SelectionDAGISel &SDISel) { int64_t Val = MatcherTable[MatcherIndex++]; if (Val & 128) Val = GetVBR(Val, MatcherTable, MatcherIndex); if (N->getOpcode() != ISD::OR) return false; ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1)); return C && SDISel.CheckOrMask(N.getOperand(0), C, Val); } /// IsPredicateKnownToFail - If we know how and can do so without pushing a /// scope, evaluate the current node. If the current predicate is known to /// fail, set Result=true and return anything. If the current predicate is /// known to pass, set Result=false and return the MatcherIndex to continue /// with. If the current predicate is unknown, set Result=false and return the /// MatcherIndex to continue with. static unsigned IsPredicateKnownToFail(const unsigned char *Table, unsigned Index, SDValue N, bool &Result, const SelectionDAGISel &SDISel, SmallVectorImpl<std::pair<SDValue, SDNode*> > &RecordedNodes) { switch (Table[Index++]) { default: Result = false; return Index-1; // Could not evaluate this predicate. case SelectionDAGISel::OPC_CheckSame: Result = !::CheckSame(Table, Index, N, RecordedNodes); return Index; case SelectionDAGISel::OPC_CheckChild0Same: case SelectionDAGISel::OPC_CheckChild1Same: case SelectionDAGISel::OPC_CheckChild2Same: case SelectionDAGISel::OPC_CheckChild3Same: Result = !::CheckChildSame(Table, Index, N, RecordedNodes, Table[Index-1] - SelectionDAGISel::OPC_CheckChild0Same); return Index; case SelectionDAGISel::OPC_CheckPatternPredicate: Result = !::CheckPatternPredicate(Table, Index, SDISel); return Index; case SelectionDAGISel::OPC_CheckPredicate: Result = !::CheckNodePredicate(Table, Index, SDISel, N.getNode()); return Index; case SelectionDAGISel::OPC_CheckOpcode: Result = !::CheckOpcode(Table, Index, N.getNode()); return Index; case SelectionDAGISel::OPC_CheckType: Result = !::CheckType(Table, Index, N, SDISel.TLI, SDISel.CurDAG->getDataLayout()); return Index; case SelectionDAGISel::OPC_CheckChild0Type: case SelectionDAGISel::OPC_CheckChild1Type: case SelectionDAGISel::OPC_CheckChild2Type: case SelectionDAGISel::OPC_CheckChild3Type: case SelectionDAGISel::OPC_CheckChild4Type: case SelectionDAGISel::OPC_CheckChild5Type: case SelectionDAGISel::OPC_CheckChild6Type: case SelectionDAGISel::OPC_CheckChild7Type: Result = !::CheckChildType( Table, Index, N, SDISel.TLI, SDISel.CurDAG->getDataLayout(), Table[Index - 1] - SelectionDAGISel::OPC_CheckChild0Type); return Index; case SelectionDAGISel::OPC_CheckCondCode: Result = !::CheckCondCode(Table, Index, N); return Index; case SelectionDAGISel::OPC_CheckValueType: Result = !::CheckValueType(Table, Index, N, SDISel.TLI, SDISel.CurDAG->getDataLayout()); return Index; case SelectionDAGISel::OPC_CheckInteger: Result = !::CheckInteger(Table, Index, N); return Index; case SelectionDAGISel::OPC_CheckChild0Integer: case SelectionDAGISel::OPC_CheckChild1Integer: case SelectionDAGISel::OPC_CheckChild2Integer: case SelectionDAGISel::OPC_CheckChild3Integer: case SelectionDAGISel::OPC_CheckChild4Integer: Result = !::CheckChildInteger(Table, Index, N, Table[Index-1] - SelectionDAGISel::OPC_CheckChild0Integer); return Index; case SelectionDAGISel::OPC_CheckAndImm: Result = !::CheckAndImm(Table, Index, N, SDISel); return Index; case SelectionDAGISel::OPC_CheckOrImm: Result = !::CheckOrImm(Table, Index, N, SDISel); return Index; } } namespace { struct MatchScope { /// FailIndex - If this match fails, this is the index to continue with. unsigned FailIndex; /// NodeStack - The node stack when the scope was formed. SmallVector<SDValue, 4> NodeStack; /// NumRecordedNodes - The number of recorded nodes when the scope was formed. unsigned NumRecordedNodes; /// NumMatchedMemRefs - The number of matched memref entries. unsigned NumMatchedMemRefs; /// InputChain/InputGlue - The current chain/glue SDValue InputChain, InputGlue; /// HasChainNodesMatched - True if the ChainNodesMatched list is non-empty. bool HasChainNodesMatched; }; /// \\brief A DAG update listener to keep the matching state /// (i.e. RecordedNodes and MatchScope) uptodate if the target is allowed to /// change the DAG while matching. X86 addressing mode matcher is an example /// for this. class MatchStateUpdater : public SelectionDAG::DAGUpdateListener { SmallVectorImpl<std::pair<SDValue, SDNode*> > &RecordedNodes; SmallVectorImpl<MatchScope> &MatchScopes; public: MatchStateUpdater(SelectionDAG &DAG, SmallVectorImpl<std::pair<SDValue, SDNode*> > &RN, SmallVectorImpl<MatchScope> &MS) : SelectionDAG::DAGUpdateListener(DAG), RecordedNodes(RN), MatchScopes(MS) { } void NodeDeleted(SDNode *N, SDNode *E) override { // Some early-returns here to avoid the search if we deleted the node or // if the update comes from MorphNodeTo (MorphNodeTo is the last thing we // do, so it's unnecessary to update matching state at that point). // Neither of these can occur currently because we only install this // update listener during matching a complex patterns. if (!E || E->isMachineOpcode()) return; // Performing linear search here does not matter because we almost never // run this code. You'd have to have a CSE during complex pattern // matching. for (auto &I : RecordedNodes) if (I.first.getNode() == N) I.first.setNode(E); for (auto &I : MatchScopes) for (auto &J : I.NodeStack) if (J.getNode() == N) J.setNode(E); } }; } // end anonymous namespace void SelectionDAGISel::SelectCodeCommon(SDNode *NodeToMatch, const unsigned char *MatcherTable, unsigned TableSize) { // FIXME: Should these even be selected? Handle these cases in the caller? switch (NodeToMatch->getOpcode()) { default: break; case ISD::EntryToken: // These nodes remain the same. case ISD::BasicBlock: case ISD::Register: case ISD::RegisterMask: case ISD::HANDLENODE: case ISD::MDNODE_SDNODE: case ISD::TargetConstant: case ISD::TargetConstantFP: case ISD::TargetConstantPool: case ISD::TargetFrameIndex: case ISD::TargetExternalSymbol: case ISD::MCSymbol: case ISD::TargetBlockAddress: case ISD::TargetJumpTable: case ISD::TargetGlobalTLSAddress: case ISD::TargetGlobalAddress: case ISD::TokenFactor: case ISD::CopyFromReg: case ISD::CopyToReg: case ISD::EH_LABEL: case ISD::LIFETIME_START: case ISD::LIFETIME_END: NodeToMatch->setNodeId(-1); // Mark selected. return; case ISD::AssertSext: case ISD::AssertZext: CurDAG->ReplaceAllUsesOfValueWith(SDValue(NodeToMatch, 0), NodeToMatch->getOperand(0)); CurDAG->RemoveDeadNode(NodeToMatch); return; case ISD::INLINEASM: Select_INLINEASM(NodeToMatch); return; case ISD::READ_REGISTER: Select_READ_REGISTER(NodeToMatch); return; case ISD::WRITE_REGISTER: Select_WRITE_REGISTER(NodeToMatch); return; case ISD::UNDEF: Select_UNDEF(NodeToMatch); return; } assert(!NodeToMatch->isMachineOpcode() && "Node already selected!"); // Set up the node stack with NodeToMatch as the only node on the stack. SmallVector<SDValue, 8> NodeStack; SDValue N = SDValue(NodeToMatch, 0); NodeStack.push_back(N); // MatchScopes - Scopes used when matching, if a match failure happens, this // indicates where to continue checking. SmallVector<MatchScope, 8> MatchScopes; // RecordedNodes - This is the set of nodes that have been recorded by the // state machine. The second value is the parent of the node, or null if the // root is recorded. SmallVector<std::pair<SDValue, SDNode*>, 8> RecordedNodes; // MatchedMemRefs - This is the set of MemRef's we've seen in the input // pattern. SmallVector<MachineMemOperand*, 2> MatchedMemRefs; // These are the current input chain and glue for use when generating nodes. // Various Emit operations change these. For example, emitting a copytoreg // uses and updates these. SDValue InputChain, InputGlue; // ChainNodesMatched - If a pattern matches nodes that have input/output // chains, the OPC_EmitMergeInputChains operation is emitted which indicates // which ones they are. The result is captured into this list so that we can // update the chain results when the pattern is complete. SmallVector<SDNode*, 3> ChainNodesMatched; DEBUG(dbgs() << "ISEL: Starting pattern match on root node: "; NodeToMatch->dump(CurDAG); dbgs() << '\n'); // Determine where to start the interpreter. Normally we start at opcode #0, // but if the state machine starts with an OPC_SwitchOpcode, then we // accelerate the first lookup (which is guaranteed to be hot) with the // OpcodeOffset table. unsigned MatcherIndex = 0; if (!OpcodeOffset.empty()) { // Already computed the OpcodeOffset table, just index into it. if (N.getOpcode() < OpcodeOffset.size()) MatcherIndex = OpcodeOffset[N.getOpcode()]; DEBUG(dbgs() << " Initial Opcode index to " << MatcherIndex << "\n"); } else if (MatcherTable[0] == OPC_SwitchOpcode) { // Otherwise, the table isn't computed, but the state machine does start // with an OPC_SwitchOpcode instruction. Populate the table now, since this // is the first time we're selecting an instruction. unsigned Idx = 1; while (1) { // Get the size of this case. unsigned CaseSize = MatcherTable[Idx++]; if (CaseSize & 128) CaseSize = GetVBR(CaseSize, MatcherTable, Idx); if (CaseSize == 0) break; // Get the opcode, add the index to the table. uint16_t Opc = MatcherTable[Idx++]; Opc |= (unsigned short)MatcherTable[Idx++] << 8; if (Opc >= OpcodeOffset.size()) OpcodeOffset.resize((Opc+1)*2); OpcodeOffset[Opc] = Idx; Idx += CaseSize; } // Okay, do the lookup for the first opcode. if (N.getOpcode() < OpcodeOffset.size()) MatcherIndex = OpcodeOffset[N.getOpcode()]; } while (1) { assert(MatcherIndex < TableSize && "Invalid index"); #ifndef NDEBUG unsigned CurrentOpcodeIndex = MatcherIndex; #endif BuiltinOpcodes Opcode = (BuiltinOpcodes)MatcherTable[MatcherIndex++]; switch (Opcode) { case OPC_Scope: { // Okay, the semantics of this operation are that we should push a scope // then evaluate the first child. However, pushing a scope only to have // the first check fail (which then pops it) is inefficient. If we can // determine immediately that the first check (or first several) will // immediately fail, don't even bother pushing a scope for them. unsigned FailIndex; while (1) { unsigned NumToSkip = MatcherTable[MatcherIndex++]; if (NumToSkip & 128) NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex); // Found the end of the scope with no match. if (NumToSkip == 0) { FailIndex = 0; break; } FailIndex = MatcherIndex+NumToSkip; unsigned MatcherIndexOfPredicate = MatcherIndex; (void)MatcherIndexOfPredicate; // silence warning. // If we can't evaluate this predicate without pushing a scope (e.g. if // it is a 'MoveParent') or if the predicate succeeds on this node, we // push the scope and evaluate the full predicate chain. bool Result; MatcherIndex = IsPredicateKnownToFail(MatcherTable, MatcherIndex, N, Result, *this, RecordedNodes); if (!Result) break; DEBUG(dbgs() << " Skipped scope entry (due to false predicate) at " << "index " << MatcherIndexOfPredicate << ", continuing at " << FailIndex << "\n"); ++NumDAGIselRetries; // Otherwise, we know that this case of the Scope is guaranteed to fail, // move to the next case. MatcherIndex = FailIndex; } // If the whole scope failed to match, bail. if (FailIndex == 0) break; // Push a MatchScope which indicates where to go if the first child fails // to match. MatchScope NewEntry; NewEntry.FailIndex = FailIndex; NewEntry.NodeStack.append(NodeStack.begin(), NodeStack.end()); NewEntry.NumRecordedNodes = RecordedNodes.size(); NewEntry.NumMatchedMemRefs = MatchedMemRefs.size(); NewEntry.InputChain = InputChain; NewEntry.InputGlue = InputGlue; NewEntry.HasChainNodesMatched = !ChainNodesMatched.empty(); MatchScopes.push_back(NewEntry); continue; } case OPC_RecordNode: { // Remember this node, it may end up being an operand in the pattern. SDNode *Parent = nullptr; if (NodeStack.size() > 1) Parent = NodeStack[NodeStack.size()-2].getNode(); RecordedNodes.push_back(std::make_pair(N, Parent)); continue; } case OPC_RecordChild0: case OPC_RecordChild1: case OPC_RecordChild2: case OPC_RecordChild3: case OPC_RecordChild4: case OPC_RecordChild5: case OPC_RecordChild6: case OPC_RecordChild7: { unsigned ChildNo = Opcode-OPC_RecordChild0; if (ChildNo >= N.getNumOperands()) break; // Match fails if out of range child #. RecordedNodes.push_back(std::make_pair(N->getOperand(ChildNo), N.getNode())); continue; } case OPC_RecordMemRef: MatchedMemRefs.push_back(cast<MemSDNode>(N)->getMemOperand()); continue; case OPC_CaptureGlueInput: // If the current node has an input glue, capture it in InputGlue. if (N->getNumOperands() != 0 && N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Glue) InputGlue = N->getOperand(N->getNumOperands()-1); continue; case OPC_MoveChild: { unsigned ChildNo = MatcherTable[MatcherIndex++]; if (ChildNo >= N.getNumOperands()) break; // Match fails if out of range child #. N = N.getOperand(ChildNo); NodeStack.push_back(N); continue; } case OPC_MoveChild0: case OPC_MoveChild1: case OPC_MoveChild2: case OPC_MoveChild3: case OPC_MoveChild4: case OPC_MoveChild5: case OPC_MoveChild6: case OPC_MoveChild7: { unsigned ChildNo = Opcode-OPC_MoveChild0; if (ChildNo >= N.getNumOperands()) break; // Match fails if out of range child #. N = N.getOperand(ChildNo); NodeStack.push_back(N); continue; } case OPC_MoveParent: // Pop the current node off the NodeStack. NodeStack.pop_back(); assert(!NodeStack.empty() && "Node stack imbalance!"); N = NodeStack.back(); continue; case OPC_CheckSame: if (!::CheckSame(MatcherTable, MatcherIndex, N, RecordedNodes)) break; continue; case OPC_CheckChild0Same: case OPC_CheckChild1Same: case OPC_CheckChild2Same: case OPC_CheckChild3Same: if (!::CheckChildSame(MatcherTable, MatcherIndex, N, RecordedNodes, Opcode-OPC_CheckChild0Same)) break; continue; case OPC_CheckPatternPredicate: if (!::CheckPatternPredicate(MatcherTable, MatcherIndex, *this)) break; continue; case OPC_CheckPredicate: if (!::CheckNodePredicate(MatcherTable, MatcherIndex, *this, N.getNode())) break; continue; case OPC_CheckComplexPat: { unsigned CPNum = MatcherTable[MatcherIndex++]; unsigned RecNo = MatcherTable[MatcherIndex++]; assert(RecNo < RecordedNodes.size() && "Invalid CheckComplexPat"); // If target can modify DAG during matching, keep the matching state // consistent. std::unique_ptr<MatchStateUpdater> MSU; if (ComplexPatternFuncMutatesDAG()) MSU.reset(new MatchStateUpdater(*CurDAG, RecordedNodes, MatchScopes)); if (!CheckComplexPattern(NodeToMatch, RecordedNodes[RecNo].second, RecordedNodes[RecNo].first, CPNum, RecordedNodes)) break; continue; } case OPC_CheckOpcode: if (!::CheckOpcode(MatcherTable, MatcherIndex, N.getNode())) break; continue; case OPC_CheckType: if (!::CheckType(MatcherTable, MatcherIndex, N, TLI, CurDAG->getDataLayout())) break; continue; case OPC_SwitchOpcode: { unsigned CurNodeOpcode = N.getOpcode(); unsigned SwitchStart = MatcherIndex-1; (void)SwitchStart; unsigned CaseSize; while (1) { // Get the size of this case. CaseSize = MatcherTable[MatcherIndex++]; if (CaseSize & 128) CaseSize = GetVBR(CaseSize, MatcherTable, MatcherIndex); if (CaseSize == 0) break; uint16_t Opc = MatcherTable[MatcherIndex++]; Opc |= (unsigned short)MatcherTable[MatcherIndex++] << 8; // If the opcode matches, then we will execute this case. if (CurNodeOpcode == Opc) break; // Otherwise, skip over this case. MatcherIndex += CaseSize; } // If no cases matched, bail out. if (CaseSize == 0) break; // Otherwise, execute the case we found. DEBUG(dbgs() << " OpcodeSwitch from " << SwitchStart << " to " << MatcherIndex << "\n"); continue; } case OPC_SwitchType: { MVT CurNodeVT = N.getSimpleValueType(); unsigned SwitchStart = MatcherIndex-1; (void)SwitchStart; unsigned CaseSize; while (1) { // Get the size of this case. CaseSize = MatcherTable[MatcherIndex++]; if (CaseSize & 128) CaseSize = GetVBR(CaseSize, MatcherTable, MatcherIndex); if (CaseSize == 0) break; MVT CaseVT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++]; if (CaseVT == MVT::iPTR) CaseVT = TLI->getPointerTy(CurDAG->getDataLayout()); // If the VT matches, then we will execute this case. if (CurNodeVT == CaseVT) break; // Otherwise, skip over this case. MatcherIndex += CaseSize; } // If no cases matched, bail out. if (CaseSize == 0) break; // Otherwise, execute the case we found. DEBUG(dbgs() << " TypeSwitch[" << EVT(CurNodeVT).getEVTString() << "] from " << SwitchStart << " to " << MatcherIndex<<'\n'); continue; } case OPC_CheckChild0Type: case OPC_CheckChild1Type: case OPC_CheckChild2Type: case OPC_CheckChild3Type: case OPC_CheckChild4Type: case OPC_CheckChild5Type: case OPC_CheckChild6Type: case OPC_CheckChild7Type: if (!::CheckChildType(MatcherTable, MatcherIndex, N, TLI, CurDAG->getDataLayout(), Opcode - OPC_CheckChild0Type)) break; continue; case OPC_CheckCondCode: if (!::CheckCondCode(MatcherTable, MatcherIndex, N)) break; continue; case OPC_CheckValueType: if (!::CheckValueType(MatcherTable, MatcherIndex, N, TLI, CurDAG->getDataLayout())) break; continue; case OPC_CheckInteger: if (!::CheckInteger(MatcherTable, MatcherIndex, N)) break; continue; case OPC_CheckChild0Integer: case OPC_CheckChild1Integer: case OPC_CheckChild2Integer: case OPC_CheckChild3Integer: case OPC_CheckChild4Integer: if (!::CheckChildInteger(MatcherTable, MatcherIndex, N, Opcode-OPC_CheckChild0Integer)) break; continue; case OPC_CheckAndImm: if (!::CheckAndImm(MatcherTable, MatcherIndex, N, *this)) break; continue; case OPC_CheckOrImm: if (!::CheckOrImm(MatcherTable, MatcherIndex, N, *this)) break; continue; case OPC_CheckFoldableChainNode: { assert(NodeStack.size() != 1 && "No parent node"); // Verify that all intermediate nodes between the root and this one have // a single use. bool HasMultipleUses = false; for (unsigned i = 1, e = NodeStack.size()-1; i != e; ++i) if (!NodeStack[i].hasOneUse()) { HasMultipleUses = true; break; } if (HasMultipleUses) break; // Check to see that the target thinks this is profitable to fold and that // we can fold it without inducing cycles in the graph. if (!IsProfitableToFold(N, NodeStack[NodeStack.size()-2].getNode(), NodeToMatch) || !IsLegalToFold(N, NodeStack[NodeStack.size()-2].getNode(), NodeToMatch, OptLevel, true/*We validate our own chains*/)) break; continue; } case OPC_EmitInteger: { MVT::SimpleValueType VT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++]; int64_t Val = MatcherTable[MatcherIndex++]; if (Val & 128) Val = GetVBR(Val, MatcherTable, MatcherIndex); RecordedNodes.push_back(std::pair<SDValue, SDNode*>( CurDAG->getTargetConstant(Val, SDLoc(NodeToMatch), VT), nullptr)); continue; } case OPC_EmitRegister: { MVT::SimpleValueType VT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++]; unsigned RegNo = MatcherTable[MatcherIndex++]; RecordedNodes.push_back(std::pair<SDValue, SDNode*>( CurDAG->getRegister(RegNo, VT), nullptr)); continue; } case OPC_EmitRegister2: { // For targets w/ more than 256 register names, the register enum // values are stored in two bytes in the matcher table (just like // opcodes). MVT::SimpleValueType VT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++]; unsigned RegNo = MatcherTable[MatcherIndex++]; RegNo |= MatcherTable[MatcherIndex++] << 8; RecordedNodes.push_back(std::pair<SDValue, SDNode*>( CurDAG->getRegister(RegNo, VT), nullptr)); continue; } case OPC_EmitConvertToTarget: { // Convert from IMM/FPIMM to target version. unsigned RecNo = MatcherTable[MatcherIndex++]; assert(RecNo < RecordedNodes.size() && "Invalid EmitConvertToTarget"); SDValue Imm = RecordedNodes[RecNo].first; if (Imm->getOpcode() == ISD::Constant) { const ConstantInt *Val=cast<ConstantSDNode>(Imm)->getConstantIntValue(); Imm = CurDAG->getTargetConstant(*Val, SDLoc(NodeToMatch), Imm.getValueType()); } else if (Imm->getOpcode() == ISD::ConstantFP) { const ConstantFP *Val=cast<ConstantFPSDNode>(Imm)->getConstantFPValue(); Imm = CurDAG->getTargetConstantFP(*Val, SDLoc(NodeToMatch), Imm.getValueType()); } RecordedNodes.push_back(std::make_pair(Imm, RecordedNodes[RecNo].second)); continue; } case OPC_EmitMergeInputChains1_0: // OPC_EmitMergeInputChains, 1, 0 case OPC_EmitMergeInputChains1_1: // OPC_EmitMergeInputChains, 1, 1 case OPC_EmitMergeInputChains1_2: { // OPC_EmitMergeInputChains, 1, 2 // These are space-optimized forms of OPC_EmitMergeInputChains. assert(!InputChain.getNode() && "EmitMergeInputChains should be the first chain producing node"); assert(ChainNodesMatched.empty() && "Should only have one EmitMergeInputChains per match"); // Read all of the chained nodes. unsigned RecNo = Opcode - OPC_EmitMergeInputChains1_0; assert(RecNo < RecordedNodes.size() && "Invalid EmitMergeInputChains"); ChainNodesMatched.push_back(RecordedNodes[RecNo].first.getNode()); // FIXME: What if other value results of the node have uses not matched // by this pattern? if (ChainNodesMatched.back() != NodeToMatch && !RecordedNodes[RecNo].first.hasOneUse()) { ChainNodesMatched.clear(); break; } // Merge the input chains if they are not intra-pattern references. InputChain = HandleMergeInputChains(ChainNodesMatched, CurDAG); if (!InputChain.getNode()) break; // Failed to merge. continue; } case OPC_EmitMergeInputChains: { assert(!InputChain.getNode() && "EmitMergeInputChains should be the first chain producing node"); // This node gets a list of nodes we matched in the input that have // chains. We want to token factor all of the input chains to these nodes // together. However, if any of the input chains is actually one of the // nodes matched in this pattern, then we have an intra-match reference. // Ignore these because the newly token factored chain should not refer to // the old nodes. unsigned NumChains = MatcherTable[MatcherIndex++]; assert(NumChains != 0 && "Can't TF zero chains"); assert(ChainNodesMatched.empty() && "Should only have one EmitMergeInputChains per match"); // Read all of the chained nodes. for (unsigned i = 0; i != NumChains; ++i) { unsigned RecNo = MatcherTable[MatcherIndex++]; assert(RecNo < RecordedNodes.size() && "Invalid EmitMergeInputChains"); ChainNodesMatched.push_back(RecordedNodes[RecNo].first.getNode()); // FIXME: What if other value results of the node have uses not matched // by this pattern? if (ChainNodesMatched.back() != NodeToMatch && !RecordedNodes[RecNo].first.hasOneUse()) { ChainNodesMatched.clear(); break; } } // If the inner loop broke out, the match fails. if (ChainNodesMatched.empty()) break; // Merge the input chains if they are not intra-pattern references. InputChain = HandleMergeInputChains(ChainNodesMatched, CurDAG); if (!InputChain.getNode()) break; // Failed to merge. continue; } case OPC_EmitCopyToReg: { unsigned RecNo = MatcherTable[MatcherIndex++]; assert(RecNo < RecordedNodes.size() && "Invalid EmitCopyToReg"); unsigned DestPhysReg = MatcherTable[MatcherIndex++]; if (!InputChain.getNode()) InputChain = CurDAG->getEntryNode(); InputChain = CurDAG->getCopyToReg(InputChain, SDLoc(NodeToMatch), DestPhysReg, RecordedNodes[RecNo].first, InputGlue); InputGlue = InputChain.getValue(1); continue; } case OPC_EmitNodeXForm: { unsigned XFormNo = MatcherTable[MatcherIndex++]; unsigned RecNo = MatcherTable[MatcherIndex++]; assert(RecNo < RecordedNodes.size() && "Invalid EmitNodeXForm"); SDValue Res = RunSDNodeXForm(RecordedNodes[RecNo].first, XFormNo); RecordedNodes.push_back(std::pair<SDValue,SDNode*>(Res, nullptr)); continue; } case OPC_EmitNode: case OPC_MorphNodeTo: case OPC_EmitNode0: case OPC_EmitNode1: case OPC_EmitNode2: case OPC_MorphNodeTo0: case OPC_MorphNodeTo1: case OPC_MorphNodeTo2: { uint16_t TargetOpc = MatcherTable[MatcherIndex++]; TargetOpc |= (unsigned short)MatcherTable[MatcherIndex++] << 8; unsigned EmitNodeInfo = MatcherTable[MatcherIndex++]; // Get the result VT list. unsigned NumVTs; // If this is one of the compressed forms, get the number of VTs based // on the Opcode. Otherwise read the next byte from the table. if (Opcode >= OPC_MorphNodeTo0 && Opcode <= OPC_MorphNodeTo2) NumVTs = Opcode - OPC_MorphNodeTo0; else if (Opcode >= OPC_EmitNode0 && Opcode <= OPC_EmitNode2) NumVTs = Opcode - OPC_EmitNode0; else NumVTs = MatcherTable[MatcherIndex++]; SmallVector<EVT, 4> VTs; for (unsigned i = 0; i != NumVTs; ++i) { MVT::SimpleValueType VT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++]; if (VT == MVT::iPTR) VT = TLI->getPointerTy(CurDAG->getDataLayout()).SimpleTy; VTs.push_back(VT); } if (EmitNodeInfo & OPFL_Chain) VTs.push_back(MVT::Other); if (EmitNodeInfo & OPFL_GlueOutput) VTs.push_back(MVT::Glue); // This is hot code, so optimize the two most common cases of 1 and 2 // results. SDVTList VTList; if (VTs.size() == 1) VTList = CurDAG->getVTList(VTs[0]); else if (VTs.size() == 2) VTList = CurDAG->getVTList(VTs[0], VTs[1]); else VTList = CurDAG->getVTList(VTs); // Get the operand list. unsigned NumOps = MatcherTable[MatcherIndex++]; SmallVector<SDValue, 8> Ops; for (unsigned i = 0; i != NumOps; ++i) { unsigned RecNo = MatcherTable[MatcherIndex++]; if (RecNo & 128) RecNo = GetVBR(RecNo, MatcherTable, MatcherIndex); assert(RecNo < RecordedNodes.size() && "Invalid EmitNode"); Ops.push_back(RecordedNodes[RecNo].first); } // If there are variadic operands to add, handle them now. if (EmitNodeInfo & OPFL_VariadicInfo) { // Determine the start index to copy from. unsigned FirstOpToCopy = getNumFixedFromVariadicInfo(EmitNodeInfo); FirstOpToCopy += (EmitNodeInfo & OPFL_Chain) ? 1 : 0; assert(NodeToMatch->getNumOperands() >= FirstOpToCopy && "Invalid variadic node"); // Copy all of the variadic operands, not including a potential glue // input. for (unsigned i = FirstOpToCopy, e = NodeToMatch->getNumOperands(); i != e; ++i) { SDValue V = NodeToMatch->getOperand(i); if (V.getValueType() == MVT::Glue) break; Ops.push_back(V); } } // If this has chain/glue inputs, add them. if (EmitNodeInfo & OPFL_Chain) Ops.push_back(InputChain); if ((EmitNodeInfo & OPFL_GlueInput) && InputGlue.getNode() != nullptr) Ops.push_back(InputGlue); // Create the node. SDNode *Res = nullptr; bool IsMorphNodeTo = Opcode == OPC_MorphNodeTo || (Opcode >= OPC_MorphNodeTo0 && Opcode <= OPC_MorphNodeTo2); if (!IsMorphNodeTo) { // If this is a normal EmitNode command, just create the new node and // add the results to the RecordedNodes list. Res = CurDAG->getMachineNode(TargetOpc, SDLoc(NodeToMatch), VTList, Ops); // Add all the non-glue/non-chain results to the RecordedNodes list. for (unsigned i = 0, e = VTs.size(); i != e; ++i) { if (VTs[i] == MVT::Other || VTs[i] == MVT::Glue) break; RecordedNodes.push_back(std::pair<SDValue,SDNode*>(SDValue(Res, i), nullptr)); } } else { assert(NodeToMatch->getOpcode() != ISD::DELETED_NODE && "NodeToMatch was removed partway through selection"); SelectionDAG::DAGNodeDeletedListener NDL(*CurDAG, [&](SDNode *N, SDNode *E) { auto &Chain = ChainNodesMatched; assert((!E || !is_contained(Chain, N)) && "Chain node replaced during MorphNode"); Chain.erase(std::remove(Chain.begin(), Chain.end(), N), Chain.end()); }); Res = MorphNode(NodeToMatch, TargetOpc, VTList, Ops, EmitNodeInfo); } // If the node had chain/glue results, update our notion of the current // chain and glue. if (EmitNodeInfo & OPFL_GlueOutput) { InputGlue = SDValue(Res, VTs.size()-1); if (EmitNodeInfo & OPFL_Chain) InputChain = SDValue(Res, VTs.size()-2); } else if (EmitNodeInfo & OPFL_Chain) InputChain = SDValue(Res, VTs.size()-1); // If the OPFL_MemRefs glue is set on this node, slap all of the // accumulated memrefs onto it. // // FIXME: This is vastly incorrect for patterns with multiple outputs // instructions that access memory and for ComplexPatterns that match // loads. if (EmitNodeInfo & OPFL_MemRefs) { // Only attach load or store memory operands if the generated // instruction may load or store. const MCInstrDesc &MCID = TII->get(TargetOpc); bool mayLoad = MCID.mayLoad(); bool mayStore = MCID.mayStore(); unsigned NumMemRefs = 0; for (SmallVectorImpl<MachineMemOperand *>::const_iterator I = MatchedMemRefs.begin(), E = MatchedMemRefs.end(); I != E; ++I) { if ((*I)->isLoad()) { if (mayLoad) ++NumMemRefs; } else if ((*I)->isStore()) { if (mayStore) ++NumMemRefs; } else { ++NumMemRefs; } } MachineSDNode::mmo_iterator MemRefs = MF->allocateMemRefsArray(NumMemRefs); MachineSDNode::mmo_iterator MemRefsPos = MemRefs; for (SmallVectorImpl<MachineMemOperand *>::const_iterator I = MatchedMemRefs.begin(), E = MatchedMemRefs.end(); I != E; ++I) { if ((*I)->isLoad()) { if (mayLoad) *MemRefsPos++ = *I; } else if ((*I)->isStore()) { if (mayStore) *MemRefsPos++ = *I; } else { *MemRefsPos++ = *I; } } cast<MachineSDNode>(Res) ->setMemRefs(MemRefs, MemRefs + NumMemRefs); } DEBUG(dbgs() << " " << (IsMorphNodeTo ? "Morphed" : "Created") << " node: "; Res->dump(CurDAG); dbgs() << "\n"); // If this was a MorphNodeTo then we're completely done! if (IsMorphNodeTo) { // Update chain uses. UpdateChains(Res, InputChain, ChainNodesMatched, true); return; } continue; } case OPC_CompleteMatch: { // The match has been completed, and any new nodes (if any) have been // created. Patch up references to the matched dag to use the newly // created nodes. unsigned NumResults = MatcherTable[MatcherIndex++]; for (unsigned i = 0; i != NumResults; ++i) { unsigned ResSlot = MatcherTable[MatcherIndex++]; if (ResSlot & 128) ResSlot = GetVBR(ResSlot, MatcherTable, MatcherIndex); assert(ResSlot < RecordedNodes.size() && "Invalid CompleteMatch"); SDValue Res = RecordedNodes[ResSlot].first; assert(i < NodeToMatch->getNumValues() && NodeToMatch->getValueType(i) != MVT::Other && NodeToMatch->getValueType(i) != MVT::Glue && "Invalid number of results to complete!"); assert((NodeToMatch->getValueType(i) == Res.getValueType() || NodeToMatch->getValueType(i) == MVT::iPTR || Res.getValueType() == MVT::iPTR || NodeToMatch->getValueType(i).getSizeInBits() == Res.getValueSizeInBits()) && "invalid replacement"); CurDAG->ReplaceAllUsesOfValueWith(SDValue(NodeToMatch, i), Res); } // Update chain uses. UpdateChains(NodeToMatch, InputChain, ChainNodesMatched, false); // If the root node defines glue, we need to update it to the glue result. // TODO: This never happens in our tests and I think it can be removed / // replaced with an assert, but if we do it this the way the change is // NFC. if (NodeToMatch->getValueType(NodeToMatch->getNumValues() - 1) == MVT::Glue && InputGlue.getNode()) CurDAG->ReplaceAllUsesOfValueWith( SDValue(NodeToMatch, NodeToMatch->getNumValues() - 1), InputGlue); assert(NodeToMatch->use_empty() && "Didn't replace all uses of the node?"); CurDAG->RemoveDeadNode(NodeToMatch); return; } } // If the code reached this point, then the match failed. See if there is // another child to try in the current 'Scope', otherwise pop it until we // find a case to check. DEBUG(dbgs() << " Match failed at index " << CurrentOpcodeIndex << "\n"); ++NumDAGIselRetries; while (1) { if (MatchScopes.empty()) { CannotYetSelect(NodeToMatch); return; } // Restore the interpreter state back to the point where the scope was // formed. MatchScope &LastScope = MatchScopes.back(); RecordedNodes.resize(LastScope.NumRecordedNodes); NodeStack.clear(); NodeStack.append(LastScope.NodeStack.begin(), LastScope.NodeStack.end()); N = NodeStack.back(); if (LastScope.NumMatchedMemRefs != MatchedMemRefs.size()) MatchedMemRefs.resize(LastScope.NumMatchedMemRefs); MatcherIndex = LastScope.FailIndex; DEBUG(dbgs() << " Continuing at " << MatcherIndex << "\n"); InputChain = LastScope.InputChain; InputGlue = LastScope.InputGlue; if (!LastScope.HasChainNodesMatched) ChainNodesMatched.clear(); // Check to see what the offset is at the new MatcherIndex. If it is zero // we have reached the end of this scope, otherwise we have another child // in the current scope to try. unsigned NumToSkip = MatcherTable[MatcherIndex++]; if (NumToSkip & 128) NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex); // If we have another child in this scope to match, update FailIndex and // try it. if (NumToSkip != 0) { LastScope.FailIndex = MatcherIndex+NumToSkip; break; } // End of this scope, pop it and try the next child in the containing // scope. MatchScopes.pop_back(); } } } void SelectionDAGISel::CannotYetSelect(SDNode *N) { std::string msg; raw_string_ostream Msg(msg); Msg << "Cannot select: "; if (N->getOpcode() != ISD::INTRINSIC_W_CHAIN && N->getOpcode() != ISD::INTRINSIC_WO_CHAIN && N->getOpcode() != ISD::INTRINSIC_VOID) { N->printrFull(Msg, CurDAG); Msg << "\nIn function: " << MF->getName(); } else { bool HasInputChain = N->getOperand(0).getValueType() == MVT::Other; unsigned iid = cast<ConstantSDNode>(N->getOperand(HasInputChain))->getZExtValue(); if (iid < Intrinsic::num_intrinsics) Msg << "intrinsic %" << Intrinsic::getName((Intrinsic::ID)iid, None); else if (const TargetIntrinsicInfo *TII = TM.getIntrinsicInfo()) Msg << "target intrinsic %" << TII->getName(iid); else Msg << "unknown intrinsic #" << iid; } report_fatal_error(Msg.str()); } char SelectionDAGISel::ID = 0;
[ "rich@ellcc.org" ]
rich@ellcc.org
162bfcd88be88572d57def00f901bfb55ff9bed9
3b52c6242edcbf40135886314441855a0abbddae
/Source/Engine/ECS/System.cpp
43e1618d90400e681240f0022f3824171515af24
[ "Apache-2.0" ]
permissive
codacy-badger/RiftEngine
5666e84175260aa40932d726e46ea78894c25880
96f8de5ccf1973955e0265df42c2373b054aba23
refs/heads/master
2020-04-17T19:56:31.507829
2019-01-21T16:45:36
2019-01-21T16:45:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
173
cpp
// Copyright 2015-2019 Piperift - All rights reserved #include "System.h" #include "ECSManager.h" Ptr<ECSManager> System::ECS() { return GetOwner().Cast<ECSManager>(); }
[ "muit@piperift.com" ]
muit@piperift.com
005f69c319cdab9aa29eacf5b7345ae930d2f931
04b1803adb6653ecb7cb827c4f4aa616afacf629
/third_party/blink/common/associated_interfaces/associated_interface_provider.cc
2a10832aa7f8d2b9a9e49c10e8ad59007b8b14a2
[ "BSD-3-Clause", "LGPL-2.0-or-later", "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.1-only", "GPL-1.0-or-later", "GPL-2.0-only", "LGPL-2.0-only", "BSD-2-Clause", "LicenseRef-scancode-other-copyleft", "MIT", "Apache-2.0" ]
permissive
Samsung/Castanets
240d9338e097b75b3f669604315b06f7cf129d64
4896f732fc747dfdcfcbac3d442f2d2d42df264a
refs/heads/castanets_76_dev
2023-08-31T09:01:04.744346
2021-07-30T04:56:25
2021-08-11T05:45:21
125,484,161
58
49
BSD-3-Clause
2022-10-16T19:31:26
2018-03-16T08:07:37
null
UTF-8
C++
false
false
3,237
cc
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h" #include <map> #include "mojo/public/cpp/bindings/associated_binding.h" namespace blink { class AssociatedInterfaceProvider::LocalProvider : public mojom::AssociatedInterfaceProvider { public: using Binder = base::RepeatingCallback<void(mojo::ScopedInterfaceEndpointHandle)>; explicit LocalProvider( scoped_refptr<base::SingleThreadTaskRunner> task_runner) : associated_interface_provider_binding_(this) { associated_interface_provider_binding_.Bind( mojo::MakeRequestAssociatedWithDedicatedPipe(&ptr_), std::move(task_runner)); } ~LocalProvider() override {} void SetBinderForName(const std::string& name, const Binder& binder) { binders_[name] = binder; } bool HasInterface(const std::string& name) const { return binders_.find(name) != binders_.end(); } void GetInterface(const std::string& name, mojo::ScopedInterfaceEndpointHandle handle) { return ptr_->GetAssociatedInterface( name, mojom::AssociatedInterfaceAssociatedRequest(std::move(handle))); } private: // mojom::AssociatedInterfaceProvider: void GetAssociatedInterface( const std::string& name, mojom::AssociatedInterfaceAssociatedRequest request) override { auto it = binders_.find(name); if (it != binders_.end()) it->second.Run(request.PassHandle()); } std::map<std::string, Binder> binders_; mojo::AssociatedBinding<mojom::AssociatedInterfaceProvider> associated_interface_provider_binding_; mojom::AssociatedInterfaceProviderAssociatedPtr ptr_; DISALLOW_COPY_AND_ASSIGN(LocalProvider); }; AssociatedInterfaceProvider::AssociatedInterfaceProvider( mojom::AssociatedInterfaceProviderAssociatedPtr proxy, scoped_refptr<base::SingleThreadTaskRunner> task_runner) : proxy_(std::move(proxy)), task_runner_(std::move(task_runner)) { DCHECK(proxy_.is_bound()); } AssociatedInterfaceProvider::AssociatedInterfaceProvider( scoped_refptr<base::SingleThreadTaskRunner> task_runner) : local_provider_(std::make_unique<LocalProvider>(task_runner)), task_runner_(std::move(task_runner)) {} AssociatedInterfaceProvider::~AssociatedInterfaceProvider() = default; void AssociatedInterfaceProvider::GetInterface( const std::string& name, mojo::ScopedInterfaceEndpointHandle handle) { if (local_provider_ && (local_provider_->HasInterface(name) || !proxy_)) { local_provider_->GetInterface(name, std::move(handle)); return; } DCHECK(proxy_); proxy_->GetAssociatedInterface( name, mojom::AssociatedInterfaceAssociatedRequest(std::move(handle))); } void AssociatedInterfaceProvider::OverrideBinderForTesting( const std::string& name, const base::RepeatingCallback<void(mojo::ScopedInterfaceEndpointHandle)>& binder) { if (!local_provider_) local_provider_ = std::make_unique<LocalProvider>(task_runner_); local_provider_->SetBinderForName(name, binder); } } // namespace blink
[ "sunny.nam@samsung.com" ]
sunny.nam@samsung.com
1ff865a5b7c3557c24e71eedc41f16f6cde64e53
8cbe8569d4974a2dd6b87615586ee4ab590bbdec
/Tools/DumpRenderTree/AccessibilityUIElement.h
03b56697514d5a2f496001ea315ee9ab5d3e3e67
[]
no_license
h4ck3rm1k3/blink-git-problems
84215cae6dc9fdcbd12f8c1bc785f8db0c0a3d9a
330e71e45587b4d4bce32024415c247c9a7dd718
refs/heads/master
2020-04-30T05:24:46.089779
2013-04-04T19:54:17
2013-04-11T01:55:15
9,214,255
1
0
null
null
null
null
UTF-8
C++
false
false
10,311
h
/* * Copyright (C) 2008 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 AccessibilityUIElement_h #define AccessibilityUIElement_h #include "AccessibilityTextMarker.h" #include <JavaScriptCore/JSObjectRef.h> #include <wtf/Platform.h> #include <wtf/Vector.h> #if PLATFORM(MAC) #ifdef __OBJC__ typedef id PlatformUIElement; #else typedef struct objc_object* PlatformUIElement; #endif #elif PLATFORM(WIN) #undef _WINSOCKAPI_ #define _WINSOCKAPI_ // Prevent inclusion of winsock.h in windows.h #include <WebCore/COMPtr.h> #include <oleacc.h> typedef COMPtr<IAccessible> PlatformUIElement; #elif HAVE(ACCESSIBILITY) && (PLATFORM(GTK) || PLATFORM(EFL)) #include <atk/atk.h> typedef AtkObject* PlatformUIElement; #else typedef void* PlatformUIElement; #endif #if PLATFORM(MAC) #ifdef __OBJC__ typedef id NotificationHandler; #else typedef struct objc_object* NotificationHandler; #endif #endif class AccessibilityUIElement { public: AccessibilityUIElement(PlatformUIElement); AccessibilityUIElement(const AccessibilityUIElement&); ~AccessibilityUIElement(); PlatformUIElement platformUIElement() { return m_element; } static JSObjectRef makeJSAccessibilityUIElement(JSContextRef, const AccessibilityUIElement&); bool isEqual(AccessibilityUIElement* otherElement); void getLinkedUIElements(Vector<AccessibilityUIElement>&); void getDocumentLinks(Vector<AccessibilityUIElement>&); void getChildren(Vector<AccessibilityUIElement>&); void getChildrenWithRange(Vector<AccessibilityUIElement>&, unsigned location, unsigned length); AccessibilityUIElement elementAtPoint(int x, int y); AccessibilityUIElement getChildAtIndex(unsigned); unsigned indexOfChild(AccessibilityUIElement*); int childrenCount(); AccessibilityUIElement titleUIElement(); AccessibilityUIElement parentElement(); void takeFocus(); void takeSelection(); void addSelection(); void removeSelection(); // Methods - platform-independent implementations JSStringRef allAttributes(); JSStringRef attributesOfLinkedUIElements(); AccessibilityUIElement linkedUIElementAtIndex(unsigned); JSStringRef attributesOfDocumentLinks(); JSStringRef attributesOfChildren(); JSStringRef parameterizedAttributeNames(); void increment(); void decrement(); void showMenu(); void press(); // Attributes - platform-independent implementations JSStringRef stringAttributeValue(JSStringRef attribute); double numberAttributeValue(JSStringRef attribute); AccessibilityUIElement uiElementAttributeValue(JSStringRef attribute) const; bool boolAttributeValue(JSStringRef attribute); bool isAttributeSupported(JSStringRef attribute); bool isAttributeSettable(JSStringRef attribute); bool isPressActionSupported(); bool isIncrementActionSupported(); bool isDecrementActionSupported(); JSStringRef role(); JSStringRef subrole(); JSStringRef roleDescription(); JSStringRef title(); JSStringRef description(); JSStringRef language(); JSStringRef stringValue(); JSStringRef accessibilityValue() const; JSStringRef helpText() const; JSStringRef orientation() const; double x(); double y(); double width(); double height(); double intValue() const; double minValue(); double maxValue(); JSStringRef valueDescription(); int insertionPointLineNumber(); JSStringRef selectedTextRange(); bool isEnabled(); bool isRequired() const; bool isFocused() const; bool isFocusable() const; bool isSelected() const; bool isSelectable() const; bool isMultiSelectable() const; bool isSelectedOptionActive() const; void setSelectedChild(AccessibilityUIElement*) const; unsigned selectedChildrenCount() const; AccessibilityUIElement selectedChildAtIndex(unsigned) const; bool isExpanded() const; bool isChecked() const; bool isVisible() const; bool isOffScreen() const; bool isCollapsed() const; bool isIgnored() const; bool hasPopup() const; int hierarchicalLevel() const; double clickPointX(); double clickPointY(); JSStringRef documentEncoding(); JSStringRef documentURI(); JSStringRef url(); // CSS3-speech properties. JSStringRef speak(); // Table-specific attributes JSStringRef attributesOfColumnHeaders(); JSStringRef attributesOfRowHeaders(); JSStringRef attributesOfColumns(); JSStringRef attributesOfRows(); JSStringRef attributesOfVisibleCells(); JSStringRef attributesOfHeader(); int indexInTable(); JSStringRef rowIndexRange(); JSStringRef columnIndexRange(); int rowCount(); int columnCount(); // Tree/Outline specific attributes AccessibilityUIElement selectedRowAtIndex(unsigned); AccessibilityUIElement disclosedByRow(); AccessibilityUIElement disclosedRowAtIndex(unsigned); AccessibilityUIElement rowAtIndex(unsigned); // ARIA specific AccessibilityUIElement ariaOwnsElementAtIndex(unsigned); AccessibilityUIElement ariaFlowToElementAtIndex(unsigned); // ARIA Drag and Drop bool ariaIsGrabbed() const; // A space concatentated string of all the drop effects. JSStringRef ariaDropEffects() const; // Parameterized attributes int lineForIndex(int); JSStringRef rangeForLine(int); JSStringRef rangeForPosition(int x, int y); JSStringRef boundsForRange(unsigned location, unsigned length); void setSelectedTextRange(unsigned location, unsigned length); JSStringRef stringForRange(unsigned location, unsigned length); JSStringRef attributedStringForRange(unsigned location, unsigned length); bool attributedStringRangeIsMisspelled(unsigned location, unsigned length); AccessibilityUIElement uiElementForSearchPredicate(JSContextRef, AccessibilityUIElement* startElement, bool isDirectionNext, JSValueRef searchKey, JSStringRef searchText); #if PLATFORM(IOS) void elementsForRange(unsigned location, unsigned length, Vector<AccessibilityUIElement>& elements); JSStringRef stringForSelection(); void increaseTextSelection(); void decreaseTextSelection(); AccessibilityUIElement linkedElement(); #endif // Table-specific AccessibilityUIElement cellForColumnAndRow(unsigned column, unsigned row); // Scrollarea-specific AccessibilityUIElement horizontalScrollbar() const; AccessibilityUIElement verticalScrollbar() const; // Text markers. AccessibilityTextMarkerRange textMarkerRangeForElement(AccessibilityUIElement*); AccessibilityTextMarkerRange textMarkerRangeForMarkers(AccessibilityTextMarker* startMarker, AccessibilityTextMarker* endMarker); AccessibilityTextMarker startTextMarkerForTextMarkerRange(AccessibilityTextMarkerRange*); AccessibilityTextMarker endTextMarkerForTextMarkerRange(AccessibilityTextMarkerRange*); AccessibilityTextMarker textMarkerForPoint(int x, int y); AccessibilityTextMarker previousTextMarker(AccessibilityTextMarker*); AccessibilityTextMarker nextTextMarker(AccessibilityTextMarker*); AccessibilityUIElement accessibilityElementForTextMarker(AccessibilityTextMarker*); JSStringRef stringForTextMarkerRange(AccessibilityTextMarkerRange*); int textMarkerRangeLength(AccessibilityTextMarkerRange*); bool attributedStringForTextMarkerRangeContainsAttribute(JSStringRef, AccessibilityTextMarkerRange*); int indexForTextMarker(AccessibilityTextMarker*); bool isTextMarkerValid(AccessibilityTextMarker*); AccessibilityTextMarker textMarkerForIndex(int); void scrollToMakeVisible(); void scrollToMakeVisibleWithSubFocus(int x, int y, int width, int height); void scrollToGlobalPoint(int x, int y); // Notifications // Function callback should take one argument, the name of the notification. bool addNotificationListener(JSObjectRef functionCallback); // Make sure you call remove, because you can't rely on objects being deallocated in a timely fashion. void removeNotificationListener(); #if PLATFORM(IOS) JSStringRef iphoneLabel(); JSStringRef iphoneValue(); JSStringRef iphoneTraits(); JSStringRef iphoneHint(); JSStringRef iphoneIdentifier(); bool iphoneIsElement(); int iphoneElementTextPosition(); int iphoneElementTextLength(); AccessibilityUIElement headerElementAtIndex(unsigned); // This will simulate the accessibilityDidBecomeFocused API in UIKit. void assistiveTechnologySimulatedFocus(); #endif // PLATFORM(IOS) #if PLATFORM(MAC) && !PLATFORM(IOS) // Returns an ordered list of supported actions for an element. JSStringRef supportedActions(); #endif private: static JSClassRef getJSClass(); PlatformUIElement m_element; // A retained, platform specific object used to help manage notifications for this object. #if PLATFORM(MAC) NotificationHandler m_notificationHandler; #endif }; #endif // AccessibilityUIElement_h
[ "JamesMikeDuPont@gmail.com" ]
JamesMikeDuPont@gmail.com
8df1bde7c522a5ada8599530de74f7e801642cb7
6b447308363468aff76c247084c0584b9124f689
/ParseCSVTest/LoadData.h
2b4ebe37f17a52cdd51a301bb863408cf18c04f2
[]
no_license
itsHugo77/RedundancyElimination
92cd4e188aeda6b466fa9dfc724fc92995851575
1331df86ef1906080977a6b20d4221049effbe16
refs/heads/master
2021-08-27T15:17:33.036274
2014-06-12T07:56:38
2014-06-12T07:56:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
903
h
#ifndef LOADDATA_H #define LOADDATA_H #include <stdio.h> #include <map> #include <vector> #include <string> #include "SplitRadius.h" #include "DataStruct.h" using namespace std; // map<string, vector<Session>> is IP - Session relation // map<string, vector<EtherPattern>> is ethernet address connection properities // load csv and store to map // raw csv data is incomplete due to packets loss // error handling and information repairing is needed void LoadSession(const char*, map<string, vector<Session> >&); // write session to disk void StoreSession(const char*, const map<string, vector<Session> >&); // extract session information from IP-Session relationship void LoadEtherPattern(const map<string, vector<Session> >&, map<string, vector<EtherPattern> >&); // write client ethernet and corresponding to disk void StoreEtherPattern(const char*, map<string, vector<EtherPattern> >&); #endif
[ "xinshengchou@gmail.com" ]
xinshengchou@gmail.com
2e1c9ad0df0a33562e9a162be075794637b37af9
28c000caf6617ba2074e0f2a8fc936ccb8c01fb3
/poj/3218/7165678_PE.cc
c667f4c4bc3b91d38958bb68d333c13bd5675776
[]
no_license
ATM006/acm_problem_code
f597fa31033fd663b14d74ad94cae3f7c1629b99
ac40d230cd450bcce60df801eb3b8ce9409dfaac
refs/heads/master
2020-08-31T21:34:00.707529
2014-01-23T05:30:42
2014-01-23T05:30:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,961
cc
#include <cstdio> #include <cstring> char map[5]; struct node { int len; char str[200]; } nod[10010]; int top; void left_align(int lf, int rt, int sum) { printf("%s", nod[lf].str); for(int i=lf+1; i<rt;i++){ printf(" %s", nod[i].str); } puts(""); } void right_align(int lf, int rt, int sum) { sum=75-sum; for(int i=0;i<sum;i++){ putchar(' '); } printf("%s", nod[lf].str); for(int i=lf+1;i<rt;i++){ printf(" %s", nod[i].str); } puts(""); } void center_align(int lf, int rt, int sum) { int y=(75-sum)/2; y=75-sum-y; for(int i=0;i<y;i++){ putchar(' '); } printf("%s", nod[lf].str); for(int i=lf+1;i<rt;i++){ printf(" %s", nod[i].str); } /* y=75-sum-y; for(int i=0;i<y;i++){ putchar(' '); } */ puts(""); } void justify_align(int lf, int rt, int sum) { int y=74-sum+rt-lf; printf("%s", nod[lf].str); if(rt==lf+1)return ; int x=rt-lf-1, z=y/x, cnt=y%x; for(int i=lf+1;i<rt;i++){ for(int j=0;j<z;j++){ putchar(' '); } if(cnt){ cnt--; putchar(' '); } printf("%s", nod[i].str); } puts(""); } void align(int i, int j, int sum) { if (map[0] == 'L') { left_align(i, j+1, sum); } else if (map[0] == 'R') { right_align(i, j+1, sum); } else if (map[0] == 'C') { center_align(i, j+1, sum); } else { justify_align(i, j+1, sum); } } void solve() { int sum = nod[0].len, j = 0; for (int i = 1; i < top; i++) { if (sum + nod[i].len + 1 > 75) { align(j, i - 1, sum); sum = nod[i].len; j = i; } else { sum += nod[i].len + 1; } } align(j, top - 1, sum); } int main() { // freopen("small.in", "r", stdin); // freopen("out.txt", "w", stdout); scanf("%s", map); while (scanf("%s", nod[top].str) != EOF) { nod[top].len = strlen(nod[top].str); top++; } // for(int i=0;i<top;i++){ // printf("%d %s\n", nod[i].len, nod[i].str); // } solve(); return 0; }
[ "wangjunyong@doodlemobile.com" ]
wangjunyong@doodlemobile.com
36df74e45f84870d35b4aed59230b078be22ded6
cd02119141a2258ea2952a5e6ab34736e81dc514
/TikzEdtQt/teglobals.cpp
060c71e6c1fb5ea1e33d7b856511a42371de780d
[]
no_license
kpym/tikzedt
2d5728b68eaad69dc805db05063770507466cd86
85ef5ea19ad4d042416ddf212db45330d68a8fce
refs/heads/master
2021-01-10T07:59:44.179456
2014-03-23T23:04:38
2014-03-23T23:04:38
45,317,452
32
20
null
2016-09-21T11:08:42
2015-10-31T20:36:36
C#
UTF-8
C++
false
false
641
cpp
#include "teglobals.h" TEGlobals::TEGlobals(QObject *parent) : QObject(parent), settings(QString("config.ini"), QSettings::IniFormat) { // copy header makefile QString shfile(appendPath(getSettingsDirectory(), "make_headers.sh")); // if (!QFile::exists(shfile)) // QFile::copy(appendPath(getAppDirectory(), "make_headers.sh"), // shfile); } TEGlobals TEGlobals::Instance; void TEGlobals::setTexPreamble(QString val) { settings.setValue("TexPreamble", val); } QString TEGlobals::getTexPreamble() { QString val = settings.value("TexPreamble", DefaultTexPreamble).toString(); return val; }
[ "t.willwacher@gmail.com" ]
t.willwacher@gmail.com
dbe72eb6e0dce85501eb5f5da2e663bf5cc24f1a
a433291d9fca04da2152636b2cb3f8504246c7f4
/BigRRePair.cpp
c585db5a1e241a136c08dc99f52dadb9b36851e3
[]
no_license
apachecom/rrepair
1fad610d78ce590df364d808f1900cfad84b4ecd
b0e27b562922507d9e07fd5190584001894daaca
refs/heads/master
2021-06-28T04:25:36.579455
2020-08-20T14:53:05
2020-08-20T14:53:05
197,471,858
2
0
null
2020-07-06T16:12:19
2019-07-17T22:27:57
C++
UTF-8
C++
false
false
68
cpp
// // Created by alejandro on 29-07-19. // #include "BigRRePair.h"
[ "=" ]
=
ec64f185e5245677c95d7a1345f70d243329e014
846a7668ac964632bdb6db639ab381be11c13b77
/android/frameworks/av/media/libmedia/MediaDefs.cpp
84eb1e8c9f27c620e5fcb0ba952341a51eeae015
[ "LicenseRef-scancode-unicode", "Apache-2.0" ]
permissive
BPI-SINOVOIP/BPI-A64-Android8
f2900965e96fd6f2a28ced68af668a858b15ebe1
744c72c133b9bf5d2e9efe0ab33e01e6e51d5743
refs/heads/master
2023-05-21T08:02:23.364495
2020-07-15T11:27:51
2020-07-15T11:27:51
143,945,191
2
0
null
null
null
null
UTF-8
C++
false
false
4,014
cpp
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <media/MediaDefs.h> namespace android { const char *MEDIA_MIMETYPE_IMAGE_JPEG = "image/jpeg"; const char *MEDIA_MIMETYPE_VIDEO_VP8 = "video/x-vnd.on2.vp8"; const char *MEDIA_MIMETYPE_VIDEO_VP9 = "video/x-vnd.on2.vp9"; const char *MEDIA_MIMETYPE_VIDEO_AVC = "video/avc"; const char *MEDIA_MIMETYPE_VIDEO_HEVC = "video/hevc"; const char *MEDIA_MIMETYPE_VIDEO_MPEG4 = "video/mp4v-es"; const char *MEDIA_MIMETYPE_VIDEO_H263 = "video/3gpp"; const char *MEDIA_MIMETYPE_VIDEO_MPEG2 = "video/mpeg2"; const char *MEDIA_MIMETYPE_VIDEO_RAW = "video/raw"; const char *MEDIA_MIMETYPE_VIDEO_DOLBY_VISION = "video/dolby-vision"; const char *MEDIA_MIMETYPE_VIDEO_SCRAMBLED = "video/scrambled"; const char *MEDIA_MIMETYPE_VIDEO_WMV1 = "video/wmv1"; const char *MEDIA_MIMETYPE_VIDEO_WMV2 = "video/wmv2"; const char *MEDIA_MIMETYPE_VIDEO_VC1 = "video/wvc1"; //const char *MEDIA_MIMETYPE_VIDEO_VC1 = "video/x-ms-wmv"; //const char *MEDIA_MIMETYPE_VIDEO_VP6 = "video/x-vp6"; const char *MEDIA_MIMETYPE_VIDEO_VP6 = "video/x-vnd.on2.vp6"; const char *MEDIA_MIMETYPE_VIDEO_S263 = "video/flv1"; const char *MEDIA_MIMETYPE_VIDEO_MJPEG = "video/jpeg"; const char *MEDIA_MIMETYPE_VIDEO_MPEG1 = "video/mpeg1"; const char *MEDIA_MIMETYPE_VIDEO_MSMPEG4V1 = "video/x-ms-mpeg4v1"; const char *MEDIA_MIMETYPE_VIDEO_MSMPEG4V2 = "video/x-ms-mpeg4v2"; const char *MEDIA_MIMETYPE_VIDEO_DIVX = "video/divx"; const char *MEDIA_MIMETYPE_VIDEO_XVID = "video/xvid"; const char *MEDIA_MIMETYPE_VIDEO_RXG2 = "video/rvg2"; const char *MEDIA_MIMETYPE_AUDIO_AMR_NB = "audio/3gpp"; const char *MEDIA_MIMETYPE_AUDIO_AMR_WB = "audio/amr-wb"; const char *MEDIA_MIMETYPE_AUDIO_MPEG = "audio/mpeg"; const char *MEDIA_MIMETYPE_AUDIO_MPEG_LAYER_I = "audio/mpeg-L1"; const char *MEDIA_MIMETYPE_AUDIO_MPEG_LAYER_II = "audio/mpeg-L2"; const char *MEDIA_MIMETYPE_AUDIO_MIDI = "audio/midi"; const char *MEDIA_MIMETYPE_AUDIO_AAC = "audio/mp4a-latm"; const char *MEDIA_MIMETYPE_AUDIO_QCELP = "audio/qcelp"; const char *MEDIA_MIMETYPE_AUDIO_VORBIS = "audio/vorbis"; const char *MEDIA_MIMETYPE_AUDIO_OPUS = "audio/opus"; const char *MEDIA_MIMETYPE_AUDIO_G711_ALAW = "audio/g711-alaw"; const char *MEDIA_MIMETYPE_AUDIO_G711_MLAW = "audio/g711-mlaw"; const char *MEDIA_MIMETYPE_AUDIO_RAW = "audio/raw"; const char *MEDIA_MIMETYPE_AUDIO_FLAC = "audio/flac"; const char *MEDIA_MIMETYPE_AUDIO_AAC_ADTS = "audio/aac-adts"; const char *MEDIA_MIMETYPE_AUDIO_MSGSM = "audio/gsm"; const char *MEDIA_MIMETYPE_AUDIO_AC3 = "audio/ac3"; const char *MEDIA_MIMETYPE_AUDIO_EAC3 = "audio/eac3"; const char *MEDIA_MIMETYPE_AUDIO_SCRAMBLED = "audio/scrambled"; const char *MEDIA_MIMETYPE_CONTAINER_MPEG4 = "video/mp4"; const char *MEDIA_MIMETYPE_CONTAINER_WAV = "audio/x-wav"; const char *MEDIA_MIMETYPE_CONTAINER_OGG = "application/ogg"; const char *MEDIA_MIMETYPE_CONTAINER_MATROSKA = "video/x-matroska"; const char *MEDIA_MIMETYPE_CONTAINER_MPEG2TS = "video/mp2ts"; const char *MEDIA_MIMETYPE_CONTAINER_AVI = "video/avi"; const char *MEDIA_MIMETYPE_CONTAINER_MPEG2PS = "video/mp2p"; const char *MEDIA_MIMETYPE_TEXT_3GPP = "text/3gpp-tt"; const char *MEDIA_MIMETYPE_TEXT_SUBRIP = "application/x-subrip"; const char *MEDIA_MIMETYPE_TEXT_VTT = "text/vtt"; const char *MEDIA_MIMETYPE_TEXT_CEA_608 = "text/cea-608"; const char *MEDIA_MIMETYPE_TEXT_CEA_708 = "text/cea-708"; const char *MEDIA_MIMETYPE_DATA_TIMED_ID3 = "application/x-id3v4"; } // namespace android
[ "mingxin.android@gmail.com" ]
mingxin.android@gmail.com